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/BinaryFormat/MachO.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/DebugInfo/DIContext.h"
22 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
23 #include "llvm/Demangle/Demangle.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstPrinter.h"
29 #include "llvm/MC/MCInstrDesc.h"
30 #include "llvm/MC/MCInstrInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCSubtargetInfo.h"
33 #include "llvm/Object/MachO.h"
34 #include "llvm/Object/MachOUniversal.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Endian.h"
39 #include "llvm/Support/Format.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/GraphWriter.h"
42 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <system_error>
51 
52 #ifdef HAVE_LIBXAR
53 extern "C" {
54 #include <xar/xar.h>
55 }
56 #endif
57 
58 using namespace llvm;
59 using namespace object;
60 
61 static cl::opt<bool>
62     UseDbg("g",
63            cl::desc("Print line information from debug info if available"));
64 
65 static cl::opt<std::string> DSYMFile("dsym",
66                                      cl::desc("Use .dSYM file for debug info"));
67 
68 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
69                                      cl::desc("Print full leading address"));
70 
71 static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
72                                       cl::desc("Print no leading headers"));
73 
74 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
75                                      cl::desc("Print Mach-O universal headers "
76                                               "(requires -macho)"));
77 
78 cl::opt<bool>
79     llvm::ArchiveHeaders("archive-headers",
80                          cl::desc("Print archive headers for Mach-O archives "
81                                   "(requires -macho)"));
82 
83 cl::opt<bool>
84     ArchiveMemberOffsets("archive-member-offsets",
85                          cl::desc("Print the offset to each archive member for "
86                                   "Mach-O archives (requires -macho and "
87                                   "-archive-headers)"));
88 
89 cl::opt<bool>
90     llvm::IndirectSymbols("indirect-symbols",
91                           cl::desc("Print indirect symbol table for Mach-O "
92                                    "objects (requires -macho)"));
93 
94 cl::opt<bool>
95     llvm::DataInCode("data-in-code",
96                      cl::desc("Print the data in code table for Mach-O objects "
97                               "(requires -macho)"));
98 
99 cl::opt<bool>
100     llvm::LinkOptHints("link-opt-hints",
101                        cl::desc("Print the linker optimization hints for "
102                                 "Mach-O objects (requires -macho)"));
103 
104 cl::opt<bool>
105     llvm::InfoPlist("info-plist",
106                     cl::desc("Print the info plist section as strings for "
107                              "Mach-O objects (requires -macho)"));
108 
109 cl::opt<bool>
110     llvm::DylibsUsed("dylibs-used",
111                      cl::desc("Print the shared libraries used for linked "
112                               "Mach-O files (requires -macho)"));
113 
114 cl::opt<bool>
115     llvm::DylibId("dylib-id",
116                   cl::desc("Print the shared library's id for the dylib Mach-O "
117                            "file (requires -macho)"));
118 
119 cl::opt<bool>
120     llvm::NonVerbose("non-verbose",
121                      cl::desc("Print the info for Mach-O objects in "
122                               "non-verbose or numeric form (requires -macho)"));
123 
124 cl::opt<bool>
125     llvm::ObjcMetaData("objc-meta-data",
126                        cl::desc("Print the Objective-C runtime meta data for "
127                                 "Mach-O files (requires -macho)"));
128 
129 cl::opt<std::string> llvm::DisSymName(
130     "dis-symname",
131     cl::desc("disassemble just this symbol's instructions (requires -macho)"));
132 
133 static cl::opt<bool> NoSymbolicOperands(
134     "no-symbolic-operands",
135     cl::desc("do not symbolic operands when disassembling (requires -macho)"));
136 
137 static cl::list<std::string>
138     ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
139               cl::ZeroOrMore);
140 
141 bool ArchAll = false;
142 
143 static std::string ThumbTripleName;
144 
145 static const Target *GetTarget(const MachOObjectFile *MachOObj,
146                                const char **McpuDefault,
147                                const Target **ThumbTarget) {
148   // Figure out the target triple.
149   llvm::Triple TT(TripleName);
150   if (TripleName.empty()) {
151     TT = MachOObj->getArchTriple(McpuDefault);
152     TripleName = TT.str();
153   }
154 
155   if (TT.getArch() == Triple::arm) {
156     // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
157     // that support ARM are also capable of Thumb mode.
158     llvm::Triple ThumbTriple = TT;
159     std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
160     ThumbTriple.setArchName(ThumbName);
161     ThumbTripleName = ThumbTriple.str();
162   }
163 
164   // Get the target specific parser.
165   std::string Error;
166   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
167   if (TheTarget && ThumbTripleName.empty())
168     return TheTarget;
169 
170   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
171   if (*ThumbTarget)
172     return TheTarget;
173 
174   errs() << "llvm-objdump: error: unable to get target for '";
175   if (!TheTarget)
176     errs() << TripleName;
177   else
178     errs() << ThumbTripleName;
179   errs() << "', see --version and --triple.\n";
180   return nullptr;
181 }
182 
183 struct SymbolSorter {
184   bool operator()(const SymbolRef &A, const SymbolRef &B) {
185     Expected<SymbolRef::Type> ATypeOrErr = A.getType();
186     if (!ATypeOrErr)
187       report_error(A.getObject()->getFileName(), ATypeOrErr.takeError());
188     SymbolRef::Type AType = *ATypeOrErr;
189     Expected<SymbolRef::Type> BTypeOrErr = B.getType();
190     if (!BTypeOrErr)
191       report_error(B.getObject()->getFileName(), BTypeOrErr.takeError());
192     SymbolRef::Type BType = *BTypeOrErr;
193     uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
194     uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
195     return AAddr < BAddr;
196   }
197 };
198 
199 // Types for the storted data in code table that is built before disassembly
200 // and the predicate function to sort them.
201 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
202 typedef std::vector<DiceTableEntry> DiceTable;
203 typedef DiceTable::iterator dice_table_iterator;
204 
205 #ifdef HAVE_LIBXAR
206 namespace {
207 struct ScopedXarFile {
208   xar_t xar;
209   ScopedXarFile(const char *filename, int32_t flags)
210       : xar(xar_open(filename, flags)) {}
211   ~ScopedXarFile() {
212     if (xar)
213       xar_close(xar);
214   }
215   ScopedXarFile(const ScopedXarFile &) = delete;
216   ScopedXarFile &operator=(const ScopedXarFile &) = delete;
217   operator xar_t() { return xar; }
218 };
219 
220 struct ScopedXarIter {
221   xar_iter_t iter;
222   ScopedXarIter() : iter(xar_iter_new()) {}
223   ~ScopedXarIter() {
224     if (iter)
225       xar_iter_free(iter);
226   }
227   ScopedXarIter(const ScopedXarIter &) = delete;
228   ScopedXarIter &operator=(const ScopedXarIter &) = delete;
229   operator xar_iter_t() { return iter; }
230 };
231 } // namespace
232 #endif // defined(HAVE_LIBXAR)
233 
234 // This is used to search for a data in code table entry for the PC being
235 // disassembled.  The j parameter has the PC in j.first.  A single data in code
236 // table entry can cover many bytes for each of its Kind's.  So if the offset,
237 // aka the i.first value, of the data in code table entry plus its Length
238 // covers the PC being searched for this will return true.  If not it will
239 // return false.
240 static bool compareDiceTableEntries(const DiceTableEntry &i,
241                                     const DiceTableEntry &j) {
242   uint16_t Length;
243   i.second.getLength(Length);
244 
245   return j.first >= i.first && j.first < i.first + Length;
246 }
247 
248 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
249                                unsigned short Kind) {
250   uint32_t Value, Size = 1;
251 
252   switch (Kind) {
253   default:
254   case MachO::DICE_KIND_DATA:
255     if (Length >= 4) {
256       if (!NoShowRawInsn)
257         dumpBytes(makeArrayRef(bytes, 4), outs());
258       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
259       outs() << "\t.long " << Value;
260       Size = 4;
261     } else if (Length >= 2) {
262       if (!NoShowRawInsn)
263         dumpBytes(makeArrayRef(bytes, 2), outs());
264       Value = bytes[1] << 8 | bytes[0];
265       outs() << "\t.short " << Value;
266       Size = 2;
267     } else {
268       if (!NoShowRawInsn)
269         dumpBytes(makeArrayRef(bytes, 2), outs());
270       Value = bytes[0];
271       outs() << "\t.byte " << Value;
272       Size = 1;
273     }
274     if (Kind == MachO::DICE_KIND_DATA)
275       outs() << "\t@ KIND_DATA\n";
276     else
277       outs() << "\t@ data in code kind = " << Kind << "\n";
278     break;
279   case MachO::DICE_KIND_JUMP_TABLE8:
280     if (!NoShowRawInsn)
281       dumpBytes(makeArrayRef(bytes, 1), outs());
282     Value = bytes[0];
283     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
284     Size = 1;
285     break;
286   case MachO::DICE_KIND_JUMP_TABLE16:
287     if (!NoShowRawInsn)
288       dumpBytes(makeArrayRef(bytes, 2), outs());
289     Value = bytes[1] << 8 | bytes[0];
290     outs() << "\t.short " << format("%5u", Value & 0xffff)
291            << "\t@ KIND_JUMP_TABLE16\n";
292     Size = 2;
293     break;
294   case MachO::DICE_KIND_JUMP_TABLE32:
295   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
296     if (!NoShowRawInsn)
297       dumpBytes(makeArrayRef(bytes, 4), outs());
298     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
299     outs() << "\t.long " << Value;
300     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
301       outs() << "\t@ KIND_JUMP_TABLE32\n";
302     else
303       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
304     Size = 4;
305     break;
306   }
307   return Size;
308 }
309 
310 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
311                                   std::vector<SectionRef> &Sections,
312                                   std::vector<SymbolRef> &Symbols,
313                                   SmallVectorImpl<uint64_t> &FoundFns,
314                                   uint64_t &BaseSegmentAddress) {
315   for (const SymbolRef &Symbol : MachOObj->symbols()) {
316     Expected<StringRef> SymName = Symbol.getName();
317     if (!SymName)
318       report_error(MachOObj->getFileName(), SymName.takeError());
319     if (!SymName->startswith("ltmp"))
320       Symbols.push_back(Symbol);
321   }
322 
323   for (const SectionRef &Section : MachOObj->sections()) {
324     StringRef SectName;
325     Section.getName(SectName);
326     Sections.push_back(Section);
327   }
328 
329   bool BaseSegmentAddressSet = false;
330   for (const auto &Command : MachOObj->load_commands()) {
331     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
332       // We found a function starts segment, parse the addresses for later
333       // consumption.
334       MachO::linkedit_data_command LLC =
335           MachOObj->getLinkeditDataLoadCommand(Command);
336 
337       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
338     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
339       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
340       StringRef SegName = SLC.segname;
341       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
342         BaseSegmentAddressSet = true;
343         BaseSegmentAddress = SLC.vmaddr;
344       }
345     }
346   }
347 }
348 
349 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
350                                      uint32_t n, uint32_t count,
351                                      uint32_t stride, uint64_t addr) {
352   MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
353   uint32_t nindirectsyms = Dysymtab.nindirectsyms;
354   if (n > nindirectsyms)
355     outs() << " (entries start past the end of the indirect symbol "
356               "table) (reserved1 field greater than the table size)";
357   else if (n + count > nindirectsyms)
358     outs() << " (entries extends past the end of the indirect symbol "
359               "table)";
360   outs() << "\n";
361   uint32_t cputype = O->getHeader().cputype;
362   if (cputype & MachO::CPU_ARCH_ABI64)
363     outs() << "address            index";
364   else
365     outs() << "address    index";
366   if (verbose)
367     outs() << " name\n";
368   else
369     outs() << "\n";
370   for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
371     if (cputype & MachO::CPU_ARCH_ABI64)
372       outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
373     else
374       outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
375     MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
376     uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
377     if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
378       outs() << "LOCAL\n";
379       continue;
380     }
381     if (indirect_symbol ==
382         (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
383       outs() << "LOCAL ABSOLUTE\n";
384       continue;
385     }
386     if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
387       outs() << "ABSOLUTE\n";
388       continue;
389     }
390     outs() << format("%5u ", indirect_symbol);
391     if (verbose) {
392       MachO::symtab_command Symtab = O->getSymtabLoadCommand();
393       if (indirect_symbol < Symtab.nsyms) {
394         symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
395         SymbolRef Symbol = *Sym;
396         Expected<StringRef> SymName = Symbol.getName();
397         if (!SymName)
398           report_error(O->getFileName(), SymName.takeError());
399         outs() << *SymName;
400       } else {
401         outs() << "?";
402       }
403     }
404     outs() << "\n";
405   }
406 }
407 
408 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
409   for (const auto &Load : O->load_commands()) {
410     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
411       MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
412       for (unsigned J = 0; J < Seg.nsects; ++J) {
413         MachO::section_64 Sec = O->getSection64(Load, J);
414         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
415         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
416             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
417             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
418             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
419             section_type == MachO::S_SYMBOL_STUBS) {
420           uint32_t stride;
421           if (section_type == MachO::S_SYMBOL_STUBS)
422             stride = Sec.reserved2;
423           else
424             stride = 8;
425           if (stride == 0) {
426             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
427                    << Sec.sectname << ") "
428                    << "(size of stubs in reserved2 field is zero)\n";
429             continue;
430           }
431           uint32_t count = Sec.size / stride;
432           outs() << "Indirect symbols for (" << Sec.segname << ","
433                  << Sec.sectname << ") " << count << " entries";
434           uint32_t n = Sec.reserved1;
435           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
436         }
437       }
438     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
439       MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
440       for (unsigned J = 0; J < Seg.nsects; ++J) {
441         MachO::section Sec = O->getSection(Load, J);
442         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
443         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
444             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
445             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
446             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
447             section_type == MachO::S_SYMBOL_STUBS) {
448           uint32_t stride;
449           if (section_type == MachO::S_SYMBOL_STUBS)
450             stride = Sec.reserved2;
451           else
452             stride = 4;
453           if (stride == 0) {
454             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
455                    << Sec.sectname << ") "
456                    << "(size of stubs in reserved2 field is zero)\n";
457             continue;
458           }
459           uint32_t count = Sec.size / stride;
460           outs() << "Indirect symbols for (" << Sec.segname << ","
461                  << Sec.sectname << ") " << count << " entries";
462           uint32_t n = Sec.reserved1;
463           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
464         }
465       }
466     }
467   }
468 }
469 
470 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
471   static char const *generic_r_types[] = {
472     "VANILLA ", "PAIR    ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV     ",
473     "  6 (?) ", "  7 (?) ", "  8 (?) ", "  9 (?) ", " 10 (?) ", " 11 (?) ",
474     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
475   };
476   static char const *x86_64_r_types[] = {
477     "UNSIGND ", "SIGNED  ", "BRANCH  ", "GOT_LD  ", "GOT     ", "SUB     ",
478     "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV     ", " 10 (?) ", " 11 (?) ",
479     " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
480   };
481   static char const *arm_r_types[] = {
482     "VANILLA ", "PAIR    ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
483     "BR24    ", "T_BR22  ", "T_BR32  ", "HALF    ", "HALFDIF ",
484     " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
485   };
486   static char const *arm64_r_types[] = {
487     "UNSIGND ", "SUB     ", "BR26    ", "PAGE21  ", "PAGOF12 ",
488     "GOTLDP  ", "GOTLDPOF", "PTRTGOT ", "TLVLDP  ", "TLVLDPOF",
489     "ADDEND  ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
490   };
491 
492   if (r_type > 0xf){
493     outs() << format("%-7u", r_type) << " ";
494     return;
495   }
496   switch (cputype) {
497     case MachO::CPU_TYPE_I386:
498       outs() << generic_r_types[r_type];
499       break;
500     case MachO::CPU_TYPE_X86_64:
501       outs() << x86_64_r_types[r_type];
502       break;
503     case MachO::CPU_TYPE_ARM:
504       outs() << arm_r_types[r_type];
505       break;
506     case MachO::CPU_TYPE_ARM64:
507       outs() << arm64_r_types[r_type];
508       break;
509     default:
510       outs() << format("%-7u ", r_type);
511   }
512 }
513 
514 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
515                          const unsigned r_length, const bool previous_arm_half){
516   if (cputype == MachO::CPU_TYPE_ARM &&
517       (r_type == llvm::MachO::ARM_RELOC_HALF ||
518        r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
519        previous_arm_half == true)) {
520     if ((r_length & 0x1) == 0)
521       outs() << "lo/";
522     else
523       outs() << "hi/";
524     if ((r_length & 0x1) == 0)
525       outs() << "arm ";
526     else
527       outs() << "thm ";
528   } else {
529     switch (r_length) {
530       case 0:
531         outs() << "byte   ";
532         break;
533       case 1:
534         outs() << "word   ";
535         break;
536       case 2:
537         outs() << "long   ";
538         break;
539       case 3:
540         if (cputype == MachO::CPU_TYPE_X86_64)
541           outs() << "quad   ";
542         else
543           outs() << format("?(%2d)  ", r_length);
544         break;
545       default:
546         outs() << format("?(%2d)  ", r_length);
547     }
548   }
549 }
550 
551 static void PrintRelocationEntries(const MachOObjectFile *O,
552                                    const relocation_iterator Begin,
553                                    const relocation_iterator End,
554                                    const uint64_t cputype,
555                                    const bool verbose) {
556   const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
557   bool previous_arm_half = false;
558   bool previous_sectdiff = false;
559   uint32_t sectdiff_r_type = 0;
560 
561   for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
562     const DataRefImpl Rel = Reloc->getRawDataRefImpl();
563     const MachO::any_relocation_info RE = O->getRelocation(Rel);
564     const unsigned r_type = O->getAnyRelocationType(RE);
565     const bool r_scattered = O->isRelocationScattered(RE);
566     const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
567     const unsigned r_length = O->getAnyRelocationLength(RE);
568     const unsigned r_address = O->getAnyRelocationAddress(RE);
569     const bool r_extern = (r_scattered ? false :
570                            O->getPlainRelocationExternal(RE));
571     const uint32_t r_value = (r_scattered ?
572                               O->getScatteredRelocationValue(RE) : 0);
573     const unsigned r_symbolnum = (r_scattered ? 0 :
574                                   O->getPlainRelocationSymbolNum(RE));
575 
576     if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
577       if (verbose) {
578         // scattered: address
579         if ((cputype == MachO::CPU_TYPE_I386 &&
580              r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
581             (cputype == MachO::CPU_TYPE_ARM &&
582              r_type == llvm::MachO::ARM_RELOC_PAIR))
583           outs() << "         ";
584         else
585           outs() << format("%08x ", (unsigned int)r_address);
586 
587         // scattered: pcrel
588         if (r_pcrel)
589           outs() << "True  ";
590         else
591           outs() << "False ";
592 
593         // scattered: length
594         PrintRLength(cputype, r_type, r_length, previous_arm_half);
595 
596         // scattered: extern & type
597         outs() << "n/a    ";
598         PrintRType(cputype, r_type);
599 
600         // scattered: scattered & value
601         outs() << format("True      0x%08x", (unsigned int)r_value);
602         if (previous_sectdiff == false) {
603           if ((cputype == MachO::CPU_TYPE_ARM &&
604                r_type == llvm::MachO::ARM_RELOC_PAIR))
605             outs() << format(" half = 0x%04x ", (unsigned int)r_address);
606         }
607         else if (cputype == MachO::CPU_TYPE_ARM &&
608                  sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
609           outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
610         if ((cputype == MachO::CPU_TYPE_I386 &&
611              (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
612               r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
613             (cputype == MachO::CPU_TYPE_ARM &&
614              (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
615               sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
616               sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
617                previous_sectdiff = true;
618                sectdiff_r_type = r_type;
619              }
620         else {
621           previous_sectdiff = false;
622           sectdiff_r_type = 0;
623         }
624         if (cputype == MachO::CPU_TYPE_ARM &&
625             (r_type == llvm::MachO::ARM_RELOC_HALF ||
626              r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
627           previous_arm_half = true;
628         else
629           previous_arm_half = false;
630         outs() << "\n";
631       }
632       else {
633         // scattered: address pcrel length extern type scattered value
634         outs() << format("%08x %1d     %-2d     n/a    %-7d 1         0x%08x\n",
635                          (unsigned int)r_address, r_pcrel, r_length, r_type,
636                          (unsigned int)r_value);
637       }
638     }
639     else {
640       if (verbose) {
641         // plain: address
642         if (cputype == MachO::CPU_TYPE_ARM &&
643             r_type == llvm::MachO::ARM_RELOC_PAIR)
644           outs() << "         ";
645         else
646           outs() << format("%08x ", (unsigned int)r_address);
647 
648         // plain: pcrel
649         if (r_pcrel)
650           outs() << "True  ";
651         else
652           outs() << "False ";
653 
654         // plain: length
655         PrintRLength(cputype, r_type, r_length, previous_arm_half);
656 
657         if (r_extern) {
658           // plain: extern & type & scattered
659           outs() << "True   ";
660           PrintRType(cputype, r_type);
661           outs() << "False     ";
662 
663           // plain: symbolnum/value
664           if (r_symbolnum > Symtab.nsyms)
665             outs() << format("?(%d)\n", r_symbolnum);
666           else {
667             SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
668             Expected<StringRef> SymNameNext = Symbol.getName();
669             const char *name = NULL;
670             if (SymNameNext)
671               name = SymNameNext->data();
672             if (name == NULL)
673               outs() << format("?(%d)\n", r_symbolnum);
674             else
675               outs() << name << "\n";
676           }
677         }
678         else {
679           // plain: extern & type & scattered
680           outs() << "False  ";
681           PrintRType(cputype, r_type);
682           outs() << "False     ";
683 
684           // plain: symbolnum/value
685           if (cputype == MachO::CPU_TYPE_ARM &&
686                    r_type == llvm::MachO::ARM_RELOC_PAIR)
687             outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
688           else if (cputype == MachO::CPU_TYPE_ARM64 &&
689                    r_type == llvm::MachO::ARM64_RELOC_ADDEND)
690             outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
691           else {
692             outs() << format("%d ", r_symbolnum);
693             if (r_symbolnum == llvm::MachO::R_ABS)
694               outs() << "R_ABS\n";
695             else {
696               // in this case, r_symbolnum is actually a 1-based section number
697               uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
698               if (r_symbolnum > 0 && r_symbolnum <= nsects) {
699                 llvm::object::DataRefImpl DRI;
700                 DRI.d.a = r_symbolnum-1;
701                 StringRef SegName = O->getSectionFinalSegmentName(DRI);
702                 StringRef SectName;
703                 if (O->getSectionName(DRI, SectName))
704                   outs() << "(?,?)\n";
705                 else
706                   outs() << "(" << SegName << "," << SectName << ")\n";
707               }
708               else {
709                 outs() << "(?,?)\n";
710               }
711             }
712           }
713         }
714         if (cputype == MachO::CPU_TYPE_ARM &&
715             (r_type == llvm::MachO::ARM_RELOC_HALF ||
716              r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
717           previous_arm_half = true;
718         else
719           previous_arm_half = false;
720       }
721       else {
722         // plain: address pcrel length extern type scattered symbolnum/section
723         outs() << format("%08x %1d     %-2d     %1d      %-7d 0         %d\n",
724                          (unsigned int)r_address, r_pcrel, r_length, r_extern,
725                          r_type, r_symbolnum);
726       }
727     }
728   }
729 }
730 
731 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
732   const uint64_t cputype = O->getHeader().cputype;
733   const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
734   if (Dysymtab.nextrel != 0) {
735     outs() << "External relocation information " << Dysymtab.nextrel
736            << " entries";
737     outs() << "\naddress  pcrel length extern type    scattered "
738               "symbolnum/value\n";
739     PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
740                            verbose);
741   }
742   if (Dysymtab.nlocrel != 0) {
743     outs() << format("Local relocation information %u entries",
744                      Dysymtab.nlocrel);
745     outs() << "\naddress  pcrel length extern type    scattered "
746               "symbolnum/value\n";
747     PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
748                            verbose);
749   }
750   for (const auto &Load : O->load_commands()) {
751     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
752       const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
753       for (unsigned J = 0; J < Seg.nsects; ++J) {
754         const MachO::section_64 Sec = O->getSection64(Load, J);
755         if (Sec.nreloc != 0) {
756           DataRefImpl DRI;
757           DRI.d.a = J;
758           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
759           StringRef SectName;
760           if (O->getSectionName(DRI, SectName))
761             outs() << "Relocation information (" << SegName << ",?) "
762                    << format("%u entries", Sec.nreloc);
763           else
764             outs() << "Relocation information (" << SegName << ","
765                    << SectName << format(") %u entries", Sec.nreloc);
766           outs() << "\naddress  pcrel length extern type    scattered "
767                     "symbolnum/value\n";
768           PrintRelocationEntries(O, O->section_rel_begin(DRI),
769                                  O->section_rel_end(DRI), cputype, verbose);
770         }
771       }
772     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
773       const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
774       for (unsigned J = 0; J < Seg.nsects; ++J) {
775         const MachO::section Sec = O->getSection(Load, J);
776         if (Sec.nreloc != 0) {
777           DataRefImpl DRI;
778           DRI.d.a = J;
779           const StringRef SegName = O->getSectionFinalSegmentName(DRI);
780           StringRef SectName;
781           if (O->getSectionName(DRI, SectName))
782             outs() << "Relocation information (" << SegName << ",?) "
783                    << format("%u entries", Sec.nreloc);
784           else
785             outs() << "Relocation information (" << SegName << ","
786                    << SectName << format(") %u entries", Sec.nreloc);
787           outs() << "\naddress  pcrel length extern type    scattered "
788                     "symbolnum/value\n";
789           PrintRelocationEntries(O, O->section_rel_begin(DRI),
790                                  O->section_rel_end(DRI), cputype, verbose);
791         }
792       }
793     }
794   }
795 }
796 
797 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
798   MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
799   uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
800   outs() << "Data in code table (" << nentries << " entries)\n";
801   outs() << "offset     length kind\n";
802   for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
803        ++DI) {
804     uint32_t Offset;
805     DI->getOffset(Offset);
806     outs() << format("0x%08" PRIx32, Offset) << " ";
807     uint16_t Length;
808     DI->getLength(Length);
809     outs() << format("%6u", Length) << " ";
810     uint16_t Kind;
811     DI->getKind(Kind);
812     if (verbose) {
813       switch (Kind) {
814       case MachO::DICE_KIND_DATA:
815         outs() << "DATA";
816         break;
817       case MachO::DICE_KIND_JUMP_TABLE8:
818         outs() << "JUMP_TABLE8";
819         break;
820       case MachO::DICE_KIND_JUMP_TABLE16:
821         outs() << "JUMP_TABLE16";
822         break;
823       case MachO::DICE_KIND_JUMP_TABLE32:
824         outs() << "JUMP_TABLE32";
825         break;
826       case MachO::DICE_KIND_ABS_JUMP_TABLE32:
827         outs() << "ABS_JUMP_TABLE32";
828         break;
829       default:
830         outs() << format("0x%04" PRIx32, Kind);
831         break;
832       }
833     } else
834       outs() << format("0x%04" PRIx32, Kind);
835     outs() << "\n";
836   }
837 }
838 
839 static void PrintLinkOptHints(MachOObjectFile *O) {
840   MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
841   const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
842   uint32_t nloh = LohLC.datasize;
843   outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
844   for (uint32_t i = 0; i < nloh;) {
845     unsigned n;
846     uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
847     i += n;
848     outs() << "    identifier " << identifier << " ";
849     if (i >= nloh)
850       return;
851     switch (identifier) {
852     case 1:
853       outs() << "AdrpAdrp\n";
854       break;
855     case 2:
856       outs() << "AdrpLdr\n";
857       break;
858     case 3:
859       outs() << "AdrpAddLdr\n";
860       break;
861     case 4:
862       outs() << "AdrpLdrGotLdr\n";
863       break;
864     case 5:
865       outs() << "AdrpAddStr\n";
866       break;
867     case 6:
868       outs() << "AdrpLdrGotStr\n";
869       break;
870     case 7:
871       outs() << "AdrpAdd\n";
872       break;
873     case 8:
874       outs() << "AdrpLdrGot\n";
875       break;
876     default:
877       outs() << "Unknown identifier value\n";
878       break;
879     }
880     uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
881     i += n;
882     outs() << "    narguments " << narguments << "\n";
883     if (i >= nloh)
884       return;
885 
886     for (uint32_t j = 0; j < narguments; j++) {
887       uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
888       i += n;
889       outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
890       if (i >= nloh)
891         return;
892     }
893   }
894 }
895 
896 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
897   unsigned Index = 0;
898   for (const auto &Load : O->load_commands()) {
899     if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
900         (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
901                      Load.C.cmd == MachO::LC_LOAD_DYLIB ||
902                      Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
903                      Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
904                      Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
905                      Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
906       MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
907       if (dl.dylib.name < dl.cmdsize) {
908         const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
909         if (JustId)
910           outs() << p << "\n";
911         else {
912           outs() << "\t" << p;
913           outs() << " (compatibility version "
914                  << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
915                  << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
916                  << (dl.dylib.compatibility_version & 0xff) << ",";
917           outs() << " current version "
918                  << ((dl.dylib.current_version >> 16) & 0xffff) << "."
919                  << ((dl.dylib.current_version >> 8) & 0xff) << "."
920                  << (dl.dylib.current_version & 0xff) << ")\n";
921         }
922       } else {
923         outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
924         if (Load.C.cmd == MachO::LC_ID_DYLIB)
925           outs() << "LC_ID_DYLIB ";
926         else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
927           outs() << "LC_LOAD_DYLIB ";
928         else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
929           outs() << "LC_LOAD_WEAK_DYLIB ";
930         else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
931           outs() << "LC_LAZY_LOAD_DYLIB ";
932         else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
933           outs() << "LC_REEXPORT_DYLIB ";
934         else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
935           outs() << "LC_LOAD_UPWARD_DYLIB ";
936         else
937           outs() << "LC_??? ";
938         outs() << "command " << Index++ << "\n";
939       }
940     }
941   }
942 }
943 
944 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
945 
946 static void CreateSymbolAddressMap(MachOObjectFile *O,
947                                    SymbolAddressMap *AddrMap) {
948   // Create a map of symbol addresses to symbol names.
949   for (const SymbolRef &Symbol : O->symbols()) {
950     Expected<SymbolRef::Type> STOrErr = Symbol.getType();
951     if (!STOrErr)
952       report_error(O->getFileName(), STOrErr.takeError());
953     SymbolRef::Type ST = *STOrErr;
954     if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
955         ST == SymbolRef::ST_Other) {
956       uint64_t Address = Symbol.getValue();
957       Expected<StringRef> SymNameOrErr = Symbol.getName();
958       if (!SymNameOrErr)
959         report_error(O->getFileName(), SymNameOrErr.takeError());
960       StringRef SymName = *SymNameOrErr;
961       if (!SymName.startswith(".objc"))
962         (*AddrMap)[Address] = SymName;
963     }
964   }
965 }
966 
967 // GuessSymbolName is passed the address of what might be a symbol and a
968 // pointer to the SymbolAddressMap.  It returns the name of a symbol
969 // with that address or nullptr if no symbol is found with that address.
970 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
971   const char *SymbolName = nullptr;
972   // A DenseMap can't lookup up some values.
973   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
974     StringRef name = AddrMap->lookup(value);
975     if (!name.empty())
976       SymbolName = name.data();
977   }
978   return SymbolName;
979 }
980 
981 static void DumpCstringChar(const char c) {
982   char p[2];
983   p[0] = c;
984   p[1] = '\0';
985   outs().write_escaped(p);
986 }
987 
988 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
989                                uint32_t sect_size, uint64_t sect_addr,
990                                bool print_addresses) {
991   for (uint32_t i = 0; i < sect_size; i++) {
992     if (print_addresses) {
993       if (O->is64Bit())
994         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
995       else
996         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
997     }
998     for (; i < sect_size && sect[i] != '\0'; i++)
999       DumpCstringChar(sect[i]);
1000     if (i < sect_size && sect[i] == '\0')
1001       outs() << "\n";
1002   }
1003 }
1004 
1005 static void DumpLiteral4(uint32_t l, float f) {
1006   outs() << format("0x%08" PRIx32, l);
1007   if ((l & 0x7f800000) != 0x7f800000)
1008     outs() << format(" (%.16e)\n", f);
1009   else {
1010     if (l == 0x7f800000)
1011       outs() << " (+Infinity)\n";
1012     else if (l == 0xff800000)
1013       outs() << " (-Infinity)\n";
1014     else if ((l & 0x00400000) == 0x00400000)
1015       outs() << " (non-signaling Not-a-Number)\n";
1016     else
1017       outs() << " (signaling Not-a-Number)\n";
1018   }
1019 }
1020 
1021 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1022                                 uint32_t sect_size, uint64_t sect_addr,
1023                                 bool print_addresses) {
1024   for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1025     if (print_addresses) {
1026       if (O->is64Bit())
1027         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1028       else
1029         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1030     }
1031     float f;
1032     memcpy(&f, sect + i, sizeof(float));
1033     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1034       sys::swapByteOrder(f);
1035     uint32_t l;
1036     memcpy(&l, sect + i, sizeof(uint32_t));
1037     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1038       sys::swapByteOrder(l);
1039     DumpLiteral4(l, f);
1040   }
1041 }
1042 
1043 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1044                          double d) {
1045   outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1046   uint32_t Hi, Lo;
1047   Hi = (O->isLittleEndian()) ? l1 : l0;
1048   Lo = (O->isLittleEndian()) ? l0 : l1;
1049 
1050   // Hi is the high word, so this is equivalent to if(isfinite(d))
1051   if ((Hi & 0x7ff00000) != 0x7ff00000)
1052     outs() << format(" (%.16e)\n", d);
1053   else {
1054     if (Hi == 0x7ff00000 && Lo == 0)
1055       outs() << " (+Infinity)\n";
1056     else if (Hi == 0xfff00000 && Lo == 0)
1057       outs() << " (-Infinity)\n";
1058     else if ((Hi & 0x00080000) == 0x00080000)
1059       outs() << " (non-signaling Not-a-Number)\n";
1060     else
1061       outs() << " (signaling Not-a-Number)\n";
1062   }
1063 }
1064 
1065 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1066                                 uint32_t sect_size, uint64_t sect_addr,
1067                                 bool print_addresses) {
1068   for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1069     if (print_addresses) {
1070       if (O->is64Bit())
1071         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1072       else
1073         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1074     }
1075     double d;
1076     memcpy(&d, sect + i, sizeof(double));
1077     if (O->isLittleEndian() != sys::IsLittleEndianHost)
1078       sys::swapByteOrder(d);
1079     uint32_t l0, l1;
1080     memcpy(&l0, sect + i, sizeof(uint32_t));
1081     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1082     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1083       sys::swapByteOrder(l0);
1084       sys::swapByteOrder(l1);
1085     }
1086     DumpLiteral8(O, l0, l1, d);
1087   }
1088 }
1089 
1090 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1091   outs() << format("0x%08" PRIx32, l0) << " ";
1092   outs() << format("0x%08" PRIx32, l1) << " ";
1093   outs() << format("0x%08" PRIx32, l2) << " ";
1094   outs() << format("0x%08" PRIx32, l3) << "\n";
1095 }
1096 
1097 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1098                                  uint32_t sect_size, uint64_t sect_addr,
1099                                  bool print_addresses) {
1100   for (uint32_t i = 0; i < sect_size; i += 16) {
1101     if (print_addresses) {
1102       if (O->is64Bit())
1103         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1104       else
1105         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1106     }
1107     uint32_t l0, l1, l2, l3;
1108     memcpy(&l0, sect + i, sizeof(uint32_t));
1109     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1110     memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1111     memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1112     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1113       sys::swapByteOrder(l0);
1114       sys::swapByteOrder(l1);
1115       sys::swapByteOrder(l2);
1116       sys::swapByteOrder(l3);
1117     }
1118     DumpLiteral16(l0, l1, l2, l3);
1119   }
1120 }
1121 
1122 static void DumpLiteralPointerSection(MachOObjectFile *O,
1123                                       const SectionRef &Section,
1124                                       const char *sect, uint32_t sect_size,
1125                                       uint64_t sect_addr,
1126                                       bool print_addresses) {
1127   // Collect the literal sections in this Mach-O file.
1128   std::vector<SectionRef> LiteralSections;
1129   for (const SectionRef &Section : O->sections()) {
1130     DataRefImpl Ref = Section.getRawDataRefImpl();
1131     uint32_t section_type;
1132     if (O->is64Bit()) {
1133       const MachO::section_64 Sec = O->getSection64(Ref);
1134       section_type = Sec.flags & MachO::SECTION_TYPE;
1135     } else {
1136       const MachO::section Sec = O->getSection(Ref);
1137       section_type = Sec.flags & MachO::SECTION_TYPE;
1138     }
1139     if (section_type == MachO::S_CSTRING_LITERALS ||
1140         section_type == MachO::S_4BYTE_LITERALS ||
1141         section_type == MachO::S_8BYTE_LITERALS ||
1142         section_type == MachO::S_16BYTE_LITERALS)
1143       LiteralSections.push_back(Section);
1144   }
1145 
1146   // Set the size of the literal pointer.
1147   uint32_t lp_size = O->is64Bit() ? 8 : 4;
1148 
1149   // Collect the external relocation symbols for the literal pointers.
1150   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1151   for (const RelocationRef &Reloc : Section.relocations()) {
1152     DataRefImpl Rel;
1153     MachO::any_relocation_info RE;
1154     bool isExtern = false;
1155     Rel = Reloc.getRawDataRefImpl();
1156     RE = O->getRelocation(Rel);
1157     isExtern = O->getPlainRelocationExternal(RE);
1158     if (isExtern) {
1159       uint64_t RelocOffset = Reloc.getOffset();
1160       symbol_iterator RelocSym = Reloc.getSymbol();
1161       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1162     }
1163   }
1164   array_pod_sort(Relocs.begin(), Relocs.end());
1165 
1166   // Dump each literal pointer.
1167   for (uint32_t i = 0; i < sect_size; i += lp_size) {
1168     if (print_addresses) {
1169       if (O->is64Bit())
1170         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
1171       else
1172         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
1173     }
1174     uint64_t lp;
1175     if (O->is64Bit()) {
1176       memcpy(&lp, sect + i, sizeof(uint64_t));
1177       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1178         sys::swapByteOrder(lp);
1179     } else {
1180       uint32_t li;
1181       memcpy(&li, sect + i, sizeof(uint32_t));
1182       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1183         sys::swapByteOrder(li);
1184       lp = li;
1185     }
1186 
1187     // First look for an external relocation entry for this literal pointer.
1188     auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1189       return P.first == i;
1190     });
1191     if (Reloc != Relocs.end()) {
1192       symbol_iterator RelocSym = Reloc->second;
1193       Expected<StringRef> SymName = RelocSym->getName();
1194       if (!SymName)
1195         report_error(O->getFileName(), SymName.takeError());
1196       outs() << "external relocation entry for symbol:" << *SymName << "\n";
1197       continue;
1198     }
1199 
1200     // For local references see what the section the literal pointer points to.
1201     auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1202       return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1203     });
1204     if (Sect == LiteralSections.end()) {
1205       outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1206       continue;
1207     }
1208 
1209     uint64_t SectAddress = Sect->getAddress();
1210     uint64_t SectSize = Sect->getSize();
1211 
1212     StringRef SectName;
1213     Sect->getName(SectName);
1214     DataRefImpl Ref = Sect->getRawDataRefImpl();
1215     StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1216     outs() << SegmentName << ":" << SectName << ":";
1217 
1218     uint32_t section_type;
1219     if (O->is64Bit()) {
1220       const MachO::section_64 Sec = O->getSection64(Ref);
1221       section_type = Sec.flags & MachO::SECTION_TYPE;
1222     } else {
1223       const MachO::section Sec = O->getSection(Ref);
1224       section_type = Sec.flags & MachO::SECTION_TYPE;
1225     }
1226 
1227     StringRef BytesStr;
1228     Sect->getContents(BytesStr);
1229     const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1230 
1231     switch (section_type) {
1232     case MachO::S_CSTRING_LITERALS:
1233       for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1234            i++) {
1235         DumpCstringChar(Contents[i]);
1236       }
1237       outs() << "\n";
1238       break;
1239     case MachO::S_4BYTE_LITERALS:
1240       float f;
1241       memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1242       uint32_t l;
1243       memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1244       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1245         sys::swapByteOrder(f);
1246         sys::swapByteOrder(l);
1247       }
1248       DumpLiteral4(l, f);
1249       break;
1250     case MachO::S_8BYTE_LITERALS: {
1251       double d;
1252       memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1253       uint32_t l0, l1;
1254       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1255       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1256              sizeof(uint32_t));
1257       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1258         sys::swapByteOrder(f);
1259         sys::swapByteOrder(l0);
1260         sys::swapByteOrder(l1);
1261       }
1262       DumpLiteral8(O, l0, l1, d);
1263       break;
1264     }
1265     case MachO::S_16BYTE_LITERALS: {
1266       uint32_t l0, l1, l2, l3;
1267       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1268       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1269              sizeof(uint32_t));
1270       memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1271              sizeof(uint32_t));
1272       memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1273              sizeof(uint32_t));
1274       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1275         sys::swapByteOrder(l0);
1276         sys::swapByteOrder(l1);
1277         sys::swapByteOrder(l2);
1278         sys::swapByteOrder(l3);
1279       }
1280       DumpLiteral16(l0, l1, l2, l3);
1281       break;
1282     }
1283     }
1284   }
1285 }
1286 
1287 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
1288                                        uint32_t sect_size, uint64_t sect_addr,
1289                                        SymbolAddressMap *AddrMap,
1290                                        bool verbose) {
1291   uint32_t stride;
1292   stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1293   for (uint32_t i = 0; i < sect_size; i += stride) {
1294     const char *SymbolName = nullptr;
1295     if (O->is64Bit()) {
1296       outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1297       uint64_t pointer_value;
1298       memcpy(&pointer_value, sect + i, stride);
1299       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1300         sys::swapByteOrder(pointer_value);
1301       outs() << format("0x%016" PRIx64, pointer_value);
1302       if (verbose)
1303         SymbolName = GuessSymbolName(pointer_value, AddrMap);
1304     } else {
1305       outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1306       uint32_t pointer_value;
1307       memcpy(&pointer_value, sect + i, stride);
1308       if (O->isLittleEndian() != sys::IsLittleEndianHost)
1309         sys::swapByteOrder(pointer_value);
1310       outs() << format("0x%08" PRIx32, pointer_value);
1311       if (verbose)
1312         SymbolName = GuessSymbolName(pointer_value, AddrMap);
1313     }
1314     if (SymbolName)
1315       outs() << " " << SymbolName;
1316     outs() << "\n";
1317   }
1318 }
1319 
1320 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1321                                    uint32_t size, uint64_t addr) {
1322   uint32_t cputype = O->getHeader().cputype;
1323   if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1324     uint32_t j;
1325     for (uint32_t i = 0; i < size; i += j, addr += j) {
1326       if (O->is64Bit())
1327         outs() << format("%016" PRIx64, addr) << "\t";
1328       else
1329         outs() << format("%08" PRIx64, addr) << "\t";
1330       for (j = 0; j < 16 && i + j < size; j++) {
1331         uint8_t byte_word = *(sect + i + j);
1332         outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1333       }
1334       outs() << "\n";
1335     }
1336   } else {
1337     uint32_t j;
1338     for (uint32_t i = 0; i < size; i += j, addr += j) {
1339       if (O->is64Bit())
1340         outs() << format("%016" PRIx64, addr) << "\t";
1341       else
1342         outs() << format("%08" PRIx64, addr) << "\t";
1343       for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1344            j += sizeof(int32_t)) {
1345         if (i + j + sizeof(int32_t) <= size) {
1346           uint32_t long_word;
1347           memcpy(&long_word, sect + i + j, sizeof(int32_t));
1348           if (O->isLittleEndian() != sys::IsLittleEndianHost)
1349             sys::swapByteOrder(long_word);
1350           outs() << format("%08" PRIx32, long_word) << " ";
1351         } else {
1352           for (uint32_t k = 0; i + j + k < size; k++) {
1353             uint8_t byte_word = *(sect + i + j + k);
1354             outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1355           }
1356         }
1357       }
1358       outs() << "\n";
1359     }
1360   }
1361 }
1362 
1363 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1364                              StringRef DisSegName, StringRef DisSectName);
1365 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1366                                 uint32_t size, uint32_t addr);
1367 #ifdef HAVE_LIBXAR
1368 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1369                                 uint32_t size, bool verbose,
1370                                 bool PrintXarHeader, bool PrintXarFileHeaders,
1371                                 std::string XarMemberName);
1372 #endif // defined(HAVE_LIBXAR)
1373 
1374 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1375                                 bool verbose) {
1376   SymbolAddressMap AddrMap;
1377   if (verbose)
1378     CreateSymbolAddressMap(O, &AddrMap);
1379 
1380   for (unsigned i = 0; i < FilterSections.size(); ++i) {
1381     StringRef DumpSection = FilterSections[i];
1382     std::pair<StringRef, StringRef> DumpSegSectName;
1383     DumpSegSectName = DumpSection.split(',');
1384     StringRef DumpSegName, DumpSectName;
1385     if (DumpSegSectName.second.size()) {
1386       DumpSegName = DumpSegSectName.first;
1387       DumpSectName = DumpSegSectName.second;
1388     } else {
1389       DumpSegName = "";
1390       DumpSectName = DumpSegSectName.first;
1391     }
1392     for (const SectionRef &Section : O->sections()) {
1393       StringRef SectName;
1394       Section.getName(SectName);
1395       DataRefImpl Ref = Section.getRawDataRefImpl();
1396       StringRef SegName = O->getSectionFinalSegmentName(Ref);
1397       if ((DumpSegName.empty() || SegName == DumpSegName) &&
1398           (SectName == DumpSectName)) {
1399 
1400         uint32_t section_flags;
1401         if (O->is64Bit()) {
1402           const MachO::section_64 Sec = O->getSection64(Ref);
1403           section_flags = Sec.flags;
1404 
1405         } else {
1406           const MachO::section Sec = O->getSection(Ref);
1407           section_flags = Sec.flags;
1408         }
1409         uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1410 
1411         StringRef BytesStr;
1412         Section.getContents(BytesStr);
1413         const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1414         uint32_t sect_size = BytesStr.size();
1415         uint64_t sect_addr = Section.getAddress();
1416 
1417         outs() << "Contents of (" << SegName << "," << SectName
1418                << ") section\n";
1419 
1420         if (verbose) {
1421           if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1422               (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1423             DisassembleMachO(Filename, O, SegName, SectName);
1424             continue;
1425           }
1426           if (SegName == "__TEXT" && SectName == "__info_plist") {
1427             outs() << sect;
1428             continue;
1429           }
1430           if (SegName == "__OBJC" && SectName == "__protocol") {
1431             DumpProtocolSection(O, sect, sect_size, sect_addr);
1432             continue;
1433           }
1434 #ifdef HAVE_LIBXAR
1435           if (SegName == "__LLVM" && SectName == "__bundle") {
1436             DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1437                                ArchiveHeaders, "");
1438             continue;
1439           }
1440 #endif // defined(HAVE_LIBXAR)
1441           switch (section_type) {
1442           case MachO::S_REGULAR:
1443             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1444             break;
1445           case MachO::S_ZEROFILL:
1446             outs() << "zerofill section and has no contents in the file\n";
1447             break;
1448           case MachO::S_CSTRING_LITERALS:
1449             DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1450             break;
1451           case MachO::S_4BYTE_LITERALS:
1452             DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1453             break;
1454           case MachO::S_8BYTE_LITERALS:
1455             DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1456             break;
1457           case MachO::S_16BYTE_LITERALS:
1458             DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1459             break;
1460           case MachO::S_LITERAL_POINTERS:
1461             DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1462                                       !NoLeadingAddr);
1463             break;
1464           case MachO::S_MOD_INIT_FUNC_POINTERS:
1465           case MachO::S_MOD_TERM_FUNC_POINTERS:
1466             DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1467                                        verbose);
1468             break;
1469           default:
1470             outs() << "Unknown section type ("
1471                    << format("0x%08" PRIx32, section_type) << ")\n";
1472             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1473             break;
1474           }
1475         } else {
1476           if (section_type == MachO::S_ZEROFILL)
1477             outs() << "zerofill section and has no contents in the file\n";
1478           else
1479             DumpRawSectionContents(O, sect, sect_size, sect_addr);
1480         }
1481       }
1482     }
1483   }
1484 }
1485 
1486 static void DumpInfoPlistSectionContents(StringRef Filename,
1487                                          MachOObjectFile *O) {
1488   for (const SectionRef &Section : O->sections()) {
1489     StringRef SectName;
1490     Section.getName(SectName);
1491     DataRefImpl Ref = Section.getRawDataRefImpl();
1492     StringRef SegName = O->getSectionFinalSegmentName(Ref);
1493     if (SegName == "__TEXT" && SectName == "__info_plist") {
1494       if (!NoLeadingHeaders)
1495         outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1496       StringRef BytesStr;
1497       Section.getContents(BytesStr);
1498       const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1499       outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1500       return;
1501     }
1502   }
1503 }
1504 
1505 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1506 // and if it is and there is a list of architecture flags is specified then
1507 // check to make sure this Mach-O file is one of those architectures or all
1508 // architectures were specified.  If not then an error is generated and this
1509 // routine returns false.  Else it returns true.
1510 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1511   auto *MachO = dyn_cast<MachOObjectFile>(O);
1512 
1513   if (!MachO || ArchAll || ArchFlags.empty())
1514     return true;
1515 
1516   MachO::mach_header H;
1517   MachO::mach_header_64 H_64;
1518   Triple T;
1519   const char *McpuDefault, *ArchFlag;
1520   if (MachO->is64Bit()) {
1521     H_64 = MachO->MachOObjectFile::getHeader64();
1522     T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1523                                        &McpuDefault, &ArchFlag);
1524   } else {
1525     H = MachO->MachOObjectFile::getHeader();
1526     T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1527                                        &McpuDefault, &ArchFlag);
1528   }
1529   const std::string ArchFlagName(ArchFlag);
1530   if (none_of(ArchFlags, [&](const std::string &Name) {
1531         return Name == ArchFlagName;
1532       })) {
1533     errs() << "llvm-objdump: " + Filename + ": No architecture specified.\n";
1534     return false;
1535   }
1536   return true;
1537 }
1538 
1539 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1540 
1541 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1542 // archive member and or in a slice of a universal file.  It prints the
1543 // the file name and header info and then processes it according to the
1544 // command line options.
1545 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1546                          StringRef ArchiveMemberName = StringRef(),
1547                          StringRef ArchitectureName = StringRef()) {
1548   // If we are doing some processing here on the Mach-O file print the header
1549   // info.  And don't print it otherwise like in the case of printing the
1550   // UniversalHeaders or ArchiveHeaders.
1551   if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1552       Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1553       DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1554       (FilterSections.size() != 0)) {
1555     if (!NoLeadingHeaders) {
1556       outs() << Name;
1557       if (!ArchiveMemberName.empty())
1558         outs() << '(' << ArchiveMemberName << ')';
1559       if (!ArchitectureName.empty())
1560         outs() << " (architecture " << ArchitectureName << ")";
1561       outs() << ":\n";
1562     }
1563   }
1564   // To use the report_error() form with an ArchiveName and FileName set
1565   // these up based on what is passed for Name and ArchiveMemberName.
1566   StringRef ArchiveName;
1567   StringRef FileName;
1568   if (!ArchiveMemberName.empty()) {
1569     ArchiveName = Name;
1570     FileName = ArchiveMemberName;
1571   } else {
1572     ArchiveName = StringRef();
1573     FileName = Name;
1574   }
1575 
1576   // If we need the symbol table to do the operation then check it here to
1577   // produce a good error message as to where the Mach-O file comes from in
1578   // the error message.
1579   if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1580       UnwindInfo)
1581     if (Error Err = MachOOF->checkSymbolTable())
1582       report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
1583 
1584   if (Disassemble) {
1585     if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1586         MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1587       DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1588     else
1589       DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1590   }
1591   if (IndirectSymbols)
1592     PrintIndirectSymbols(MachOOF, !NonVerbose);
1593   if (DataInCode)
1594     PrintDataInCodeTable(MachOOF, !NonVerbose);
1595   if (LinkOptHints)
1596     PrintLinkOptHints(MachOOF);
1597   if (Relocations)
1598     PrintRelocations(MachOOF, !NonVerbose);
1599   if (SectionHeaders)
1600     PrintSectionHeaders(MachOOF);
1601   if (SectionContents)
1602     PrintSectionContents(MachOOF);
1603   if (FilterSections.size() != 0)
1604     DumpSectionContents(FileName, MachOOF, !NonVerbose);
1605   if (InfoPlist)
1606     DumpInfoPlistSectionContents(FileName, MachOOF);
1607   if (DylibsUsed)
1608     PrintDylibs(MachOOF, false);
1609   if (DylibId)
1610     PrintDylibs(MachOOF, true);
1611   if (SymbolTable)
1612     PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1613   if (UnwindInfo)
1614     printMachOUnwindInfo(MachOOF);
1615   if (PrivateHeaders) {
1616     printMachOFileHeader(MachOOF);
1617     printMachOLoadCommands(MachOOF);
1618   }
1619   if (FirstPrivateHeader)
1620     printMachOFileHeader(MachOOF);
1621   if (ObjcMetaData)
1622     printObjcMetaData(MachOOF, !NonVerbose);
1623   if (ExportsTrie)
1624     printExportsTrie(MachOOF);
1625   if (Rebase)
1626     printRebaseTable(MachOOF);
1627   if (Bind)
1628     printBindTable(MachOOF);
1629   if (LazyBind)
1630     printLazyBindTable(MachOOF);
1631   if (WeakBind)
1632     printWeakBindTable(MachOOF);
1633 
1634   if (DwarfDumpType != DIDT_Null) {
1635     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
1636     // Dump the complete DWARF structure.
1637     DIDumpOptions DumpOpts;
1638     DumpOpts.DumpType = DwarfDumpType;
1639     DICtx->dump(outs(), DumpOpts);
1640   }
1641 }
1642 
1643 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1644 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1645   outs() << "    cputype (" << cputype << ")\n";
1646   outs() << "    cpusubtype (" << cpusubtype << ")\n";
1647 }
1648 
1649 // printCPUType() helps print_fat_headers by printing the cputype and
1650 // pusubtype (symbolically for the one's it knows about).
1651 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1652   switch (cputype) {
1653   case MachO::CPU_TYPE_I386:
1654     switch (cpusubtype) {
1655     case MachO::CPU_SUBTYPE_I386_ALL:
1656       outs() << "    cputype CPU_TYPE_I386\n";
1657       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
1658       break;
1659     default:
1660       printUnknownCPUType(cputype, cpusubtype);
1661       break;
1662     }
1663     break;
1664   case MachO::CPU_TYPE_X86_64:
1665     switch (cpusubtype) {
1666     case MachO::CPU_SUBTYPE_X86_64_ALL:
1667       outs() << "    cputype CPU_TYPE_X86_64\n";
1668       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1669       break;
1670     case MachO::CPU_SUBTYPE_X86_64_H:
1671       outs() << "    cputype CPU_TYPE_X86_64\n";
1672       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
1673       break;
1674     default:
1675       printUnknownCPUType(cputype, cpusubtype);
1676       break;
1677     }
1678     break;
1679   case MachO::CPU_TYPE_ARM:
1680     switch (cpusubtype) {
1681     case MachO::CPU_SUBTYPE_ARM_ALL:
1682       outs() << "    cputype CPU_TYPE_ARM\n";
1683       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1684       break;
1685     case MachO::CPU_SUBTYPE_ARM_V4T:
1686       outs() << "    cputype CPU_TYPE_ARM\n";
1687       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1688       break;
1689     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1690       outs() << "    cputype CPU_TYPE_ARM\n";
1691       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1692       break;
1693     case MachO::CPU_SUBTYPE_ARM_XSCALE:
1694       outs() << "    cputype CPU_TYPE_ARM\n";
1695       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1696       break;
1697     case MachO::CPU_SUBTYPE_ARM_V6:
1698       outs() << "    cputype CPU_TYPE_ARM\n";
1699       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
1700       break;
1701     case MachO::CPU_SUBTYPE_ARM_V6M:
1702       outs() << "    cputype CPU_TYPE_ARM\n";
1703       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1704       break;
1705     case MachO::CPU_SUBTYPE_ARM_V7:
1706       outs() << "    cputype CPU_TYPE_ARM\n";
1707       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
1708       break;
1709     case MachO::CPU_SUBTYPE_ARM_V7EM:
1710       outs() << "    cputype CPU_TYPE_ARM\n";
1711       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1712       break;
1713     case MachO::CPU_SUBTYPE_ARM_V7K:
1714       outs() << "    cputype CPU_TYPE_ARM\n";
1715       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1716       break;
1717     case MachO::CPU_SUBTYPE_ARM_V7M:
1718       outs() << "    cputype CPU_TYPE_ARM\n";
1719       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1720       break;
1721     case MachO::CPU_SUBTYPE_ARM_V7S:
1722       outs() << "    cputype CPU_TYPE_ARM\n";
1723       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1724       break;
1725     default:
1726       printUnknownCPUType(cputype, cpusubtype);
1727       break;
1728     }
1729     break;
1730   case MachO::CPU_TYPE_ARM64:
1731     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1732     case MachO::CPU_SUBTYPE_ARM64_ALL:
1733       outs() << "    cputype CPU_TYPE_ARM64\n";
1734       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1735       break;
1736     default:
1737       printUnknownCPUType(cputype, cpusubtype);
1738       break;
1739     }
1740     break;
1741   default:
1742     printUnknownCPUType(cputype, cpusubtype);
1743     break;
1744   }
1745 }
1746 
1747 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1748                                        bool verbose) {
1749   outs() << "Fat headers\n";
1750   if (verbose) {
1751     if (UB->getMagic() == MachO::FAT_MAGIC)
1752       outs() << "fat_magic FAT_MAGIC\n";
1753     else // UB->getMagic() == MachO::FAT_MAGIC_64
1754       outs() << "fat_magic FAT_MAGIC_64\n";
1755   } else
1756     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1757 
1758   uint32_t nfat_arch = UB->getNumberOfObjects();
1759   StringRef Buf = UB->getData();
1760   uint64_t size = Buf.size();
1761   uint64_t big_size = sizeof(struct MachO::fat_header) +
1762                       nfat_arch * sizeof(struct MachO::fat_arch);
1763   outs() << "nfat_arch " << UB->getNumberOfObjects();
1764   if (nfat_arch == 0)
1765     outs() << " (malformed, contains zero architecture types)\n";
1766   else if (big_size > size)
1767     outs() << " (malformed, architectures past end of file)\n";
1768   else
1769     outs() << "\n";
1770 
1771   for (uint32_t i = 0; i < nfat_arch; ++i) {
1772     MachOUniversalBinary::ObjectForArch OFA(UB, i);
1773     uint32_t cputype = OFA.getCPUType();
1774     uint32_t cpusubtype = OFA.getCPUSubType();
1775     outs() << "architecture ";
1776     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1777       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1778       uint32_t other_cputype = other_OFA.getCPUType();
1779       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1780       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1781           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1782               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1783         outs() << "(illegal duplicate architecture) ";
1784         break;
1785       }
1786     }
1787     if (verbose) {
1788       outs() << OFA.getArchFlagName() << "\n";
1789       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1790     } else {
1791       outs() << i << "\n";
1792       outs() << "    cputype " << cputype << "\n";
1793       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1794              << "\n";
1795     }
1796     if (verbose &&
1797         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1798       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
1799     else
1800       outs() << "    capabilities "
1801              << format("0x%" PRIx32,
1802                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1803     outs() << "    offset " << OFA.getOffset();
1804     if (OFA.getOffset() > size)
1805       outs() << " (past end of file)";
1806     if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1807       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1808     outs() << "\n";
1809     outs() << "    size " << OFA.getSize();
1810     big_size = OFA.getOffset() + OFA.getSize();
1811     if (big_size > size)
1812       outs() << " (past end of file)";
1813     outs() << "\n";
1814     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1815            << ")\n";
1816   }
1817 }
1818 
1819 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1820                               bool verbose, bool print_offset,
1821                               StringRef ArchitectureName = StringRef()) {
1822   if (print_offset)
1823     outs() << C.getChildOffset() << "\t";
1824   Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1825   if (!ModeOrErr)
1826     report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1827   sys::fs::perms Mode = ModeOrErr.get();
1828   if (verbose) {
1829     // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1830     // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1831     outs() << "-";
1832     outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1833     outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1834     outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1835     outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1836     outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1837     outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1838     outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1839     outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1840     outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1841   } else {
1842     outs() << format("0%o ", Mode);
1843   }
1844 
1845   Expected<unsigned> UIDOrErr = C.getUID();
1846   if (!UIDOrErr)
1847     report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1848   unsigned UID = UIDOrErr.get();
1849   outs() << format("%3d/", UID);
1850   Expected<unsigned> GIDOrErr = C.getGID();
1851   if (!GIDOrErr)
1852     report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1853   unsigned GID = GIDOrErr.get();
1854   outs() << format("%-3d ", GID);
1855   Expected<uint64_t> Size = C.getRawSize();
1856   if (!Size)
1857     report_error(Filename, C, Size.takeError(), ArchitectureName);
1858   outs() << format("%5" PRId64, Size.get()) << " ";
1859 
1860   StringRef RawLastModified = C.getRawLastModified();
1861   if (verbose) {
1862     unsigned Seconds;
1863     if (RawLastModified.getAsInteger(10, Seconds))
1864       outs() << "(date: \"" << RawLastModified
1865              << "\" contains non-decimal chars) ";
1866     else {
1867       // Since cime(3) returns a 26 character string of the form:
1868       // "Sun Sep 16 01:03:52 1973\n\0"
1869       // just print 24 characters.
1870       time_t t = Seconds;
1871       outs() << format("%.24s ", ctime(&t));
1872     }
1873   } else {
1874     outs() << RawLastModified << " ";
1875   }
1876 
1877   if (verbose) {
1878     Expected<StringRef> NameOrErr = C.getName();
1879     if (!NameOrErr) {
1880       consumeError(NameOrErr.takeError());
1881       Expected<StringRef> NameOrErr = C.getRawName();
1882       if (!NameOrErr)
1883         report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1884       StringRef RawName = NameOrErr.get();
1885       outs() << RawName << "\n";
1886     } else {
1887       StringRef Name = NameOrErr.get();
1888       outs() << Name << "\n";
1889     }
1890   } else {
1891     Expected<StringRef> NameOrErr = C.getRawName();
1892     if (!NameOrErr)
1893       report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1894     StringRef RawName = NameOrErr.get();
1895     outs() << RawName << "\n";
1896   }
1897 }
1898 
1899 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1900                                 bool print_offset,
1901                                 StringRef ArchitectureName = StringRef()) {
1902   Error Err = Error::success();
1903   ;
1904   for (const auto &C : A->children(Err, false))
1905     printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1906 
1907   if (Err)
1908     report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
1909 }
1910 
1911 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1912 // -arch flags selecting just those slices as specified by them and also parses
1913 // archive files.  Then for each individual Mach-O file ProcessMachO() is
1914 // called to process the file based on the command line options.
1915 void llvm::ParseInputMachO(StringRef Filename) {
1916   // Check for -arch all and verifiy the -arch flags are valid.
1917   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1918     if (ArchFlags[i] == "all") {
1919       ArchAll = true;
1920     } else {
1921       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1922         errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1923                       "'for the -arch option\n";
1924         return;
1925       }
1926     }
1927   }
1928 
1929   // Attempt to open the binary.
1930   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1931   if (!BinaryOrErr) {
1932     if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1933       report_error(Filename, std::move(E));
1934     else
1935       outs() << Filename << ": is not an object file\n";
1936     return;
1937   }
1938   Binary &Bin = *BinaryOrErr.get().getBinary();
1939 
1940   if (Archive *A = dyn_cast<Archive>(&Bin)) {
1941     outs() << "Archive : " << Filename << "\n";
1942     if (ArchiveHeaders)
1943       printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1944 
1945     Error Err = Error::success();
1946     for (auto &C : A->children(Err)) {
1947       Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1948       if (!ChildOrErr) {
1949         if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1950           report_error(Filename, C, std::move(E));
1951         continue;
1952       }
1953       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1954         if (!checkMachOAndArchFlags(O, Filename))
1955           return;
1956         ProcessMachO(Filename, O, O->getFileName());
1957       }
1958     }
1959     if (Err)
1960       report_error(Filename, std::move(Err));
1961     return;
1962   }
1963   if (UniversalHeaders) {
1964     if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1965       printMachOUniversalHeaders(UB, !NonVerbose);
1966   }
1967   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1968     // If we have a list of architecture flags specified dump only those.
1969     if (!ArchAll && ArchFlags.size() != 0) {
1970       // Look for a slice in the universal binary that matches each ArchFlag.
1971       bool ArchFound;
1972       for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1973         ArchFound = false;
1974         for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1975                                                    E = UB->end_objects();
1976              I != E; ++I) {
1977           if (ArchFlags[i] == I->getArchFlagName()) {
1978             ArchFound = true;
1979             Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
1980                 I->getAsObjectFile();
1981             std::string ArchitectureName = "";
1982             if (ArchFlags.size() > 1)
1983               ArchitectureName = I->getArchFlagName();
1984             if (ObjOrErr) {
1985               ObjectFile &O = *ObjOrErr.get();
1986               if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1987                 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1988             } else if (auto E = isNotObjectErrorInvalidFileType(
1989                        ObjOrErr.takeError())) {
1990               report_error(Filename, StringRef(), std::move(E),
1991                            ArchitectureName);
1992               continue;
1993             } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1994                            I->getAsArchive()) {
1995               std::unique_ptr<Archive> &A = *AOrErr;
1996               outs() << "Archive : " << Filename;
1997               if (!ArchitectureName.empty())
1998                 outs() << " (architecture " << ArchitectureName << ")";
1999               outs() << "\n";
2000               if (ArchiveHeaders)
2001                 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2002                                     ArchiveMemberOffsets, ArchitectureName);
2003               Error Err = Error::success();
2004               for (auto &C : A->children(Err)) {
2005                 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2006                 if (!ChildOrErr) {
2007                   if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2008                     report_error(Filename, C, std::move(E), ArchitectureName);
2009                   continue;
2010                 }
2011                 if (MachOObjectFile *O =
2012                         dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2013                   ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2014               }
2015               if (Err)
2016                 report_error(Filename, std::move(Err));
2017             } else {
2018               consumeError(AOrErr.takeError());
2019               error("Mach-O universal file: " + Filename + " for " +
2020                     "architecture " + StringRef(I->getArchFlagName()) +
2021                     " is not a Mach-O file or an archive file");
2022             }
2023           }
2024         }
2025         if (!ArchFound) {
2026           errs() << "llvm-objdump: file: " + Filename + " does not contain "
2027                  << "architecture: " + ArchFlags[i] + "\n";
2028           return;
2029         }
2030       }
2031       return;
2032     }
2033     // No architecture flags were specified so if this contains a slice that
2034     // matches the host architecture dump only that.
2035     if (!ArchAll) {
2036       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2037                                                  E = UB->end_objects();
2038            I != E; ++I) {
2039         if (MachOObjectFile::getHostArch().getArchName() ==
2040             I->getArchFlagName()) {
2041           Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2042           std::string ArchiveName;
2043           ArchiveName.clear();
2044           if (ObjOrErr) {
2045             ObjectFile &O = *ObjOrErr.get();
2046             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2047               ProcessMachO(Filename, MachOOF);
2048           } else if (auto E = isNotObjectErrorInvalidFileType(
2049                      ObjOrErr.takeError())) {
2050             report_error(Filename, std::move(E));
2051             continue;
2052           } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2053                          I->getAsArchive()) {
2054             std::unique_ptr<Archive> &A = *AOrErr;
2055             outs() << "Archive : " << Filename << "\n";
2056             if (ArchiveHeaders)
2057               printArchiveHeaders(Filename, A.get(), !NonVerbose,
2058                                   ArchiveMemberOffsets);
2059             Error Err = Error::success();
2060             for (auto &C : A->children(Err)) {
2061               Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2062               if (!ChildOrErr) {
2063                 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2064                   report_error(Filename, C, std::move(E));
2065                 continue;
2066               }
2067               if (MachOObjectFile *O =
2068                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2069                 ProcessMachO(Filename, O, O->getFileName());
2070             }
2071             if (Err)
2072               report_error(Filename, std::move(Err));
2073           } else {
2074             consumeError(AOrErr.takeError());
2075             error("Mach-O universal file: " + Filename + " for architecture " +
2076                   StringRef(I->getArchFlagName()) +
2077                   " is not a Mach-O file or an archive file");
2078           }
2079           return;
2080         }
2081       }
2082     }
2083     // Either all architectures have been specified or none have been specified
2084     // and this does not contain the host architecture so dump all the slices.
2085     bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2086     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2087                                                E = UB->end_objects();
2088          I != E; ++I) {
2089       Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2090       std::string ArchitectureName = "";
2091       if (moreThanOneArch)
2092         ArchitectureName = I->getArchFlagName();
2093       if (ObjOrErr) {
2094         ObjectFile &Obj = *ObjOrErr.get();
2095         if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2096           ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2097       } else if (auto E = isNotObjectErrorInvalidFileType(
2098                  ObjOrErr.takeError())) {
2099         report_error(StringRef(), Filename, std::move(E), ArchitectureName);
2100         continue;
2101       } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2102                    I->getAsArchive()) {
2103         std::unique_ptr<Archive> &A = *AOrErr;
2104         outs() << "Archive : " << Filename;
2105         if (!ArchitectureName.empty())
2106           outs() << " (architecture " << ArchitectureName << ")";
2107         outs() << "\n";
2108         if (ArchiveHeaders)
2109           printArchiveHeaders(Filename, A.get(), !NonVerbose,
2110                               ArchiveMemberOffsets, ArchitectureName);
2111         Error Err = Error::success();
2112         for (auto &C : A->children(Err)) {
2113           Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2114           if (!ChildOrErr) {
2115             if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2116               report_error(Filename, C, std::move(E), ArchitectureName);
2117             continue;
2118           }
2119           if (MachOObjectFile *O =
2120                   dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2121             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2122               ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2123                            ArchitectureName);
2124           }
2125         }
2126         if (Err)
2127           report_error(Filename, std::move(Err));
2128       } else {
2129         consumeError(AOrErr.takeError());
2130         error("Mach-O universal file: " + Filename + " for architecture " +
2131               StringRef(I->getArchFlagName()) +
2132               " is not a Mach-O file or an archive file");
2133       }
2134     }
2135     return;
2136   }
2137   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2138     if (!checkMachOAndArchFlags(O, Filename))
2139       return;
2140     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
2141       ProcessMachO(Filename, MachOOF);
2142     } else
2143       errs() << "llvm-objdump: '" << Filename << "': "
2144              << "Object is not a Mach-O file type.\n";
2145     return;
2146   }
2147   llvm_unreachable("Input object can't be invalid at this point");
2148 }
2149 
2150 // The block of info used by the Symbolizer call backs.
2151 struct DisassembleInfo {
2152   DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2153                   std::vector<SectionRef> *Sections, bool verbose)
2154     : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2155   bool verbose;
2156   MachOObjectFile *O;
2157   SectionRef S;
2158   SymbolAddressMap *AddrMap;
2159   std::vector<SectionRef> *Sections;
2160   const char *class_name = nullptr;
2161   const char *selector_name = nullptr;
2162   char *method = nullptr;
2163   char *demangled_name = nullptr;
2164   uint64_t adrp_addr = 0;
2165   uint32_t adrp_inst = 0;
2166   std::unique_ptr<SymbolAddressMap> bindtable;
2167   uint32_t depth = 0;
2168 };
2169 
2170 // SymbolizerGetOpInfo() is the operand information call back function.
2171 // This is called to get the symbolic information for operand(s) of an
2172 // instruction when it is being done.  This routine does this from
2173 // the relocation information, symbol table, etc. That block of information
2174 // is a pointer to the struct DisassembleInfo that was passed when the
2175 // disassembler context was created and passed to back to here when
2176 // called back by the disassembler for instruction operands that could have
2177 // relocation information. The address of the instruction containing operand is
2178 // at the Pc parameter.  The immediate value the operand has is passed in
2179 // op_info->Value and is at Offset past the start of the instruction and has a
2180 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2181 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2182 // names and addends of the symbolic expression to add for the operand.  The
2183 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2184 // information is returned then this function returns 1 else it returns 0.
2185 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2186                                uint64_t Size, int TagType, void *TagBuf) {
2187   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2188   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2189   uint64_t value = op_info->Value;
2190 
2191   // Make sure all fields returned are zero if we don't set them.
2192   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2193   op_info->Value = value;
2194 
2195   // If the TagType is not the value 1 which it code knows about or if no
2196   // verbose symbolic information is wanted then just return 0, indicating no
2197   // information is being returned.
2198   if (TagType != 1 || !info->verbose)
2199     return 0;
2200 
2201   unsigned int Arch = info->O->getArch();
2202   if (Arch == Triple::x86) {
2203     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2204       return 0;
2205     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2206       // TODO:
2207       // Search the external relocation entries of a fully linked image
2208       // (if any) for an entry that matches this segment offset.
2209       // uint32_t seg_offset = (Pc + Offset);
2210       return 0;
2211     }
2212     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2213     // for an entry for this section offset.
2214     uint32_t sect_addr = info->S.getAddress();
2215     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2216     bool reloc_found = false;
2217     DataRefImpl Rel;
2218     MachO::any_relocation_info RE;
2219     bool isExtern = false;
2220     SymbolRef Symbol;
2221     bool r_scattered = false;
2222     uint32_t r_value, pair_r_value, r_type;
2223     for (const RelocationRef &Reloc : info->S.relocations()) {
2224       uint64_t RelocOffset = Reloc.getOffset();
2225       if (RelocOffset == sect_offset) {
2226         Rel = Reloc.getRawDataRefImpl();
2227         RE = info->O->getRelocation(Rel);
2228         r_type = info->O->getAnyRelocationType(RE);
2229         r_scattered = info->O->isRelocationScattered(RE);
2230         if (r_scattered) {
2231           r_value = info->O->getScatteredRelocationValue(RE);
2232           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2233               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2234             DataRefImpl RelNext = Rel;
2235             info->O->moveRelocationNext(RelNext);
2236             MachO::any_relocation_info RENext;
2237             RENext = info->O->getRelocation(RelNext);
2238             if (info->O->isRelocationScattered(RENext))
2239               pair_r_value = info->O->getScatteredRelocationValue(RENext);
2240             else
2241               return 0;
2242           }
2243         } else {
2244           isExtern = info->O->getPlainRelocationExternal(RE);
2245           if (isExtern) {
2246             symbol_iterator RelocSym = Reloc.getSymbol();
2247             Symbol = *RelocSym;
2248           }
2249         }
2250         reloc_found = true;
2251         break;
2252       }
2253     }
2254     if (reloc_found && isExtern) {
2255       Expected<StringRef> SymName = Symbol.getName();
2256       if (!SymName)
2257         report_error(info->O->getFileName(), SymName.takeError());
2258       const char *name = SymName->data();
2259       op_info->AddSymbol.Present = 1;
2260       op_info->AddSymbol.Name = name;
2261       // For i386 extern relocation entries the value in the instruction is
2262       // the offset from the symbol, and value is already set in op_info->Value.
2263       return 1;
2264     }
2265     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2266                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2267       const char *add = GuessSymbolName(r_value, info->AddrMap);
2268       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2269       uint32_t offset = value - (r_value - pair_r_value);
2270       op_info->AddSymbol.Present = 1;
2271       if (add != nullptr)
2272         op_info->AddSymbol.Name = add;
2273       else
2274         op_info->AddSymbol.Value = r_value;
2275       op_info->SubtractSymbol.Present = 1;
2276       if (sub != nullptr)
2277         op_info->SubtractSymbol.Name = sub;
2278       else
2279         op_info->SubtractSymbol.Value = pair_r_value;
2280       op_info->Value = offset;
2281       return 1;
2282     }
2283     return 0;
2284   }
2285   if (Arch == Triple::x86_64) {
2286     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2287       return 0;
2288     // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2289     // relocation entries of a linked image (if any) for an entry that matches
2290     // this segment offset.
2291     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2292       uint64_t seg_offset = Pc + Offset;
2293       bool reloc_found = false;
2294       DataRefImpl Rel;
2295       MachO::any_relocation_info RE;
2296       bool isExtern = false;
2297       SymbolRef Symbol;
2298       for (const RelocationRef &Reloc : info->O->external_relocations()) {
2299         uint64_t RelocOffset = Reloc.getOffset();
2300         if (RelocOffset == seg_offset) {
2301           Rel = Reloc.getRawDataRefImpl();
2302           RE = info->O->getRelocation(Rel);
2303           // external relocation entries should always be external.
2304           isExtern = info->O->getPlainRelocationExternal(RE);
2305           if (isExtern) {
2306             symbol_iterator RelocSym = Reloc.getSymbol();
2307             Symbol = *RelocSym;
2308           }
2309           reloc_found = true;
2310           break;
2311         }
2312       }
2313       if (reloc_found && isExtern) {
2314         // The Value passed in will be adjusted by the Pc if the instruction
2315         // adds the Pc.  But for x86_64 external relocation entries the Value
2316         // is the offset from the external symbol.
2317         if (info->O->getAnyRelocationPCRel(RE))
2318           op_info->Value -= Pc + Offset + Size;
2319         Expected<StringRef> SymName = Symbol.getName();
2320         if (!SymName)
2321           report_error(info->O->getFileName(), SymName.takeError());
2322         const char *name = SymName->data();
2323         op_info->AddSymbol.Present = 1;
2324         op_info->AddSymbol.Name = name;
2325         return 1;
2326       }
2327       return 0;
2328     }
2329     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2330     // for an entry for this section offset.
2331     uint64_t sect_addr = info->S.getAddress();
2332     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2333     bool reloc_found = false;
2334     DataRefImpl Rel;
2335     MachO::any_relocation_info RE;
2336     bool isExtern = false;
2337     SymbolRef Symbol;
2338     for (const RelocationRef &Reloc : info->S.relocations()) {
2339       uint64_t RelocOffset = Reloc.getOffset();
2340       if (RelocOffset == sect_offset) {
2341         Rel = Reloc.getRawDataRefImpl();
2342         RE = info->O->getRelocation(Rel);
2343         // NOTE: Scattered relocations don't exist on x86_64.
2344         isExtern = info->O->getPlainRelocationExternal(RE);
2345         if (isExtern) {
2346           symbol_iterator RelocSym = Reloc.getSymbol();
2347           Symbol = *RelocSym;
2348         }
2349         reloc_found = true;
2350         break;
2351       }
2352     }
2353     if (reloc_found && isExtern) {
2354       // The Value passed in will be adjusted by the Pc if the instruction
2355       // adds the Pc.  But for x86_64 external relocation entries the Value
2356       // is the offset from the external symbol.
2357       if (info->O->getAnyRelocationPCRel(RE))
2358         op_info->Value -= Pc + Offset + Size;
2359       Expected<StringRef> SymName = Symbol.getName();
2360       if (!SymName)
2361         report_error(info->O->getFileName(), SymName.takeError());
2362       const char *name = SymName->data();
2363       unsigned Type = info->O->getAnyRelocationType(RE);
2364       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2365         DataRefImpl RelNext = Rel;
2366         info->O->moveRelocationNext(RelNext);
2367         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2368         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2369         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2370         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2371         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2372           op_info->SubtractSymbol.Present = 1;
2373           op_info->SubtractSymbol.Name = name;
2374           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2375           Symbol = *RelocSymNext;
2376           Expected<StringRef> SymNameNext = Symbol.getName();
2377           if (!SymNameNext)
2378             report_error(info->O->getFileName(), SymNameNext.takeError());
2379           name = SymNameNext->data();
2380         }
2381       }
2382       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2383       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2384       op_info->AddSymbol.Present = 1;
2385       op_info->AddSymbol.Name = name;
2386       return 1;
2387     }
2388     return 0;
2389   }
2390   if (Arch == Triple::arm) {
2391     if (Offset != 0 || (Size != 4 && Size != 2))
2392       return 0;
2393     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2394       // TODO:
2395       // Search the external relocation entries of a fully linked image
2396       // (if any) for an entry that matches this segment offset.
2397       // uint32_t seg_offset = (Pc + Offset);
2398       return 0;
2399     }
2400     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2401     // for an entry for this section offset.
2402     uint32_t sect_addr = info->S.getAddress();
2403     uint32_t sect_offset = (Pc + Offset) - sect_addr;
2404     DataRefImpl Rel;
2405     MachO::any_relocation_info RE;
2406     bool isExtern = false;
2407     SymbolRef Symbol;
2408     bool r_scattered = false;
2409     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2410     auto Reloc =
2411         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2412           uint64_t RelocOffset = Reloc.getOffset();
2413           return RelocOffset == sect_offset;
2414         });
2415 
2416     if (Reloc == info->S.relocations().end())
2417       return 0;
2418 
2419     Rel = Reloc->getRawDataRefImpl();
2420     RE = info->O->getRelocation(Rel);
2421     r_length = info->O->getAnyRelocationLength(RE);
2422     r_scattered = info->O->isRelocationScattered(RE);
2423     if (r_scattered) {
2424       r_value = info->O->getScatteredRelocationValue(RE);
2425       r_type = info->O->getScatteredRelocationType(RE);
2426     } else {
2427       r_type = info->O->getAnyRelocationType(RE);
2428       isExtern = info->O->getPlainRelocationExternal(RE);
2429       if (isExtern) {
2430         symbol_iterator RelocSym = Reloc->getSymbol();
2431         Symbol = *RelocSym;
2432       }
2433     }
2434     if (r_type == MachO::ARM_RELOC_HALF ||
2435         r_type == MachO::ARM_RELOC_SECTDIFF ||
2436         r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2437         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2438       DataRefImpl RelNext = Rel;
2439       info->O->moveRelocationNext(RelNext);
2440       MachO::any_relocation_info RENext;
2441       RENext = info->O->getRelocation(RelNext);
2442       other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2443       if (info->O->isRelocationScattered(RENext))
2444         pair_r_value = info->O->getScatteredRelocationValue(RENext);
2445     }
2446 
2447     if (isExtern) {
2448       Expected<StringRef> SymName = Symbol.getName();
2449       if (!SymName)
2450         report_error(info->O->getFileName(), SymName.takeError());
2451       const char *name = SymName->data();
2452       op_info->AddSymbol.Present = 1;
2453       op_info->AddSymbol.Name = name;
2454       switch (r_type) {
2455       case MachO::ARM_RELOC_HALF:
2456         if ((r_length & 0x1) == 1) {
2457           op_info->Value = value << 16 | other_half;
2458           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2459         } else {
2460           op_info->Value = other_half << 16 | value;
2461           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2462         }
2463         break;
2464       default:
2465         break;
2466       }
2467       return 1;
2468     }
2469     // If we have a branch that is not an external relocation entry then
2470     // return 0 so the code in tryAddingSymbolicOperand() can use the
2471     // SymbolLookUp call back with the branch target address to look up the
2472     // symbol and possibility add an annotation for a symbol stub.
2473     if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2474                           r_type == MachO::ARM_THUMB_RELOC_BR22))
2475       return 0;
2476 
2477     uint32_t offset = 0;
2478     if (r_type == MachO::ARM_RELOC_HALF ||
2479         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2480       if ((r_length & 0x1) == 1)
2481         value = value << 16 | other_half;
2482       else
2483         value = other_half << 16 | value;
2484     }
2485     if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2486                         r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2487       offset = value - r_value;
2488       value = r_value;
2489     }
2490 
2491     if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2492       if ((r_length & 0x1) == 1)
2493         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2494       else
2495         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2496       const char *add = GuessSymbolName(r_value, info->AddrMap);
2497       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2498       int32_t offset = value - (r_value - pair_r_value);
2499       op_info->AddSymbol.Present = 1;
2500       if (add != nullptr)
2501         op_info->AddSymbol.Name = add;
2502       else
2503         op_info->AddSymbol.Value = r_value;
2504       op_info->SubtractSymbol.Present = 1;
2505       if (sub != nullptr)
2506         op_info->SubtractSymbol.Name = sub;
2507       else
2508         op_info->SubtractSymbol.Value = pair_r_value;
2509       op_info->Value = offset;
2510       return 1;
2511     }
2512 
2513     op_info->AddSymbol.Present = 1;
2514     op_info->Value = offset;
2515     if (r_type == MachO::ARM_RELOC_HALF) {
2516       if ((r_length & 0x1) == 1)
2517         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2518       else
2519         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2520     }
2521     const char *add = GuessSymbolName(value, info->AddrMap);
2522     if (add != nullptr) {
2523       op_info->AddSymbol.Name = add;
2524       return 1;
2525     }
2526     op_info->AddSymbol.Value = value;
2527     return 1;
2528   }
2529   if (Arch == Triple::aarch64) {
2530     if (Offset != 0 || Size != 4)
2531       return 0;
2532     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2533       // TODO:
2534       // Search the external relocation entries of a fully linked image
2535       // (if any) for an entry that matches this segment offset.
2536       // uint64_t seg_offset = (Pc + Offset);
2537       return 0;
2538     }
2539     // In MH_OBJECT filetypes search the section's relocation entries (if any)
2540     // for an entry for this section offset.
2541     uint64_t sect_addr = info->S.getAddress();
2542     uint64_t sect_offset = (Pc + Offset) - sect_addr;
2543     auto Reloc =
2544         find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2545           uint64_t RelocOffset = Reloc.getOffset();
2546           return RelocOffset == sect_offset;
2547         });
2548 
2549     if (Reloc == info->S.relocations().end())
2550       return 0;
2551 
2552     DataRefImpl Rel = Reloc->getRawDataRefImpl();
2553     MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2554     uint32_t r_type = info->O->getAnyRelocationType(RE);
2555     if (r_type == MachO::ARM64_RELOC_ADDEND) {
2556       DataRefImpl RelNext = Rel;
2557       info->O->moveRelocationNext(RelNext);
2558       MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2559       if (value == 0) {
2560         value = info->O->getPlainRelocationSymbolNum(RENext);
2561         op_info->Value = value;
2562       }
2563     }
2564     // NOTE: Scattered relocations don't exist on arm64.
2565     if (!info->O->getPlainRelocationExternal(RE))
2566       return 0;
2567     Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2568     if (!SymName)
2569       report_error(info->O->getFileName(), SymName.takeError());
2570     const char *name = SymName->data();
2571     op_info->AddSymbol.Present = 1;
2572     op_info->AddSymbol.Name = name;
2573 
2574     switch (r_type) {
2575     case MachO::ARM64_RELOC_PAGE21:
2576       /* @page */
2577       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2578       break;
2579     case MachO::ARM64_RELOC_PAGEOFF12:
2580       /* @pageoff */
2581       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2582       break;
2583     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2584       /* @gotpage */
2585       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2586       break;
2587     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2588       /* @gotpageoff */
2589       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2590       break;
2591     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2592       /* @tvlppage is not implemented in llvm-mc */
2593       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2594       break;
2595     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2596       /* @tvlppageoff is not implemented in llvm-mc */
2597       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2598       break;
2599     default:
2600     case MachO::ARM64_RELOC_BRANCH26:
2601       op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2602       break;
2603     }
2604     return 1;
2605   }
2606   return 0;
2607 }
2608 
2609 // GuessCstringPointer is passed the address of what might be a pointer to a
2610 // literal string in a cstring section.  If that address is in a cstring section
2611 // it returns a pointer to that string.  Else it returns nullptr.
2612 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2613                                        struct DisassembleInfo *info) {
2614   for (const auto &Load : info->O->load_commands()) {
2615     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2616       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2617       for (unsigned J = 0; J < Seg.nsects; ++J) {
2618         MachO::section_64 Sec = info->O->getSection64(Load, J);
2619         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2620         if (section_type == MachO::S_CSTRING_LITERALS &&
2621             ReferenceValue >= Sec.addr &&
2622             ReferenceValue < Sec.addr + Sec.size) {
2623           uint64_t sect_offset = ReferenceValue - Sec.addr;
2624           uint64_t object_offset = Sec.offset + sect_offset;
2625           StringRef MachOContents = info->O->getData();
2626           uint64_t object_size = MachOContents.size();
2627           const char *object_addr = (const char *)MachOContents.data();
2628           if (object_offset < object_size) {
2629             const char *name = object_addr + object_offset;
2630             return name;
2631           } else {
2632             return nullptr;
2633           }
2634         }
2635       }
2636     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2637       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2638       for (unsigned J = 0; J < Seg.nsects; ++J) {
2639         MachO::section Sec = info->O->getSection(Load, J);
2640         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2641         if (section_type == MachO::S_CSTRING_LITERALS &&
2642             ReferenceValue >= Sec.addr &&
2643             ReferenceValue < Sec.addr + Sec.size) {
2644           uint64_t sect_offset = ReferenceValue - Sec.addr;
2645           uint64_t object_offset = Sec.offset + sect_offset;
2646           StringRef MachOContents = info->O->getData();
2647           uint64_t object_size = MachOContents.size();
2648           const char *object_addr = (const char *)MachOContents.data();
2649           if (object_offset < object_size) {
2650             const char *name = object_addr + object_offset;
2651             return name;
2652           } else {
2653             return nullptr;
2654           }
2655         }
2656       }
2657     }
2658   }
2659   return nullptr;
2660 }
2661 
2662 // GuessIndirectSymbol returns the name of the indirect symbol for the
2663 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
2664 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2665 // symbol name being referenced by the stub or pointer.
2666 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2667                                        struct DisassembleInfo *info) {
2668   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2669   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2670   for (const auto &Load : info->O->load_commands()) {
2671     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2672       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2673       for (unsigned J = 0; J < Seg.nsects; ++J) {
2674         MachO::section_64 Sec = info->O->getSection64(Load, J);
2675         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2676         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2677              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2678              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2679              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2680              section_type == MachO::S_SYMBOL_STUBS) &&
2681             ReferenceValue >= Sec.addr &&
2682             ReferenceValue < Sec.addr + Sec.size) {
2683           uint32_t stride;
2684           if (section_type == MachO::S_SYMBOL_STUBS)
2685             stride = Sec.reserved2;
2686           else
2687             stride = 8;
2688           if (stride == 0)
2689             return nullptr;
2690           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2691           if (index < Dysymtab.nindirectsyms) {
2692             uint32_t indirect_symbol =
2693                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2694             if (indirect_symbol < Symtab.nsyms) {
2695               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2696               SymbolRef Symbol = *Sym;
2697               Expected<StringRef> SymName = Symbol.getName();
2698               if (!SymName)
2699                 report_error(info->O->getFileName(), SymName.takeError());
2700               const char *name = SymName->data();
2701               return name;
2702             }
2703           }
2704         }
2705       }
2706     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2707       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2708       for (unsigned J = 0; J < Seg.nsects; ++J) {
2709         MachO::section Sec = info->O->getSection(Load, J);
2710         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2711         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2712              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2713              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2714              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2715              section_type == MachO::S_SYMBOL_STUBS) &&
2716             ReferenceValue >= Sec.addr &&
2717             ReferenceValue < Sec.addr + Sec.size) {
2718           uint32_t stride;
2719           if (section_type == MachO::S_SYMBOL_STUBS)
2720             stride = Sec.reserved2;
2721           else
2722             stride = 4;
2723           if (stride == 0)
2724             return nullptr;
2725           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2726           if (index < Dysymtab.nindirectsyms) {
2727             uint32_t indirect_symbol =
2728                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2729             if (indirect_symbol < Symtab.nsyms) {
2730               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2731               SymbolRef Symbol = *Sym;
2732               Expected<StringRef> SymName = Symbol.getName();
2733               if (!SymName)
2734                 report_error(info->O->getFileName(), SymName.takeError());
2735               const char *name = SymName->data();
2736               return name;
2737             }
2738           }
2739         }
2740       }
2741     }
2742   }
2743   return nullptr;
2744 }
2745 
2746 // method_reference() is called passing it the ReferenceName that might be
2747 // a reference it to an Objective-C method call.  If so then it allocates and
2748 // assembles a method call string with the values last seen and saved in
2749 // the DisassembleInfo's class_name and selector_name fields.  This is saved
2750 // into the method field of the info and any previous string is free'ed.
2751 // Then the class_name field in the info is set to nullptr.  The method call
2752 // string is set into ReferenceName and ReferenceType is set to
2753 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
2754 // then both ReferenceType and ReferenceName are left unchanged.
2755 static void method_reference(struct DisassembleInfo *info,
2756                              uint64_t *ReferenceType,
2757                              const char **ReferenceName) {
2758   unsigned int Arch = info->O->getArch();
2759   if (*ReferenceName != nullptr) {
2760     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2761       if (info->selector_name != nullptr) {
2762         if (info->method != nullptr)
2763           delete[] info->method;
2764         if (info->class_name != nullptr) {
2765           info->method = new char[5 + strlen(info->class_name) +
2766                                   strlen(info->selector_name)];
2767           if (info->method != nullptr) {
2768             strcpy(info->method, "+[");
2769             strcat(info->method, info->class_name);
2770             strcat(info->method, " ");
2771             strcat(info->method, info->selector_name);
2772             strcat(info->method, "]");
2773             *ReferenceName = info->method;
2774             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2775           }
2776         } else {
2777           info->method = new char[9 + strlen(info->selector_name)];
2778           if (info->method != nullptr) {
2779             if (Arch == Triple::x86_64)
2780               strcpy(info->method, "-[%rdi ");
2781             else if (Arch == Triple::aarch64)
2782               strcpy(info->method, "-[x0 ");
2783             else
2784               strcpy(info->method, "-[r? ");
2785             strcat(info->method, info->selector_name);
2786             strcat(info->method, "]");
2787             *ReferenceName = info->method;
2788             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2789           }
2790         }
2791         info->class_name = nullptr;
2792       }
2793     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2794       if (info->selector_name != nullptr) {
2795         if (info->method != nullptr)
2796           delete[] info->method;
2797         info->method = new char[17 + strlen(info->selector_name)];
2798         if (info->method != nullptr) {
2799           if (Arch == Triple::x86_64)
2800             strcpy(info->method, "-[[%rdi super] ");
2801           else if (Arch == Triple::aarch64)
2802             strcpy(info->method, "-[[x0 super] ");
2803           else
2804             strcpy(info->method, "-[[r? super] ");
2805           strcat(info->method, info->selector_name);
2806           strcat(info->method, "]");
2807           *ReferenceName = info->method;
2808           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2809         }
2810         info->class_name = nullptr;
2811       }
2812     }
2813   }
2814 }
2815 
2816 // GuessPointerPointer() is passed the address of what might be a pointer to
2817 // a reference to an Objective-C class, selector, message ref or cfstring.
2818 // If so the value of the pointer is returned and one of the booleans are set
2819 // to true.  If not zero is returned and all the booleans are set to false.
2820 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2821                                     struct DisassembleInfo *info,
2822                                     bool &classref, bool &selref, bool &msgref,
2823                                     bool &cfstring) {
2824   classref = false;
2825   selref = false;
2826   msgref = false;
2827   cfstring = false;
2828   for (const auto &Load : info->O->load_commands()) {
2829     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2830       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2831       for (unsigned J = 0; J < Seg.nsects; ++J) {
2832         MachO::section_64 Sec = info->O->getSection64(Load, J);
2833         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2834              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2835              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2836              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2837              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2838             ReferenceValue >= Sec.addr &&
2839             ReferenceValue < Sec.addr + Sec.size) {
2840           uint64_t sect_offset = ReferenceValue - Sec.addr;
2841           uint64_t object_offset = Sec.offset + sect_offset;
2842           StringRef MachOContents = info->O->getData();
2843           uint64_t object_size = MachOContents.size();
2844           const char *object_addr = (const char *)MachOContents.data();
2845           if (object_offset < object_size) {
2846             uint64_t pointer_value;
2847             memcpy(&pointer_value, object_addr + object_offset,
2848                    sizeof(uint64_t));
2849             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2850               sys::swapByteOrder(pointer_value);
2851             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2852               selref = true;
2853             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2854                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2855               classref = true;
2856             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2857                      ReferenceValue + 8 < Sec.addr + Sec.size) {
2858               msgref = true;
2859               memcpy(&pointer_value, object_addr + object_offset + 8,
2860                      sizeof(uint64_t));
2861               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2862                 sys::swapByteOrder(pointer_value);
2863             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2864               cfstring = true;
2865             return pointer_value;
2866           } else {
2867             return 0;
2868           }
2869         }
2870       }
2871     }
2872     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2873   }
2874   return 0;
2875 }
2876 
2877 // get_pointer_64 returns a pointer to the bytes in the object file at the
2878 // Address from a section in the Mach-O file.  And indirectly returns the
2879 // offset into the section, number of bytes left in the section past the offset
2880 // and which section is was being referenced.  If the Address is not in a
2881 // section nullptr is returned.
2882 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2883                                   uint32_t &left, SectionRef &S,
2884                                   DisassembleInfo *info,
2885                                   bool objc_only = false) {
2886   offset = 0;
2887   left = 0;
2888   S = SectionRef();
2889   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2890     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2891     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2892     if (SectSize == 0)
2893       continue;
2894     if (objc_only) {
2895       StringRef SectName;
2896       ((*(info->Sections))[SectIdx]).getName(SectName);
2897       DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2898       StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2899       if (SegName != "__OBJC" && SectName != "__cstring")
2900         continue;
2901     }
2902     if (Address >= SectAddress && Address < SectAddress + SectSize) {
2903       S = (*(info->Sections))[SectIdx];
2904       offset = Address - SectAddress;
2905       left = SectSize - offset;
2906       StringRef SectContents;
2907       ((*(info->Sections))[SectIdx]).getContents(SectContents);
2908       return SectContents.data() + offset;
2909     }
2910   }
2911   return nullptr;
2912 }
2913 
2914 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2915                                   uint32_t &left, SectionRef &S,
2916                                   DisassembleInfo *info,
2917                                   bool objc_only = false) {
2918   return get_pointer_64(Address, offset, left, S, info, objc_only);
2919 }
2920 
2921 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2922 // the symbol indirectly through n_value. Based on the relocation information
2923 // for the specified section offset in the specified section reference.
2924 // If no relocation information is found and a non-zero ReferenceValue for the
2925 // symbol is passed, look up that address in the info's AddrMap.
2926 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2927                                  DisassembleInfo *info, uint64_t &n_value,
2928                                  uint64_t ReferenceValue = 0) {
2929   n_value = 0;
2930   if (!info->verbose)
2931     return nullptr;
2932 
2933   // See if there is an external relocation entry at the sect_offset.
2934   bool reloc_found = false;
2935   DataRefImpl Rel;
2936   MachO::any_relocation_info RE;
2937   bool isExtern = false;
2938   SymbolRef Symbol;
2939   for (const RelocationRef &Reloc : S.relocations()) {
2940     uint64_t RelocOffset = Reloc.getOffset();
2941     if (RelocOffset == sect_offset) {
2942       Rel = Reloc.getRawDataRefImpl();
2943       RE = info->O->getRelocation(Rel);
2944       if (info->O->isRelocationScattered(RE))
2945         continue;
2946       isExtern = info->O->getPlainRelocationExternal(RE);
2947       if (isExtern) {
2948         symbol_iterator RelocSym = Reloc.getSymbol();
2949         Symbol = *RelocSym;
2950       }
2951       reloc_found = true;
2952       break;
2953     }
2954   }
2955   // If there is an external relocation entry for a symbol in this section
2956   // at this section_offset then use that symbol's value for the n_value
2957   // and return its name.
2958   const char *SymbolName = nullptr;
2959   if (reloc_found && isExtern) {
2960     n_value = Symbol.getValue();
2961     Expected<StringRef> NameOrError = Symbol.getName();
2962     if (!NameOrError)
2963       report_error(info->O->getFileName(), NameOrError.takeError());
2964     StringRef Name = *NameOrError;
2965     if (!Name.empty()) {
2966       SymbolName = Name.data();
2967       return SymbolName;
2968     }
2969   }
2970 
2971   // TODO: For fully linked images, look through the external relocation
2972   // entries off the dynamic symtab command. For these the r_offset is from the
2973   // start of the first writeable segment in the Mach-O file.  So the offset
2974   // to this section from that segment is passed to this routine by the caller,
2975   // as the database_offset. Which is the difference of the section's starting
2976   // address and the first writable segment.
2977   //
2978   // NOTE: need add passing the database_offset to this routine.
2979 
2980   // We did not find an external relocation entry so look up the ReferenceValue
2981   // as an address of a symbol and if found return that symbol's name.
2982   SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2983 
2984   return SymbolName;
2985 }
2986 
2987 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2988                                  DisassembleInfo *info,
2989                                  uint32_t ReferenceValue) {
2990   uint64_t n_value64;
2991   return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2992 }
2993 
2994 // These are structs in the Objective-C meta data and read to produce the
2995 // comments for disassembly.  While these are part of the ABI they are no
2996 // public defintions.  So the are here not in include/llvm/BinaryFormat/MachO.h
2997 // .
2998 
2999 // The cfstring object in a 64-bit Mach-O file.
3000 struct cfstring64_t {
3001   uint64_t isa;        // class64_t * (64-bit pointer)
3002   uint64_t flags;      // flag bits
3003   uint64_t characters; // char * (64-bit pointer)
3004   uint64_t length;     // number of non-NULL characters in above
3005 };
3006 
3007 // The class object in a 64-bit Mach-O file.
3008 struct class64_t {
3009   uint64_t isa;        // class64_t * (64-bit pointer)
3010   uint64_t superclass; // class64_t * (64-bit pointer)
3011   uint64_t cache;      // Cache (64-bit pointer)
3012   uint64_t vtable;     // IMP * (64-bit pointer)
3013   uint64_t data;       // class_ro64_t * (64-bit pointer)
3014 };
3015 
3016 struct class32_t {
3017   uint32_t isa;        /* class32_t * (32-bit pointer) */
3018   uint32_t superclass; /* class32_t * (32-bit pointer) */
3019   uint32_t cache;      /* Cache (32-bit pointer) */
3020   uint32_t vtable;     /* IMP * (32-bit pointer) */
3021   uint32_t data;       /* class_ro32_t * (32-bit pointer) */
3022 };
3023 
3024 struct class_ro64_t {
3025   uint32_t flags;
3026   uint32_t instanceStart;
3027   uint32_t instanceSize;
3028   uint32_t reserved;
3029   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
3030   uint64_t name;           // const char * (64-bit pointer)
3031   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
3032   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
3033   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
3034   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3035   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3036 };
3037 
3038 struct class_ro32_t {
3039   uint32_t flags;
3040   uint32_t instanceStart;
3041   uint32_t instanceSize;
3042   uint32_t ivarLayout;     /* const uint8_t * (32-bit pointer) */
3043   uint32_t name;           /* const char * (32-bit pointer) */
3044   uint32_t baseMethods;    /* const method_list_t * (32-bit pointer) */
3045   uint32_t baseProtocols;  /* const protocol_list_t * (32-bit pointer) */
3046   uint32_t ivars;          /* const ivar_list_t * (32-bit pointer) */
3047   uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3048   uint32_t baseProperties; /* const struct objc_property_list *
3049                                                    (32-bit pointer) */
3050 };
3051 
3052 /* Values for class_ro{64,32}_t->flags */
3053 #define RO_META (1 << 0)
3054 #define RO_ROOT (1 << 1)
3055 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3056 
3057 struct method_list64_t {
3058   uint32_t entsize;
3059   uint32_t count;
3060   /* struct method64_t first;  These structures follow inline */
3061 };
3062 
3063 struct method_list32_t {
3064   uint32_t entsize;
3065   uint32_t count;
3066   /* struct method32_t first;  These structures follow inline */
3067 };
3068 
3069 struct method64_t {
3070   uint64_t name;  /* SEL (64-bit pointer) */
3071   uint64_t types; /* const char * (64-bit pointer) */
3072   uint64_t imp;   /* IMP (64-bit pointer) */
3073 };
3074 
3075 struct method32_t {
3076   uint32_t name;  /* SEL (32-bit pointer) */
3077   uint32_t types; /* const char * (32-bit pointer) */
3078   uint32_t imp;   /* IMP (32-bit pointer) */
3079 };
3080 
3081 struct protocol_list64_t {
3082   uint64_t count; /* uintptr_t (a 64-bit value) */
3083   /* struct protocol64_t * list[0];  These pointers follow inline */
3084 };
3085 
3086 struct protocol_list32_t {
3087   uint32_t count; /* uintptr_t (a 32-bit value) */
3088   /* struct protocol32_t * list[0];  These pointers follow inline */
3089 };
3090 
3091 struct protocol64_t {
3092   uint64_t isa;                     /* id * (64-bit pointer) */
3093   uint64_t name;                    /* const char * (64-bit pointer) */
3094   uint64_t protocols;               /* struct protocol_list64_t *
3095                                                     (64-bit pointer) */
3096   uint64_t instanceMethods;         /* method_list_t * (64-bit pointer) */
3097   uint64_t classMethods;            /* method_list_t * (64-bit pointer) */
3098   uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3099   uint64_t optionalClassMethods;    /* method_list_t * (64-bit pointer) */
3100   uint64_t instanceProperties;      /* struct objc_property_list *
3101                                                        (64-bit pointer) */
3102 };
3103 
3104 struct protocol32_t {
3105   uint32_t isa;                     /* id * (32-bit pointer) */
3106   uint32_t name;                    /* const char * (32-bit pointer) */
3107   uint32_t protocols;               /* struct protocol_list_t *
3108                                                     (32-bit pointer) */
3109   uint32_t instanceMethods;         /* method_list_t * (32-bit pointer) */
3110   uint32_t classMethods;            /* method_list_t * (32-bit pointer) */
3111   uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3112   uint32_t optionalClassMethods;    /* method_list_t * (32-bit pointer) */
3113   uint32_t instanceProperties;      /* struct objc_property_list *
3114                                                        (32-bit pointer) */
3115 };
3116 
3117 struct ivar_list64_t {
3118   uint32_t entsize;
3119   uint32_t count;
3120   /* struct ivar64_t first;  These structures follow inline */
3121 };
3122 
3123 struct ivar_list32_t {
3124   uint32_t entsize;
3125   uint32_t count;
3126   /* struct ivar32_t first;  These structures follow inline */
3127 };
3128 
3129 struct ivar64_t {
3130   uint64_t offset; /* uintptr_t * (64-bit pointer) */
3131   uint64_t name;   /* const char * (64-bit pointer) */
3132   uint64_t type;   /* const char * (64-bit pointer) */
3133   uint32_t alignment;
3134   uint32_t size;
3135 };
3136 
3137 struct ivar32_t {
3138   uint32_t offset; /* uintptr_t * (32-bit pointer) */
3139   uint32_t name;   /* const char * (32-bit pointer) */
3140   uint32_t type;   /* const char * (32-bit pointer) */
3141   uint32_t alignment;
3142   uint32_t size;
3143 };
3144 
3145 struct objc_property_list64 {
3146   uint32_t entsize;
3147   uint32_t count;
3148   /* struct objc_property64 first;  These structures follow inline */
3149 };
3150 
3151 struct objc_property_list32 {
3152   uint32_t entsize;
3153   uint32_t count;
3154   /* struct objc_property32 first;  These structures follow inline */
3155 };
3156 
3157 struct objc_property64 {
3158   uint64_t name;       /* const char * (64-bit pointer) */
3159   uint64_t attributes; /* const char * (64-bit pointer) */
3160 };
3161 
3162 struct objc_property32 {
3163   uint32_t name;       /* const char * (32-bit pointer) */
3164   uint32_t attributes; /* const char * (32-bit pointer) */
3165 };
3166 
3167 struct category64_t {
3168   uint64_t name;               /* const char * (64-bit pointer) */
3169   uint64_t cls;                /* struct class_t * (64-bit pointer) */
3170   uint64_t instanceMethods;    /* struct method_list_t * (64-bit pointer) */
3171   uint64_t classMethods;       /* struct method_list_t * (64-bit pointer) */
3172   uint64_t protocols;          /* struct protocol_list_t * (64-bit pointer) */
3173   uint64_t instanceProperties; /* struct objc_property_list *
3174                                   (64-bit pointer) */
3175 };
3176 
3177 struct category32_t {
3178   uint32_t name;               /* const char * (32-bit pointer) */
3179   uint32_t cls;                /* struct class_t * (32-bit pointer) */
3180   uint32_t instanceMethods;    /* struct method_list_t * (32-bit pointer) */
3181   uint32_t classMethods;       /* struct method_list_t * (32-bit pointer) */
3182   uint32_t protocols;          /* struct protocol_list_t * (32-bit pointer) */
3183   uint32_t instanceProperties; /* struct objc_property_list *
3184                                   (32-bit pointer) */
3185 };
3186 
3187 struct objc_image_info64 {
3188   uint32_t version;
3189   uint32_t flags;
3190 };
3191 struct objc_image_info32 {
3192   uint32_t version;
3193   uint32_t flags;
3194 };
3195 struct imageInfo_t {
3196   uint32_t version;
3197   uint32_t flags;
3198 };
3199 /* masks for objc_image_info.flags */
3200 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3201 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3202 
3203 struct message_ref64 {
3204   uint64_t imp; /* IMP (64-bit pointer) */
3205   uint64_t sel; /* SEL (64-bit pointer) */
3206 };
3207 
3208 struct message_ref32 {
3209   uint32_t imp; /* IMP (32-bit pointer) */
3210   uint32_t sel; /* SEL (32-bit pointer) */
3211 };
3212 
3213 // Objective-C 1 (32-bit only) meta data structs.
3214 
3215 struct objc_module_t {
3216   uint32_t version;
3217   uint32_t size;
3218   uint32_t name;   /* char * (32-bit pointer) */
3219   uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3220 };
3221 
3222 struct objc_symtab_t {
3223   uint32_t sel_ref_cnt;
3224   uint32_t refs; /* SEL * (32-bit pointer) */
3225   uint16_t cls_def_cnt;
3226   uint16_t cat_def_cnt;
3227   // uint32_t defs[1];        /* void * (32-bit pointer) variable size */
3228 };
3229 
3230 struct objc_class_t {
3231   uint32_t isa;         /* struct objc_class * (32-bit pointer) */
3232   uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3233   uint32_t name;        /* const char * (32-bit pointer) */
3234   int32_t version;
3235   int32_t info;
3236   int32_t instance_size;
3237   uint32_t ivars;       /* struct objc_ivar_list * (32-bit pointer) */
3238   uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3239   uint32_t cache;       /* struct objc_cache * (32-bit pointer) */
3240   uint32_t protocols;   /* struct objc_protocol_list * (32-bit pointer) */
3241 };
3242 
3243 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3244 // class is not a metaclass
3245 #define CLS_CLASS 0x1
3246 // class is a metaclass
3247 #define CLS_META 0x2
3248 
3249 struct objc_category_t {
3250   uint32_t category_name;    /* char * (32-bit pointer) */
3251   uint32_t class_name;       /* char * (32-bit pointer) */
3252   uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3253   uint32_t class_methods;    /* struct objc_method_list * (32-bit pointer) */
3254   uint32_t protocols;        /* struct objc_protocol_list * (32-bit ptr) */
3255 };
3256 
3257 struct objc_ivar_t {
3258   uint32_t ivar_name; /* char * (32-bit pointer) */
3259   uint32_t ivar_type; /* char * (32-bit pointer) */
3260   int32_t ivar_offset;
3261 };
3262 
3263 struct objc_ivar_list_t {
3264   int32_t ivar_count;
3265   // struct objc_ivar_t ivar_list[1];          /* variable length structure */
3266 };
3267 
3268 struct objc_method_list_t {
3269   uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3270   int32_t method_count;
3271   // struct objc_method_t method_list[1];      /* variable length structure */
3272 };
3273 
3274 struct objc_method_t {
3275   uint32_t method_name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3276   uint32_t method_types; /* char * (32-bit pointer) */
3277   uint32_t method_imp;   /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3278                             (32-bit pointer) */
3279 };
3280 
3281 struct objc_protocol_list_t {
3282   uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3283   int32_t count;
3284   // uint32_t list[1];   /* Protocol *, aka struct objc_protocol_t *
3285   //                        (32-bit pointer) */
3286 };
3287 
3288 struct objc_protocol_t {
3289   uint32_t isa;              /* struct objc_class * (32-bit pointer) */
3290   uint32_t protocol_name;    /* char * (32-bit pointer) */
3291   uint32_t protocol_list;    /* struct objc_protocol_list * (32-bit pointer) */
3292   uint32_t instance_methods; /* struct objc_method_description_list *
3293                                 (32-bit pointer) */
3294   uint32_t class_methods;    /* struct objc_method_description_list *
3295                                 (32-bit pointer) */
3296 };
3297 
3298 struct objc_method_description_list_t {
3299   int32_t count;
3300   // struct objc_method_description_t list[1];
3301 };
3302 
3303 struct objc_method_description_t {
3304   uint32_t name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
3305   uint32_t types; /* char * (32-bit pointer) */
3306 };
3307 
3308 inline void swapStruct(struct cfstring64_t &cfs) {
3309   sys::swapByteOrder(cfs.isa);
3310   sys::swapByteOrder(cfs.flags);
3311   sys::swapByteOrder(cfs.characters);
3312   sys::swapByteOrder(cfs.length);
3313 }
3314 
3315 inline void swapStruct(struct class64_t &c) {
3316   sys::swapByteOrder(c.isa);
3317   sys::swapByteOrder(c.superclass);
3318   sys::swapByteOrder(c.cache);
3319   sys::swapByteOrder(c.vtable);
3320   sys::swapByteOrder(c.data);
3321 }
3322 
3323 inline void swapStruct(struct class32_t &c) {
3324   sys::swapByteOrder(c.isa);
3325   sys::swapByteOrder(c.superclass);
3326   sys::swapByteOrder(c.cache);
3327   sys::swapByteOrder(c.vtable);
3328   sys::swapByteOrder(c.data);
3329 }
3330 
3331 inline void swapStruct(struct class_ro64_t &cro) {
3332   sys::swapByteOrder(cro.flags);
3333   sys::swapByteOrder(cro.instanceStart);
3334   sys::swapByteOrder(cro.instanceSize);
3335   sys::swapByteOrder(cro.reserved);
3336   sys::swapByteOrder(cro.ivarLayout);
3337   sys::swapByteOrder(cro.name);
3338   sys::swapByteOrder(cro.baseMethods);
3339   sys::swapByteOrder(cro.baseProtocols);
3340   sys::swapByteOrder(cro.ivars);
3341   sys::swapByteOrder(cro.weakIvarLayout);
3342   sys::swapByteOrder(cro.baseProperties);
3343 }
3344 
3345 inline void swapStruct(struct class_ro32_t &cro) {
3346   sys::swapByteOrder(cro.flags);
3347   sys::swapByteOrder(cro.instanceStart);
3348   sys::swapByteOrder(cro.instanceSize);
3349   sys::swapByteOrder(cro.ivarLayout);
3350   sys::swapByteOrder(cro.name);
3351   sys::swapByteOrder(cro.baseMethods);
3352   sys::swapByteOrder(cro.baseProtocols);
3353   sys::swapByteOrder(cro.ivars);
3354   sys::swapByteOrder(cro.weakIvarLayout);
3355   sys::swapByteOrder(cro.baseProperties);
3356 }
3357 
3358 inline void swapStruct(struct method_list64_t &ml) {
3359   sys::swapByteOrder(ml.entsize);
3360   sys::swapByteOrder(ml.count);
3361 }
3362 
3363 inline void swapStruct(struct method_list32_t &ml) {
3364   sys::swapByteOrder(ml.entsize);
3365   sys::swapByteOrder(ml.count);
3366 }
3367 
3368 inline void swapStruct(struct method64_t &m) {
3369   sys::swapByteOrder(m.name);
3370   sys::swapByteOrder(m.types);
3371   sys::swapByteOrder(m.imp);
3372 }
3373 
3374 inline void swapStruct(struct method32_t &m) {
3375   sys::swapByteOrder(m.name);
3376   sys::swapByteOrder(m.types);
3377   sys::swapByteOrder(m.imp);
3378 }
3379 
3380 inline void swapStruct(struct protocol_list64_t &pl) {
3381   sys::swapByteOrder(pl.count);
3382 }
3383 
3384 inline void swapStruct(struct protocol_list32_t &pl) {
3385   sys::swapByteOrder(pl.count);
3386 }
3387 
3388 inline void swapStruct(struct protocol64_t &p) {
3389   sys::swapByteOrder(p.isa);
3390   sys::swapByteOrder(p.name);
3391   sys::swapByteOrder(p.protocols);
3392   sys::swapByteOrder(p.instanceMethods);
3393   sys::swapByteOrder(p.classMethods);
3394   sys::swapByteOrder(p.optionalInstanceMethods);
3395   sys::swapByteOrder(p.optionalClassMethods);
3396   sys::swapByteOrder(p.instanceProperties);
3397 }
3398 
3399 inline void swapStruct(struct protocol32_t &p) {
3400   sys::swapByteOrder(p.isa);
3401   sys::swapByteOrder(p.name);
3402   sys::swapByteOrder(p.protocols);
3403   sys::swapByteOrder(p.instanceMethods);
3404   sys::swapByteOrder(p.classMethods);
3405   sys::swapByteOrder(p.optionalInstanceMethods);
3406   sys::swapByteOrder(p.optionalClassMethods);
3407   sys::swapByteOrder(p.instanceProperties);
3408 }
3409 
3410 inline void swapStruct(struct ivar_list64_t &il) {
3411   sys::swapByteOrder(il.entsize);
3412   sys::swapByteOrder(il.count);
3413 }
3414 
3415 inline void swapStruct(struct ivar_list32_t &il) {
3416   sys::swapByteOrder(il.entsize);
3417   sys::swapByteOrder(il.count);
3418 }
3419 
3420 inline void swapStruct(struct ivar64_t &i) {
3421   sys::swapByteOrder(i.offset);
3422   sys::swapByteOrder(i.name);
3423   sys::swapByteOrder(i.type);
3424   sys::swapByteOrder(i.alignment);
3425   sys::swapByteOrder(i.size);
3426 }
3427 
3428 inline void swapStruct(struct ivar32_t &i) {
3429   sys::swapByteOrder(i.offset);
3430   sys::swapByteOrder(i.name);
3431   sys::swapByteOrder(i.type);
3432   sys::swapByteOrder(i.alignment);
3433   sys::swapByteOrder(i.size);
3434 }
3435 
3436 inline void swapStruct(struct objc_property_list64 &pl) {
3437   sys::swapByteOrder(pl.entsize);
3438   sys::swapByteOrder(pl.count);
3439 }
3440 
3441 inline void swapStruct(struct objc_property_list32 &pl) {
3442   sys::swapByteOrder(pl.entsize);
3443   sys::swapByteOrder(pl.count);
3444 }
3445 
3446 inline void swapStruct(struct objc_property64 &op) {
3447   sys::swapByteOrder(op.name);
3448   sys::swapByteOrder(op.attributes);
3449 }
3450 
3451 inline void swapStruct(struct objc_property32 &op) {
3452   sys::swapByteOrder(op.name);
3453   sys::swapByteOrder(op.attributes);
3454 }
3455 
3456 inline void swapStruct(struct category64_t &c) {
3457   sys::swapByteOrder(c.name);
3458   sys::swapByteOrder(c.cls);
3459   sys::swapByteOrder(c.instanceMethods);
3460   sys::swapByteOrder(c.classMethods);
3461   sys::swapByteOrder(c.protocols);
3462   sys::swapByteOrder(c.instanceProperties);
3463 }
3464 
3465 inline void swapStruct(struct category32_t &c) {
3466   sys::swapByteOrder(c.name);
3467   sys::swapByteOrder(c.cls);
3468   sys::swapByteOrder(c.instanceMethods);
3469   sys::swapByteOrder(c.classMethods);
3470   sys::swapByteOrder(c.protocols);
3471   sys::swapByteOrder(c.instanceProperties);
3472 }
3473 
3474 inline void swapStruct(struct objc_image_info64 &o) {
3475   sys::swapByteOrder(o.version);
3476   sys::swapByteOrder(o.flags);
3477 }
3478 
3479 inline void swapStruct(struct objc_image_info32 &o) {
3480   sys::swapByteOrder(o.version);
3481   sys::swapByteOrder(o.flags);
3482 }
3483 
3484 inline void swapStruct(struct imageInfo_t &o) {
3485   sys::swapByteOrder(o.version);
3486   sys::swapByteOrder(o.flags);
3487 }
3488 
3489 inline void swapStruct(struct message_ref64 &mr) {
3490   sys::swapByteOrder(mr.imp);
3491   sys::swapByteOrder(mr.sel);
3492 }
3493 
3494 inline void swapStruct(struct message_ref32 &mr) {
3495   sys::swapByteOrder(mr.imp);
3496   sys::swapByteOrder(mr.sel);
3497 }
3498 
3499 inline void swapStruct(struct objc_module_t &module) {
3500   sys::swapByteOrder(module.version);
3501   sys::swapByteOrder(module.size);
3502   sys::swapByteOrder(module.name);
3503   sys::swapByteOrder(module.symtab);
3504 }
3505 
3506 inline void swapStruct(struct objc_symtab_t &symtab) {
3507   sys::swapByteOrder(symtab.sel_ref_cnt);
3508   sys::swapByteOrder(symtab.refs);
3509   sys::swapByteOrder(symtab.cls_def_cnt);
3510   sys::swapByteOrder(symtab.cat_def_cnt);
3511 }
3512 
3513 inline void swapStruct(struct objc_class_t &objc_class) {
3514   sys::swapByteOrder(objc_class.isa);
3515   sys::swapByteOrder(objc_class.super_class);
3516   sys::swapByteOrder(objc_class.name);
3517   sys::swapByteOrder(objc_class.version);
3518   sys::swapByteOrder(objc_class.info);
3519   sys::swapByteOrder(objc_class.instance_size);
3520   sys::swapByteOrder(objc_class.ivars);
3521   sys::swapByteOrder(objc_class.methodLists);
3522   sys::swapByteOrder(objc_class.cache);
3523   sys::swapByteOrder(objc_class.protocols);
3524 }
3525 
3526 inline void swapStruct(struct objc_category_t &objc_category) {
3527   sys::swapByteOrder(objc_category.category_name);
3528   sys::swapByteOrder(objc_category.class_name);
3529   sys::swapByteOrder(objc_category.instance_methods);
3530   sys::swapByteOrder(objc_category.class_methods);
3531   sys::swapByteOrder(objc_category.protocols);
3532 }
3533 
3534 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3535   sys::swapByteOrder(objc_ivar_list.ivar_count);
3536 }
3537 
3538 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3539   sys::swapByteOrder(objc_ivar.ivar_name);
3540   sys::swapByteOrder(objc_ivar.ivar_type);
3541   sys::swapByteOrder(objc_ivar.ivar_offset);
3542 }
3543 
3544 inline void swapStruct(struct objc_method_list_t &method_list) {
3545   sys::swapByteOrder(method_list.obsolete);
3546   sys::swapByteOrder(method_list.method_count);
3547 }
3548 
3549 inline void swapStruct(struct objc_method_t &method) {
3550   sys::swapByteOrder(method.method_name);
3551   sys::swapByteOrder(method.method_types);
3552   sys::swapByteOrder(method.method_imp);
3553 }
3554 
3555 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3556   sys::swapByteOrder(protocol_list.next);
3557   sys::swapByteOrder(protocol_list.count);
3558 }
3559 
3560 inline void swapStruct(struct objc_protocol_t &protocol) {
3561   sys::swapByteOrder(protocol.isa);
3562   sys::swapByteOrder(protocol.protocol_name);
3563   sys::swapByteOrder(protocol.protocol_list);
3564   sys::swapByteOrder(protocol.instance_methods);
3565   sys::swapByteOrder(protocol.class_methods);
3566 }
3567 
3568 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3569   sys::swapByteOrder(mdl.count);
3570 }
3571 
3572 inline void swapStruct(struct objc_method_description_t &md) {
3573   sys::swapByteOrder(md.name);
3574   sys::swapByteOrder(md.types);
3575 }
3576 
3577 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3578                                                  struct DisassembleInfo *info);
3579 
3580 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3581 // to an Objective-C class and returns the class name.  It is also passed the
3582 // address of the pointer, so when the pointer is zero as it can be in an .o
3583 // file, that is used to look for an external relocation entry with a symbol
3584 // name.
3585 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3586                                               uint64_t ReferenceValue,
3587                                               struct DisassembleInfo *info) {
3588   const char *r;
3589   uint32_t offset, left;
3590   SectionRef S;
3591 
3592   // The pointer_value can be 0 in an object file and have a relocation
3593   // entry for the class symbol at the ReferenceValue (the address of the
3594   // pointer).
3595   if (pointer_value == 0) {
3596     r = get_pointer_64(ReferenceValue, offset, left, S, info);
3597     if (r == nullptr || left < sizeof(uint64_t))
3598       return nullptr;
3599     uint64_t n_value;
3600     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3601     if (symbol_name == nullptr)
3602       return nullptr;
3603     const char *class_name = strrchr(symbol_name, '$');
3604     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3605       return class_name + 2;
3606     else
3607       return nullptr;
3608   }
3609 
3610   // The case were the pointer_value is non-zero and points to a class defined
3611   // in this Mach-O file.
3612   r = get_pointer_64(pointer_value, offset, left, S, info);
3613   if (r == nullptr || left < sizeof(struct class64_t))
3614     return nullptr;
3615   struct class64_t c;
3616   memcpy(&c, r, sizeof(struct class64_t));
3617   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3618     swapStruct(c);
3619   if (c.data == 0)
3620     return nullptr;
3621   r = get_pointer_64(c.data, offset, left, S, info);
3622   if (r == nullptr || left < sizeof(struct class_ro64_t))
3623     return nullptr;
3624   struct class_ro64_t cro;
3625   memcpy(&cro, r, sizeof(struct class_ro64_t));
3626   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3627     swapStruct(cro);
3628   if (cro.name == 0)
3629     return nullptr;
3630   const char *name = get_pointer_64(cro.name, offset, left, S, info);
3631   return name;
3632 }
3633 
3634 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3635 // pointer to a cfstring and returns its name or nullptr.
3636 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3637                                                  struct DisassembleInfo *info) {
3638   const char *r, *name;
3639   uint32_t offset, left;
3640   SectionRef S;
3641   struct cfstring64_t cfs;
3642   uint64_t cfs_characters;
3643 
3644   r = get_pointer_64(ReferenceValue, offset, left, S, info);
3645   if (r == nullptr || left < sizeof(struct cfstring64_t))
3646     return nullptr;
3647   memcpy(&cfs, r, sizeof(struct cfstring64_t));
3648   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3649     swapStruct(cfs);
3650   if (cfs.characters == 0) {
3651     uint64_t n_value;
3652     const char *symbol_name = get_symbol_64(
3653         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3654     if (symbol_name == nullptr)
3655       return nullptr;
3656     cfs_characters = n_value;
3657   } else
3658     cfs_characters = cfs.characters;
3659   name = get_pointer_64(cfs_characters, offset, left, S, info);
3660 
3661   return name;
3662 }
3663 
3664 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3665 // of a pointer to an Objective-C selector reference when the pointer value is
3666 // zero as in a .o file and is likely to have a external relocation entry with
3667 // who's symbol's n_value is the real pointer to the selector name.  If that is
3668 // the case the real pointer to the selector name is returned else 0 is
3669 // returned
3670 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3671                                        struct DisassembleInfo *info) {
3672   uint32_t offset, left;
3673   SectionRef S;
3674 
3675   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3676   if (r == nullptr || left < sizeof(uint64_t))
3677     return 0;
3678   uint64_t n_value;
3679   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3680   if (symbol_name == nullptr)
3681     return 0;
3682   return n_value;
3683 }
3684 
3685 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3686                                     const char *sectname) {
3687   for (const SectionRef &Section : O->sections()) {
3688     StringRef SectName;
3689     Section.getName(SectName);
3690     DataRefImpl Ref = Section.getRawDataRefImpl();
3691     StringRef SegName = O->getSectionFinalSegmentName(Ref);
3692     if (SegName == segname && SectName == sectname)
3693       return Section;
3694   }
3695   return SectionRef();
3696 }
3697 
3698 static void
3699 walk_pointer_list_64(const char *listname, const SectionRef S,
3700                      MachOObjectFile *O, struct DisassembleInfo *info,
3701                      void (*func)(uint64_t, struct DisassembleInfo *info)) {
3702   if (S == SectionRef())
3703     return;
3704 
3705   StringRef SectName;
3706   S.getName(SectName);
3707   DataRefImpl Ref = S.getRawDataRefImpl();
3708   StringRef SegName = O->getSectionFinalSegmentName(Ref);
3709   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3710 
3711   StringRef BytesStr;
3712   S.getContents(BytesStr);
3713   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3714 
3715   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3716     uint32_t left = S.getSize() - i;
3717     uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3718     uint64_t p = 0;
3719     memcpy(&p, Contents + i, size);
3720     if (i + sizeof(uint64_t) > S.getSize())
3721       outs() << listname << " list pointer extends past end of (" << SegName
3722              << "," << SectName << ") section\n";
3723     outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3724 
3725     if (O->isLittleEndian() != sys::IsLittleEndianHost)
3726       sys::swapByteOrder(p);
3727 
3728     uint64_t n_value = 0;
3729     const char *name = get_symbol_64(i, S, info, n_value, p);
3730     if (name == nullptr)
3731       name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3732 
3733     if (n_value != 0) {
3734       outs() << format("0x%" PRIx64, n_value);
3735       if (p != 0)
3736         outs() << " + " << format("0x%" PRIx64, p);
3737     } else
3738       outs() << format("0x%" PRIx64, p);
3739     if (name != nullptr)
3740       outs() << " " << name;
3741     outs() << "\n";
3742 
3743     p += n_value;
3744     if (func)
3745       func(p, info);
3746   }
3747 }
3748 
3749 static void
3750 walk_pointer_list_32(const char *listname, const SectionRef S,
3751                      MachOObjectFile *O, struct DisassembleInfo *info,
3752                      void (*func)(uint32_t, struct DisassembleInfo *info)) {
3753   if (S == SectionRef())
3754     return;
3755 
3756   StringRef SectName;
3757   S.getName(SectName);
3758   DataRefImpl Ref = S.getRawDataRefImpl();
3759   StringRef SegName = O->getSectionFinalSegmentName(Ref);
3760   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3761 
3762   StringRef BytesStr;
3763   S.getContents(BytesStr);
3764   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3765 
3766   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3767     uint32_t left = S.getSize() - i;
3768     uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3769     uint32_t p = 0;
3770     memcpy(&p, Contents + i, size);
3771     if (i + sizeof(uint32_t) > S.getSize())
3772       outs() << listname << " list pointer extends past end of (" << SegName
3773              << "," << SectName << ") section\n";
3774     uint32_t Address = S.getAddress() + i;
3775     outs() << format("%08" PRIx32, Address) << " ";
3776 
3777     if (O->isLittleEndian() != sys::IsLittleEndianHost)
3778       sys::swapByteOrder(p);
3779     outs() << format("0x%" PRIx32, p);
3780 
3781     const char *name = get_symbol_32(i, S, info, p);
3782     if (name != nullptr)
3783       outs() << " " << name;
3784     outs() << "\n";
3785 
3786     if (func)
3787       func(p, info);
3788   }
3789 }
3790 
3791 static void print_layout_map(const char *layout_map, uint32_t left) {
3792   if (layout_map == nullptr)
3793     return;
3794   outs() << "                layout map: ";
3795   do {
3796     outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3797     left--;
3798     layout_map++;
3799   } while (*layout_map != '\0' && left != 0);
3800   outs() << "\n";
3801 }
3802 
3803 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3804   uint32_t offset, left;
3805   SectionRef S;
3806   const char *layout_map;
3807 
3808   if (p == 0)
3809     return;
3810   layout_map = get_pointer_64(p, offset, left, S, info);
3811   print_layout_map(layout_map, left);
3812 }
3813 
3814 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3815   uint32_t offset, left;
3816   SectionRef S;
3817   const char *layout_map;
3818 
3819   if (p == 0)
3820     return;
3821   layout_map = get_pointer_32(p, offset, left, S, info);
3822   print_layout_map(layout_map, left);
3823 }
3824 
3825 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3826                                   const char *indent) {
3827   struct method_list64_t ml;
3828   struct method64_t m;
3829   const char *r;
3830   uint32_t offset, xoffset, left, i;
3831   SectionRef S, xS;
3832   const char *name, *sym_name;
3833   uint64_t n_value;
3834 
3835   r = get_pointer_64(p, offset, left, S, info);
3836   if (r == nullptr)
3837     return;
3838   memset(&ml, '\0', sizeof(struct method_list64_t));
3839   if (left < sizeof(struct method_list64_t)) {
3840     memcpy(&ml, r, left);
3841     outs() << "   (method_list_t entends past the end of the section)\n";
3842   } else
3843     memcpy(&ml, r, sizeof(struct method_list64_t));
3844   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3845     swapStruct(ml);
3846   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
3847   outs() << indent << "\t\t     count " << ml.count << "\n";
3848 
3849   p += sizeof(struct method_list64_t);
3850   offset += sizeof(struct method_list64_t);
3851   for (i = 0; i < ml.count; i++) {
3852     r = get_pointer_64(p, offset, left, S, info);
3853     if (r == nullptr)
3854       return;
3855     memset(&m, '\0', sizeof(struct method64_t));
3856     if (left < sizeof(struct method64_t)) {
3857       memcpy(&m, r, left);
3858       outs() << indent << "   (method_t extends past the end of the section)\n";
3859     } else
3860       memcpy(&m, r, sizeof(struct method64_t));
3861     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3862       swapStruct(m);
3863 
3864     outs() << indent << "\t\t      name ";
3865     sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3866                              info, n_value, m.name);
3867     if (n_value != 0) {
3868       if (info->verbose && sym_name != nullptr)
3869         outs() << sym_name;
3870       else
3871         outs() << format("0x%" PRIx64, n_value);
3872       if (m.name != 0)
3873         outs() << " + " << format("0x%" PRIx64, m.name);
3874     } else
3875       outs() << format("0x%" PRIx64, m.name);
3876     name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3877     if (name != nullptr)
3878       outs() << format(" %.*s", left, name);
3879     outs() << "\n";
3880 
3881     outs() << indent << "\t\t     types ";
3882     sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3883                              info, n_value, m.types);
3884     if (n_value != 0) {
3885       if (info->verbose && sym_name != nullptr)
3886         outs() << sym_name;
3887       else
3888         outs() << format("0x%" PRIx64, n_value);
3889       if (m.types != 0)
3890         outs() << " + " << format("0x%" PRIx64, m.types);
3891     } else
3892       outs() << format("0x%" PRIx64, m.types);
3893     name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3894     if (name != nullptr)
3895       outs() << format(" %.*s", left, name);
3896     outs() << "\n";
3897 
3898     outs() << indent << "\t\t       imp ";
3899     name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3900                          n_value, m.imp);
3901     if (info->verbose && name == nullptr) {
3902       if (n_value != 0) {
3903         outs() << format("0x%" PRIx64, n_value) << " ";
3904         if (m.imp != 0)
3905           outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3906       } else
3907         outs() << format("0x%" PRIx64, m.imp) << " ";
3908     }
3909     if (name != nullptr)
3910       outs() << name;
3911     outs() << "\n";
3912 
3913     p += sizeof(struct method64_t);
3914     offset += sizeof(struct method64_t);
3915   }
3916 }
3917 
3918 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3919                                   const char *indent) {
3920   struct method_list32_t ml;
3921   struct method32_t m;
3922   const char *r, *name;
3923   uint32_t offset, xoffset, left, i;
3924   SectionRef S, xS;
3925 
3926   r = get_pointer_32(p, offset, left, S, info);
3927   if (r == nullptr)
3928     return;
3929   memset(&ml, '\0', sizeof(struct method_list32_t));
3930   if (left < sizeof(struct method_list32_t)) {
3931     memcpy(&ml, r, left);
3932     outs() << "   (method_list_t entends past the end of the section)\n";
3933   } else
3934     memcpy(&ml, r, sizeof(struct method_list32_t));
3935   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3936     swapStruct(ml);
3937   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
3938   outs() << indent << "\t\t     count " << ml.count << "\n";
3939 
3940   p += sizeof(struct method_list32_t);
3941   offset += sizeof(struct method_list32_t);
3942   for (i = 0; i < ml.count; i++) {
3943     r = get_pointer_32(p, offset, left, S, info);
3944     if (r == nullptr)
3945       return;
3946     memset(&m, '\0', sizeof(struct method32_t));
3947     if (left < sizeof(struct method32_t)) {
3948       memcpy(&ml, r, left);
3949       outs() << indent << "   (method_t entends past the end of the section)\n";
3950     } else
3951       memcpy(&m, r, sizeof(struct method32_t));
3952     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3953       swapStruct(m);
3954 
3955     outs() << indent << "\t\t      name " << format("0x%" PRIx32, m.name);
3956     name = get_pointer_32(m.name, xoffset, left, xS, info);
3957     if (name != nullptr)
3958       outs() << format(" %.*s", left, name);
3959     outs() << "\n";
3960 
3961     outs() << indent << "\t\t     types " << format("0x%" PRIx32, m.types);
3962     name = get_pointer_32(m.types, xoffset, left, xS, info);
3963     if (name != nullptr)
3964       outs() << format(" %.*s", left, name);
3965     outs() << "\n";
3966 
3967     outs() << indent << "\t\t       imp " << format("0x%" PRIx32, m.imp);
3968     name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3969                          m.imp);
3970     if (name != nullptr)
3971       outs() << " " << name;
3972     outs() << "\n";
3973 
3974     p += sizeof(struct method32_t);
3975     offset += sizeof(struct method32_t);
3976   }
3977 }
3978 
3979 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3980   uint32_t offset, left, xleft;
3981   SectionRef S;
3982   struct objc_method_list_t method_list;
3983   struct objc_method_t method;
3984   const char *r, *methods, *name, *SymbolName;
3985   int32_t i;
3986 
3987   r = get_pointer_32(p, offset, left, S, info, true);
3988   if (r == nullptr)
3989     return true;
3990 
3991   outs() << "\n";
3992   if (left > sizeof(struct objc_method_list_t)) {
3993     memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3994   } else {
3995     outs() << "\t\t objc_method_list extends past end of the section\n";
3996     memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3997     memcpy(&method_list, r, left);
3998   }
3999   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4000     swapStruct(method_list);
4001 
4002   outs() << "\t\t         obsolete "
4003          << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4004   outs() << "\t\t     method_count " << method_list.method_count << "\n";
4005 
4006   methods = r + sizeof(struct objc_method_list_t);
4007   for (i = 0; i < method_list.method_count; i++) {
4008     if ((i + 1) * sizeof(struct objc_method_t) > left) {
4009       outs() << "\t\t remaining method's extend past the of the section\n";
4010       break;
4011     }
4012     memcpy(&method, methods + i * sizeof(struct objc_method_t),
4013            sizeof(struct objc_method_t));
4014     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4015       swapStruct(method);
4016 
4017     outs() << "\t\t      method_name "
4018            << format("0x%08" PRIx32, method.method_name);
4019     if (info->verbose) {
4020       name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4021       if (name != nullptr)
4022         outs() << format(" %.*s", xleft, name);
4023       else
4024         outs() << " (not in an __OBJC section)";
4025     }
4026     outs() << "\n";
4027 
4028     outs() << "\t\t     method_types "
4029            << format("0x%08" PRIx32, method.method_types);
4030     if (info->verbose) {
4031       name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4032       if (name != nullptr)
4033         outs() << format(" %.*s", xleft, name);
4034       else
4035         outs() << " (not in an __OBJC section)";
4036     }
4037     outs() << "\n";
4038 
4039     outs() << "\t\t       method_imp "
4040            << format("0x%08" PRIx32, method.method_imp) << " ";
4041     if (info->verbose) {
4042       SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4043       if (SymbolName != nullptr)
4044         outs() << SymbolName;
4045     }
4046     outs() << "\n";
4047   }
4048   return false;
4049 }
4050 
4051 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4052   struct protocol_list64_t pl;
4053   uint64_t q, n_value;
4054   struct protocol64_t pc;
4055   const char *r;
4056   uint32_t offset, xoffset, left, i;
4057   SectionRef S, xS;
4058   const char *name, *sym_name;
4059 
4060   r = get_pointer_64(p, offset, left, S, info);
4061   if (r == nullptr)
4062     return;
4063   memset(&pl, '\0', sizeof(struct protocol_list64_t));
4064   if (left < sizeof(struct protocol_list64_t)) {
4065     memcpy(&pl, r, left);
4066     outs() << "   (protocol_list_t entends past the end of the section)\n";
4067   } else
4068     memcpy(&pl, r, sizeof(struct protocol_list64_t));
4069   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4070     swapStruct(pl);
4071   outs() << "                      count " << pl.count << "\n";
4072 
4073   p += sizeof(struct protocol_list64_t);
4074   offset += sizeof(struct protocol_list64_t);
4075   for (i = 0; i < pl.count; i++) {
4076     r = get_pointer_64(p, offset, left, S, info);
4077     if (r == nullptr)
4078       return;
4079     q = 0;
4080     if (left < sizeof(uint64_t)) {
4081       memcpy(&q, r, left);
4082       outs() << "   (protocol_t * entends past the end of the section)\n";
4083     } else
4084       memcpy(&q, r, sizeof(uint64_t));
4085     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4086       sys::swapByteOrder(q);
4087 
4088     outs() << "\t\t      list[" << i << "] ";
4089     sym_name = get_symbol_64(offset, S, info, n_value, q);
4090     if (n_value != 0) {
4091       if (info->verbose && sym_name != nullptr)
4092         outs() << sym_name;
4093       else
4094         outs() << format("0x%" PRIx64, n_value);
4095       if (q != 0)
4096         outs() << " + " << format("0x%" PRIx64, q);
4097     } else
4098       outs() << format("0x%" PRIx64, q);
4099     outs() << " (struct protocol_t *)\n";
4100 
4101     r = get_pointer_64(q + n_value, offset, left, S, info);
4102     if (r == nullptr)
4103       return;
4104     memset(&pc, '\0', sizeof(struct protocol64_t));
4105     if (left < sizeof(struct protocol64_t)) {
4106       memcpy(&pc, r, left);
4107       outs() << "   (protocol_t entends past the end of the section)\n";
4108     } else
4109       memcpy(&pc, r, sizeof(struct protocol64_t));
4110     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4111       swapStruct(pc);
4112 
4113     outs() << "\t\t\t      isa " << format("0x%" PRIx64, pc.isa) << "\n";
4114 
4115     outs() << "\t\t\t     name ";
4116     sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4117                              info, n_value, pc.name);
4118     if (n_value != 0) {
4119       if (info->verbose && sym_name != nullptr)
4120         outs() << sym_name;
4121       else
4122         outs() << format("0x%" PRIx64, n_value);
4123       if (pc.name != 0)
4124         outs() << " + " << format("0x%" PRIx64, pc.name);
4125     } else
4126       outs() << format("0x%" PRIx64, pc.name);
4127     name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4128     if (name != nullptr)
4129       outs() << format(" %.*s", left, name);
4130     outs() << "\n";
4131 
4132     outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4133 
4134     outs() << "\t\t  instanceMethods ";
4135     sym_name =
4136         get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4137                       S, info, n_value, pc.instanceMethods);
4138     if (n_value != 0) {
4139       if (info->verbose && sym_name != nullptr)
4140         outs() << sym_name;
4141       else
4142         outs() << format("0x%" PRIx64, n_value);
4143       if (pc.instanceMethods != 0)
4144         outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4145     } else
4146       outs() << format("0x%" PRIx64, pc.instanceMethods);
4147     outs() << " (struct method_list_t *)\n";
4148     if (pc.instanceMethods + n_value != 0)
4149       print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4150 
4151     outs() << "\t\t     classMethods ";
4152     sym_name =
4153         get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4154                       info, n_value, pc.classMethods);
4155     if (n_value != 0) {
4156       if (info->verbose && sym_name != nullptr)
4157         outs() << sym_name;
4158       else
4159         outs() << format("0x%" PRIx64, n_value);
4160       if (pc.classMethods != 0)
4161         outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4162     } else
4163       outs() << format("0x%" PRIx64, pc.classMethods);
4164     outs() << " (struct method_list_t *)\n";
4165     if (pc.classMethods + n_value != 0)
4166       print_method_list64_t(pc.classMethods + n_value, info, "\t");
4167 
4168     outs() << "\t  optionalInstanceMethods "
4169            << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4170     outs() << "\t     optionalClassMethods "
4171            << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4172     outs() << "\t       instanceProperties "
4173            << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4174 
4175     p += sizeof(uint64_t);
4176     offset += sizeof(uint64_t);
4177   }
4178 }
4179 
4180 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4181   struct protocol_list32_t pl;
4182   uint32_t q;
4183   struct protocol32_t pc;
4184   const char *r;
4185   uint32_t offset, xoffset, left, i;
4186   SectionRef S, xS;
4187   const char *name;
4188 
4189   r = get_pointer_32(p, offset, left, S, info);
4190   if (r == nullptr)
4191     return;
4192   memset(&pl, '\0', sizeof(struct protocol_list32_t));
4193   if (left < sizeof(struct protocol_list32_t)) {
4194     memcpy(&pl, r, left);
4195     outs() << "   (protocol_list_t entends past the end of the section)\n";
4196   } else
4197     memcpy(&pl, r, sizeof(struct protocol_list32_t));
4198   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4199     swapStruct(pl);
4200   outs() << "                      count " << pl.count << "\n";
4201 
4202   p += sizeof(struct protocol_list32_t);
4203   offset += sizeof(struct protocol_list32_t);
4204   for (i = 0; i < pl.count; i++) {
4205     r = get_pointer_32(p, offset, left, S, info);
4206     if (r == nullptr)
4207       return;
4208     q = 0;
4209     if (left < sizeof(uint32_t)) {
4210       memcpy(&q, r, left);
4211       outs() << "   (protocol_t * entends past the end of the section)\n";
4212     } else
4213       memcpy(&q, r, sizeof(uint32_t));
4214     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4215       sys::swapByteOrder(q);
4216     outs() << "\t\t      list[" << i << "] " << format("0x%" PRIx32, q)
4217            << " (struct protocol_t *)\n";
4218     r = get_pointer_32(q, offset, left, S, info);
4219     if (r == nullptr)
4220       return;
4221     memset(&pc, '\0', sizeof(struct protocol32_t));
4222     if (left < sizeof(struct protocol32_t)) {
4223       memcpy(&pc, r, left);
4224       outs() << "   (protocol_t entends past the end of the section)\n";
4225     } else
4226       memcpy(&pc, r, sizeof(struct protocol32_t));
4227     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4228       swapStruct(pc);
4229     outs() << "\t\t\t      isa " << format("0x%" PRIx32, pc.isa) << "\n";
4230     outs() << "\t\t\t     name " << format("0x%" PRIx32, pc.name);
4231     name = get_pointer_32(pc.name, xoffset, left, xS, info);
4232     if (name != nullptr)
4233       outs() << format(" %.*s", left, name);
4234     outs() << "\n";
4235     outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4236     outs() << "\t\t  instanceMethods "
4237            << format("0x%" PRIx32, pc.instanceMethods)
4238            << " (struct method_list_t *)\n";
4239     if (pc.instanceMethods != 0)
4240       print_method_list32_t(pc.instanceMethods, info, "\t");
4241     outs() << "\t\t     classMethods " << format("0x%" PRIx32, pc.classMethods)
4242            << " (struct method_list_t *)\n";
4243     if (pc.classMethods != 0)
4244       print_method_list32_t(pc.classMethods, info, "\t");
4245     outs() << "\t  optionalInstanceMethods "
4246            << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4247     outs() << "\t     optionalClassMethods "
4248            << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4249     outs() << "\t       instanceProperties "
4250            << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4251     p += sizeof(uint32_t);
4252     offset += sizeof(uint32_t);
4253   }
4254 }
4255 
4256 static void print_indent(uint32_t indent) {
4257   for (uint32_t i = 0; i < indent;) {
4258     if (indent - i >= 8) {
4259       outs() << "\t";
4260       i += 8;
4261     } else {
4262       for (uint32_t j = i; j < indent; j++)
4263         outs() << " ";
4264       return;
4265     }
4266   }
4267 }
4268 
4269 static bool print_method_description_list(uint32_t p, uint32_t indent,
4270                                           struct DisassembleInfo *info) {
4271   uint32_t offset, left, xleft;
4272   SectionRef S;
4273   struct objc_method_description_list_t mdl;
4274   struct objc_method_description_t md;
4275   const char *r, *list, *name;
4276   int32_t i;
4277 
4278   r = get_pointer_32(p, offset, left, S, info, true);
4279   if (r == nullptr)
4280     return true;
4281 
4282   outs() << "\n";
4283   if (left > sizeof(struct objc_method_description_list_t)) {
4284     memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4285   } else {
4286     print_indent(indent);
4287     outs() << " objc_method_description_list extends past end of the section\n";
4288     memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4289     memcpy(&mdl, r, left);
4290   }
4291   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4292     swapStruct(mdl);
4293 
4294   print_indent(indent);
4295   outs() << "        count " << mdl.count << "\n";
4296 
4297   list = r + sizeof(struct objc_method_description_list_t);
4298   for (i = 0; i < mdl.count; i++) {
4299     if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4300       print_indent(indent);
4301       outs() << " remaining list entries extend past the of the section\n";
4302       break;
4303     }
4304     print_indent(indent);
4305     outs() << "        list[" << i << "]\n";
4306     memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4307            sizeof(struct objc_method_description_t));
4308     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4309       swapStruct(md);
4310 
4311     print_indent(indent);
4312     outs() << "             name " << format("0x%08" PRIx32, md.name);
4313     if (info->verbose) {
4314       name = get_pointer_32(md.name, offset, xleft, S, info, true);
4315       if (name != nullptr)
4316         outs() << format(" %.*s", xleft, name);
4317       else
4318         outs() << " (not in an __OBJC section)";
4319     }
4320     outs() << "\n";
4321 
4322     print_indent(indent);
4323     outs() << "            types " << format("0x%08" PRIx32, md.types);
4324     if (info->verbose) {
4325       name = get_pointer_32(md.types, offset, xleft, S, info, true);
4326       if (name != nullptr)
4327         outs() << format(" %.*s", xleft, name);
4328       else
4329         outs() << " (not in an __OBJC section)";
4330     }
4331     outs() << "\n";
4332   }
4333   return false;
4334 }
4335 
4336 static bool print_protocol_list(uint32_t p, uint32_t indent,
4337                                 struct DisassembleInfo *info);
4338 
4339 static bool print_protocol(uint32_t p, uint32_t indent,
4340                            struct DisassembleInfo *info) {
4341   uint32_t offset, left;
4342   SectionRef S;
4343   struct objc_protocol_t protocol;
4344   const char *r, *name;
4345 
4346   r = get_pointer_32(p, offset, left, S, info, true);
4347   if (r == nullptr)
4348     return true;
4349 
4350   outs() << "\n";
4351   if (left >= sizeof(struct objc_protocol_t)) {
4352     memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4353   } else {
4354     print_indent(indent);
4355     outs() << "            Protocol extends past end of the section\n";
4356     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4357     memcpy(&protocol, r, left);
4358   }
4359   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4360     swapStruct(protocol);
4361 
4362   print_indent(indent);
4363   outs() << "              isa " << format("0x%08" PRIx32, protocol.isa)
4364          << "\n";
4365 
4366   print_indent(indent);
4367   outs() << "    protocol_name "
4368          << format("0x%08" PRIx32, protocol.protocol_name);
4369   if (info->verbose) {
4370     name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4371     if (name != nullptr)
4372       outs() << format(" %.*s", left, name);
4373     else
4374       outs() << " (not in an __OBJC section)";
4375   }
4376   outs() << "\n";
4377 
4378   print_indent(indent);
4379   outs() << "    protocol_list "
4380          << format("0x%08" PRIx32, protocol.protocol_list);
4381   if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4382     outs() << " (not in an __OBJC section)\n";
4383 
4384   print_indent(indent);
4385   outs() << " instance_methods "
4386          << format("0x%08" PRIx32, protocol.instance_methods);
4387   if (print_method_description_list(protocol.instance_methods, indent, info))
4388     outs() << " (not in an __OBJC section)\n";
4389 
4390   print_indent(indent);
4391   outs() << "    class_methods "
4392          << format("0x%08" PRIx32, protocol.class_methods);
4393   if (print_method_description_list(protocol.class_methods, indent, info))
4394     outs() << " (not in an __OBJC section)\n";
4395 
4396   return false;
4397 }
4398 
4399 static bool print_protocol_list(uint32_t p, uint32_t indent,
4400                                 struct DisassembleInfo *info) {
4401   uint32_t offset, left, l;
4402   SectionRef S;
4403   struct objc_protocol_list_t protocol_list;
4404   const char *r, *list;
4405   int32_t i;
4406 
4407   r = get_pointer_32(p, offset, left, S, info, true);
4408   if (r == nullptr)
4409     return true;
4410 
4411   outs() << "\n";
4412   if (left > sizeof(struct objc_protocol_list_t)) {
4413     memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4414   } else {
4415     outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4416     memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4417     memcpy(&protocol_list, r, left);
4418   }
4419   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4420     swapStruct(protocol_list);
4421 
4422   print_indent(indent);
4423   outs() << "         next " << format("0x%08" PRIx32, protocol_list.next)
4424          << "\n";
4425   print_indent(indent);
4426   outs() << "        count " << protocol_list.count << "\n";
4427 
4428   list = r + sizeof(struct objc_protocol_list_t);
4429   for (i = 0; i < protocol_list.count; i++) {
4430     if ((i + 1) * sizeof(uint32_t) > left) {
4431       outs() << "\t\t remaining list entries extend past the of the section\n";
4432       break;
4433     }
4434     memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4435     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4436       sys::swapByteOrder(l);
4437 
4438     print_indent(indent);
4439     outs() << "      list[" << i << "] " << format("0x%08" PRIx32, l);
4440     if (print_protocol(l, indent, info))
4441       outs() << "(not in an __OBJC section)\n";
4442   }
4443   return false;
4444 }
4445 
4446 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4447   struct ivar_list64_t il;
4448   struct ivar64_t i;
4449   const char *r;
4450   uint32_t offset, xoffset, left, j;
4451   SectionRef S, xS;
4452   const char *name, *sym_name, *ivar_offset_p;
4453   uint64_t ivar_offset, n_value;
4454 
4455   r = get_pointer_64(p, offset, left, S, info);
4456   if (r == nullptr)
4457     return;
4458   memset(&il, '\0', sizeof(struct ivar_list64_t));
4459   if (left < sizeof(struct ivar_list64_t)) {
4460     memcpy(&il, r, left);
4461     outs() << "   (ivar_list_t entends past the end of the section)\n";
4462   } else
4463     memcpy(&il, r, sizeof(struct ivar_list64_t));
4464   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4465     swapStruct(il);
4466   outs() << "                    entsize " << il.entsize << "\n";
4467   outs() << "                      count " << il.count << "\n";
4468 
4469   p += sizeof(struct ivar_list64_t);
4470   offset += sizeof(struct ivar_list64_t);
4471   for (j = 0; j < il.count; j++) {
4472     r = get_pointer_64(p, offset, left, S, info);
4473     if (r == nullptr)
4474       return;
4475     memset(&i, '\0', sizeof(struct ivar64_t));
4476     if (left < sizeof(struct ivar64_t)) {
4477       memcpy(&i, r, left);
4478       outs() << "   (ivar_t entends past the end of the section)\n";
4479     } else
4480       memcpy(&i, r, sizeof(struct ivar64_t));
4481     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4482       swapStruct(i);
4483 
4484     outs() << "\t\t\t   offset ";
4485     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4486                              info, n_value, i.offset);
4487     if (n_value != 0) {
4488       if (info->verbose && sym_name != nullptr)
4489         outs() << sym_name;
4490       else
4491         outs() << format("0x%" PRIx64, n_value);
4492       if (i.offset != 0)
4493         outs() << " + " << format("0x%" PRIx64, i.offset);
4494     } else
4495       outs() << format("0x%" PRIx64, i.offset);
4496     ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4497     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4498       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4499       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4500         sys::swapByteOrder(ivar_offset);
4501       outs() << " " << ivar_offset << "\n";
4502     } else
4503       outs() << "\n";
4504 
4505     outs() << "\t\t\t     name ";
4506     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4507                              n_value, i.name);
4508     if (n_value != 0) {
4509       if (info->verbose && sym_name != nullptr)
4510         outs() << sym_name;
4511       else
4512         outs() << format("0x%" PRIx64, n_value);
4513       if (i.name != 0)
4514         outs() << " + " << format("0x%" PRIx64, i.name);
4515     } else
4516       outs() << format("0x%" PRIx64, i.name);
4517     name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4518     if (name != nullptr)
4519       outs() << format(" %.*s", left, name);
4520     outs() << "\n";
4521 
4522     outs() << "\t\t\t     type ";
4523     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4524                              n_value, i.name);
4525     name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4526     if (n_value != 0) {
4527       if (info->verbose && sym_name != nullptr)
4528         outs() << sym_name;
4529       else
4530         outs() << format("0x%" PRIx64, n_value);
4531       if (i.type != 0)
4532         outs() << " + " << format("0x%" PRIx64, i.type);
4533     } else
4534       outs() << format("0x%" PRIx64, i.type);
4535     if (name != nullptr)
4536       outs() << format(" %.*s", left, name);
4537     outs() << "\n";
4538 
4539     outs() << "\t\t\talignment " << i.alignment << "\n";
4540     outs() << "\t\t\t     size " << i.size << "\n";
4541 
4542     p += sizeof(struct ivar64_t);
4543     offset += sizeof(struct ivar64_t);
4544   }
4545 }
4546 
4547 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4548   struct ivar_list32_t il;
4549   struct ivar32_t i;
4550   const char *r;
4551   uint32_t offset, xoffset, left, j;
4552   SectionRef S, xS;
4553   const char *name, *ivar_offset_p;
4554   uint32_t ivar_offset;
4555 
4556   r = get_pointer_32(p, offset, left, S, info);
4557   if (r == nullptr)
4558     return;
4559   memset(&il, '\0', sizeof(struct ivar_list32_t));
4560   if (left < sizeof(struct ivar_list32_t)) {
4561     memcpy(&il, r, left);
4562     outs() << "   (ivar_list_t entends past the end of the section)\n";
4563   } else
4564     memcpy(&il, r, sizeof(struct ivar_list32_t));
4565   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4566     swapStruct(il);
4567   outs() << "                    entsize " << il.entsize << "\n";
4568   outs() << "                      count " << il.count << "\n";
4569 
4570   p += sizeof(struct ivar_list32_t);
4571   offset += sizeof(struct ivar_list32_t);
4572   for (j = 0; j < il.count; j++) {
4573     r = get_pointer_32(p, offset, left, S, info);
4574     if (r == nullptr)
4575       return;
4576     memset(&i, '\0', sizeof(struct ivar32_t));
4577     if (left < sizeof(struct ivar32_t)) {
4578       memcpy(&i, r, left);
4579       outs() << "   (ivar_t entends past the end of the section)\n";
4580     } else
4581       memcpy(&i, r, sizeof(struct ivar32_t));
4582     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4583       swapStruct(i);
4584 
4585     outs() << "\t\t\t   offset " << format("0x%" PRIx32, i.offset);
4586     ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4587     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4588       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4589       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4590         sys::swapByteOrder(ivar_offset);
4591       outs() << " " << ivar_offset << "\n";
4592     } else
4593       outs() << "\n";
4594 
4595     outs() << "\t\t\t     name " << format("0x%" PRIx32, i.name);
4596     name = get_pointer_32(i.name, xoffset, left, xS, info);
4597     if (name != nullptr)
4598       outs() << format(" %.*s", left, name);
4599     outs() << "\n";
4600 
4601     outs() << "\t\t\t     type " << format("0x%" PRIx32, i.type);
4602     name = get_pointer_32(i.type, xoffset, left, xS, info);
4603     if (name != nullptr)
4604       outs() << format(" %.*s", left, name);
4605     outs() << "\n";
4606 
4607     outs() << "\t\t\talignment " << i.alignment << "\n";
4608     outs() << "\t\t\t     size " << i.size << "\n";
4609 
4610     p += sizeof(struct ivar32_t);
4611     offset += sizeof(struct ivar32_t);
4612   }
4613 }
4614 
4615 static void print_objc_property_list64(uint64_t p,
4616                                        struct DisassembleInfo *info) {
4617   struct objc_property_list64 opl;
4618   struct objc_property64 op;
4619   const char *r;
4620   uint32_t offset, xoffset, left, j;
4621   SectionRef S, xS;
4622   const char *name, *sym_name;
4623   uint64_t n_value;
4624 
4625   r = get_pointer_64(p, offset, left, S, info);
4626   if (r == nullptr)
4627     return;
4628   memset(&opl, '\0', sizeof(struct objc_property_list64));
4629   if (left < sizeof(struct objc_property_list64)) {
4630     memcpy(&opl, r, left);
4631     outs() << "   (objc_property_list entends past the end of the section)\n";
4632   } else
4633     memcpy(&opl, r, sizeof(struct objc_property_list64));
4634   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4635     swapStruct(opl);
4636   outs() << "                    entsize " << opl.entsize << "\n";
4637   outs() << "                      count " << opl.count << "\n";
4638 
4639   p += sizeof(struct objc_property_list64);
4640   offset += sizeof(struct objc_property_list64);
4641   for (j = 0; j < opl.count; j++) {
4642     r = get_pointer_64(p, offset, left, S, info);
4643     if (r == nullptr)
4644       return;
4645     memset(&op, '\0', sizeof(struct objc_property64));
4646     if (left < sizeof(struct objc_property64)) {
4647       memcpy(&op, r, left);
4648       outs() << "   (objc_property entends past the end of the section)\n";
4649     } else
4650       memcpy(&op, r, sizeof(struct objc_property64));
4651     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4652       swapStruct(op);
4653 
4654     outs() << "\t\t\t     name ";
4655     sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4656                              info, n_value, op.name);
4657     if (n_value != 0) {
4658       if (info->verbose && sym_name != nullptr)
4659         outs() << sym_name;
4660       else
4661         outs() << format("0x%" PRIx64, n_value);
4662       if (op.name != 0)
4663         outs() << " + " << format("0x%" PRIx64, op.name);
4664     } else
4665       outs() << format("0x%" PRIx64, op.name);
4666     name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4667     if (name != nullptr)
4668       outs() << format(" %.*s", left, name);
4669     outs() << "\n";
4670 
4671     outs() << "\t\t\tattributes ";
4672     sym_name =
4673         get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4674                       info, n_value, op.attributes);
4675     if (n_value != 0) {
4676       if (info->verbose && sym_name != nullptr)
4677         outs() << sym_name;
4678       else
4679         outs() << format("0x%" PRIx64, n_value);
4680       if (op.attributes != 0)
4681         outs() << " + " << format("0x%" PRIx64, op.attributes);
4682     } else
4683       outs() << format("0x%" PRIx64, op.attributes);
4684     name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4685     if (name != nullptr)
4686       outs() << format(" %.*s", left, name);
4687     outs() << "\n";
4688 
4689     p += sizeof(struct objc_property64);
4690     offset += sizeof(struct objc_property64);
4691   }
4692 }
4693 
4694 static void print_objc_property_list32(uint32_t p,
4695                                        struct DisassembleInfo *info) {
4696   struct objc_property_list32 opl;
4697   struct objc_property32 op;
4698   const char *r;
4699   uint32_t offset, xoffset, left, j;
4700   SectionRef S, xS;
4701   const char *name;
4702 
4703   r = get_pointer_32(p, offset, left, S, info);
4704   if (r == nullptr)
4705     return;
4706   memset(&opl, '\0', sizeof(struct objc_property_list32));
4707   if (left < sizeof(struct objc_property_list32)) {
4708     memcpy(&opl, r, left);
4709     outs() << "   (objc_property_list entends past the end of the section)\n";
4710   } else
4711     memcpy(&opl, r, sizeof(struct objc_property_list32));
4712   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4713     swapStruct(opl);
4714   outs() << "                    entsize " << opl.entsize << "\n";
4715   outs() << "                      count " << opl.count << "\n";
4716 
4717   p += sizeof(struct objc_property_list32);
4718   offset += sizeof(struct objc_property_list32);
4719   for (j = 0; j < opl.count; j++) {
4720     r = get_pointer_32(p, offset, left, S, info);
4721     if (r == nullptr)
4722       return;
4723     memset(&op, '\0', sizeof(struct objc_property32));
4724     if (left < sizeof(struct objc_property32)) {
4725       memcpy(&op, r, left);
4726       outs() << "   (objc_property entends past the end of the section)\n";
4727     } else
4728       memcpy(&op, r, sizeof(struct objc_property32));
4729     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4730       swapStruct(op);
4731 
4732     outs() << "\t\t\t     name " << format("0x%" PRIx32, op.name);
4733     name = get_pointer_32(op.name, xoffset, left, xS, info);
4734     if (name != nullptr)
4735       outs() << format(" %.*s", left, name);
4736     outs() << "\n";
4737 
4738     outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4739     name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4740     if (name != nullptr)
4741       outs() << format(" %.*s", left, name);
4742     outs() << "\n";
4743 
4744     p += sizeof(struct objc_property32);
4745     offset += sizeof(struct objc_property32);
4746   }
4747 }
4748 
4749 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4750                                bool &is_meta_class) {
4751   struct class_ro64_t cro;
4752   const char *r;
4753   uint32_t offset, xoffset, left;
4754   SectionRef S, xS;
4755   const char *name, *sym_name;
4756   uint64_t n_value;
4757 
4758   r = get_pointer_64(p, offset, left, S, info);
4759   if (r == nullptr || left < sizeof(struct class_ro64_t))
4760     return false;
4761   memcpy(&cro, r, sizeof(struct class_ro64_t));
4762   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4763     swapStruct(cro);
4764   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
4765   if (cro.flags & RO_META)
4766     outs() << " RO_META";
4767   if (cro.flags & RO_ROOT)
4768     outs() << " RO_ROOT";
4769   if (cro.flags & RO_HAS_CXX_STRUCTORS)
4770     outs() << " RO_HAS_CXX_STRUCTORS";
4771   outs() << "\n";
4772   outs() << "            instanceStart " << cro.instanceStart << "\n";
4773   outs() << "             instanceSize " << cro.instanceSize << "\n";
4774   outs() << "                 reserved " << format("0x%" PRIx32, cro.reserved)
4775          << "\n";
4776   outs() << "               ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4777          << "\n";
4778   print_layout_map64(cro.ivarLayout, info);
4779 
4780   outs() << "                     name ";
4781   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4782                            info, n_value, cro.name);
4783   if (n_value != 0) {
4784     if (info->verbose && sym_name != nullptr)
4785       outs() << sym_name;
4786     else
4787       outs() << format("0x%" PRIx64, n_value);
4788     if (cro.name != 0)
4789       outs() << " + " << format("0x%" PRIx64, cro.name);
4790   } else
4791     outs() << format("0x%" PRIx64, cro.name);
4792   name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4793   if (name != nullptr)
4794     outs() << format(" %.*s", left, name);
4795   outs() << "\n";
4796 
4797   outs() << "              baseMethods ";
4798   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4799                            S, info, n_value, cro.baseMethods);
4800   if (n_value != 0) {
4801     if (info->verbose && sym_name != nullptr)
4802       outs() << sym_name;
4803     else
4804       outs() << format("0x%" PRIx64, n_value);
4805     if (cro.baseMethods != 0)
4806       outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4807   } else
4808     outs() << format("0x%" PRIx64, cro.baseMethods);
4809   outs() << " (struct method_list_t *)\n";
4810   if (cro.baseMethods + n_value != 0)
4811     print_method_list64_t(cro.baseMethods + n_value, info, "");
4812 
4813   outs() << "            baseProtocols ";
4814   sym_name =
4815       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4816                     info, n_value, cro.baseProtocols);
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 (cro.baseProtocols != 0)
4823       outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4824   } else
4825     outs() << format("0x%" PRIx64, cro.baseProtocols);
4826   outs() << "\n";
4827   if (cro.baseProtocols + n_value != 0)
4828     print_protocol_list64_t(cro.baseProtocols + n_value, info);
4829 
4830   outs() << "                    ivars ";
4831   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4832                            info, n_value, cro.ivars);
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 (cro.ivars != 0)
4839       outs() << " + " << format("0x%" PRIx64, cro.ivars);
4840   } else
4841     outs() << format("0x%" PRIx64, cro.ivars);
4842   outs() << "\n";
4843   if (cro.ivars + n_value != 0)
4844     print_ivar_list64_t(cro.ivars + n_value, info);
4845 
4846   outs() << "           weakIvarLayout ";
4847   sym_name =
4848       get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4849                     info, n_value, cro.weakIvarLayout);
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 (cro.weakIvarLayout != 0)
4856       outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4857   } else
4858     outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4859   outs() << "\n";
4860   print_layout_map64(cro.weakIvarLayout + n_value, info);
4861 
4862   outs() << "           baseProperties ";
4863   sym_name =
4864       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4865                     info, n_value, cro.baseProperties);
4866   if (n_value != 0) {
4867     if (info->verbose && sym_name != nullptr)
4868       outs() << sym_name;
4869     else
4870       outs() << format("0x%" PRIx64, n_value);
4871     if (cro.baseProperties != 0)
4872       outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4873   } else
4874     outs() << format("0x%" PRIx64, cro.baseProperties);
4875   outs() << "\n";
4876   if (cro.baseProperties + n_value != 0)
4877     print_objc_property_list64(cro.baseProperties + n_value, info);
4878 
4879   is_meta_class = (cro.flags & RO_META) != 0;
4880   return true;
4881 }
4882 
4883 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4884                                bool &is_meta_class) {
4885   struct class_ro32_t cro;
4886   const char *r;
4887   uint32_t offset, xoffset, left;
4888   SectionRef S, xS;
4889   const char *name;
4890 
4891   r = get_pointer_32(p, offset, left, S, info);
4892   if (r == nullptr)
4893     return false;
4894   memset(&cro, '\0', sizeof(struct class_ro32_t));
4895   if (left < sizeof(struct class_ro32_t)) {
4896     memcpy(&cro, r, left);
4897     outs() << "   (class_ro_t entends past the end of the section)\n";
4898   } else
4899     memcpy(&cro, r, sizeof(struct class_ro32_t));
4900   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4901     swapStruct(cro);
4902   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
4903   if (cro.flags & RO_META)
4904     outs() << " RO_META";
4905   if (cro.flags & RO_ROOT)
4906     outs() << " RO_ROOT";
4907   if (cro.flags & RO_HAS_CXX_STRUCTORS)
4908     outs() << " RO_HAS_CXX_STRUCTORS";
4909   outs() << "\n";
4910   outs() << "            instanceStart " << cro.instanceStart << "\n";
4911   outs() << "             instanceSize " << cro.instanceSize << "\n";
4912   outs() << "               ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4913          << "\n";
4914   print_layout_map32(cro.ivarLayout, info);
4915 
4916   outs() << "                     name " << format("0x%" PRIx32, cro.name);
4917   name = get_pointer_32(cro.name, xoffset, left, xS, info);
4918   if (name != nullptr)
4919     outs() << format(" %.*s", left, name);
4920   outs() << "\n";
4921 
4922   outs() << "              baseMethods "
4923          << format("0x%" PRIx32, cro.baseMethods)
4924          << " (struct method_list_t *)\n";
4925   if (cro.baseMethods != 0)
4926     print_method_list32_t(cro.baseMethods, info, "");
4927 
4928   outs() << "            baseProtocols "
4929          << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4930   if (cro.baseProtocols != 0)
4931     print_protocol_list32_t(cro.baseProtocols, info);
4932   outs() << "                    ivars " << format("0x%" PRIx32, cro.ivars)
4933          << "\n";
4934   if (cro.ivars != 0)
4935     print_ivar_list32_t(cro.ivars, info);
4936   outs() << "           weakIvarLayout "
4937          << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4938   print_layout_map32(cro.weakIvarLayout, info);
4939   outs() << "           baseProperties "
4940          << format("0x%" PRIx32, cro.baseProperties) << "\n";
4941   if (cro.baseProperties != 0)
4942     print_objc_property_list32(cro.baseProperties, info);
4943   is_meta_class = (cro.flags & RO_META) != 0;
4944   return true;
4945 }
4946 
4947 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4948   struct class64_t c;
4949   const char *r;
4950   uint32_t offset, left;
4951   SectionRef S;
4952   const char *name;
4953   uint64_t isa_n_value, n_value;
4954 
4955   r = get_pointer_64(p, offset, left, S, info);
4956   if (r == nullptr || left < sizeof(struct class64_t))
4957     return;
4958   memcpy(&c, r, sizeof(struct class64_t));
4959   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4960     swapStruct(c);
4961 
4962   outs() << "           isa " << format("0x%" PRIx64, c.isa);
4963   name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4964                        isa_n_value, c.isa);
4965   if (name != nullptr)
4966     outs() << " " << name;
4967   outs() << "\n";
4968 
4969   outs() << "    superclass " << format("0x%" PRIx64, c.superclass);
4970   name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4971                        n_value, c.superclass);
4972   if (name != nullptr)
4973     outs() << " " << name;
4974   else {
4975     name = get_dyld_bind_info_symbolname(S.getAddress() +
4976              offset + offsetof(struct class64_t, superclass), info);
4977     if (name != nullptr)
4978       outs() << " " << name;
4979   }
4980   outs() << "\n";
4981 
4982   outs() << "         cache " << format("0x%" PRIx64, c.cache);
4983   name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4984                        n_value, c.cache);
4985   if (name != nullptr)
4986     outs() << " " << name;
4987   outs() << "\n";
4988 
4989   outs() << "        vtable " << format("0x%" PRIx64, c.vtable);
4990   name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4991                        n_value, c.vtable);
4992   if (name != nullptr)
4993     outs() << " " << name;
4994   outs() << "\n";
4995 
4996   name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4997                        n_value, c.data);
4998   outs() << "          data ";
4999   if (n_value != 0) {
5000     if (info->verbose && name != nullptr)
5001       outs() << name;
5002     else
5003       outs() << format("0x%" PRIx64, n_value);
5004     if (c.data != 0)
5005       outs() << " + " << format("0x%" PRIx64, c.data);
5006   } else
5007     outs() << format("0x%" PRIx64, c.data);
5008   outs() << " (struct class_ro_t *)";
5009 
5010   // This is a Swift class if some of the low bits of the pointer are set.
5011   if ((c.data + n_value) & 0x7)
5012     outs() << " Swift class";
5013   outs() << "\n";
5014   bool is_meta_class;
5015   if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5016     return;
5017 
5018   if (!is_meta_class &&
5019       c.isa + isa_n_value != p &&
5020       c.isa + isa_n_value != 0 &&
5021       info->depth < 100) {
5022       info->depth++;
5023       outs() << "Meta Class\n";
5024       print_class64_t(c.isa + isa_n_value, info);
5025   }
5026 }
5027 
5028 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5029   struct class32_t c;
5030   const char *r;
5031   uint32_t offset, left;
5032   SectionRef S;
5033   const char *name;
5034 
5035   r = get_pointer_32(p, offset, left, S, info);
5036   if (r == nullptr)
5037     return;
5038   memset(&c, '\0', sizeof(struct class32_t));
5039   if (left < sizeof(struct class32_t)) {
5040     memcpy(&c, r, left);
5041     outs() << "   (class_t entends past the end of the section)\n";
5042   } else
5043     memcpy(&c, r, sizeof(struct class32_t));
5044   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5045     swapStruct(c);
5046 
5047   outs() << "           isa " << format("0x%" PRIx32, c.isa);
5048   name =
5049       get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5050   if (name != nullptr)
5051     outs() << " " << name;
5052   outs() << "\n";
5053 
5054   outs() << "    superclass " << format("0x%" PRIx32, c.superclass);
5055   name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5056                        c.superclass);
5057   if (name != nullptr)
5058     outs() << " " << name;
5059   outs() << "\n";
5060 
5061   outs() << "         cache " << format("0x%" PRIx32, c.cache);
5062   name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5063                        c.cache);
5064   if (name != nullptr)
5065     outs() << " " << name;
5066   outs() << "\n";
5067 
5068   outs() << "        vtable " << format("0x%" PRIx32, c.vtable);
5069   name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5070                        c.vtable);
5071   if (name != nullptr)
5072     outs() << " " << name;
5073   outs() << "\n";
5074 
5075   name =
5076       get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5077   outs() << "          data " << format("0x%" PRIx32, c.data)
5078          << " (struct class_ro_t *)";
5079 
5080   // This is a Swift class if some of the low bits of the pointer are set.
5081   if (c.data & 0x3)
5082     outs() << " Swift class";
5083   outs() << "\n";
5084   bool is_meta_class;
5085   if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5086     return;
5087 
5088   if (!is_meta_class) {
5089     outs() << "Meta Class\n";
5090     print_class32_t(c.isa, info);
5091   }
5092 }
5093 
5094 static void print_objc_class_t(struct objc_class_t *objc_class,
5095                                struct DisassembleInfo *info) {
5096   uint32_t offset, left, xleft;
5097   const char *name, *p, *ivar_list;
5098   SectionRef S;
5099   int32_t i;
5100   struct objc_ivar_list_t objc_ivar_list;
5101   struct objc_ivar_t ivar;
5102 
5103   outs() << "\t\t      isa " << format("0x%08" PRIx32, objc_class->isa);
5104   if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5105     name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5106     if (name != nullptr)
5107       outs() << format(" %.*s", left, name);
5108     else
5109       outs() << " (not in an __OBJC section)";
5110   }
5111   outs() << "\n";
5112 
5113   outs() << "\t      super_class "
5114          << format("0x%08" PRIx32, objc_class->super_class);
5115   if (info->verbose) {
5116     name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5117     if (name != nullptr)
5118       outs() << format(" %.*s", left, name);
5119     else
5120       outs() << " (not in an __OBJC section)";
5121   }
5122   outs() << "\n";
5123 
5124   outs() << "\t\t     name " << format("0x%08" PRIx32, objc_class->name);
5125   if (info->verbose) {
5126     name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5127     if (name != nullptr)
5128       outs() << format(" %.*s", left, name);
5129     else
5130       outs() << " (not in an __OBJC section)";
5131   }
5132   outs() << "\n";
5133 
5134   outs() << "\t\t  version " << format("0x%08" PRIx32, objc_class->version)
5135          << "\n";
5136 
5137   outs() << "\t\t     info " << format("0x%08" PRIx32, objc_class->info);
5138   if (info->verbose) {
5139     if (CLS_GETINFO(objc_class, CLS_CLASS))
5140       outs() << " CLS_CLASS";
5141     else if (CLS_GETINFO(objc_class, CLS_META))
5142       outs() << " CLS_META";
5143   }
5144   outs() << "\n";
5145 
5146   outs() << "\t    instance_size "
5147          << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5148 
5149   p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5150   outs() << "\t\t    ivars " << format("0x%08" PRIx32, objc_class->ivars);
5151   if (p != nullptr) {
5152     if (left > sizeof(struct objc_ivar_list_t)) {
5153       outs() << "\n";
5154       memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5155     } else {
5156       outs() << " (entends past the end of the section)\n";
5157       memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5158       memcpy(&objc_ivar_list, p, left);
5159     }
5160     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5161       swapStruct(objc_ivar_list);
5162     outs() << "\t\t       ivar_count " << objc_ivar_list.ivar_count << "\n";
5163     ivar_list = p + sizeof(struct objc_ivar_list_t);
5164     for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5165       if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5166         outs() << "\t\t remaining ivar's extend past the of the section\n";
5167         break;
5168       }
5169       memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5170              sizeof(struct objc_ivar_t));
5171       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5172         swapStruct(ivar);
5173 
5174       outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5175       if (info->verbose) {
5176         name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5177         if (name != nullptr)
5178           outs() << format(" %.*s", xleft, name);
5179         else
5180           outs() << " (not in an __OBJC section)";
5181       }
5182       outs() << "\n";
5183 
5184       outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5185       if (info->verbose) {
5186         name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5187         if (name != nullptr)
5188           outs() << format(" %.*s", xleft, name);
5189         else
5190           outs() << " (not in an __OBJC section)";
5191       }
5192       outs() << "\n";
5193 
5194       outs() << "\t\t      ivar_offset "
5195              << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5196     }
5197   } else {
5198     outs() << " (not in an __OBJC section)\n";
5199   }
5200 
5201   outs() << "\t\t  methods " << format("0x%08" PRIx32, objc_class->methodLists);
5202   if (print_method_list(objc_class->methodLists, info))
5203     outs() << " (not in an __OBJC section)\n";
5204 
5205   outs() << "\t\t    cache " << format("0x%08" PRIx32, objc_class->cache)
5206          << "\n";
5207 
5208   outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5209   if (print_protocol_list(objc_class->protocols, 16, info))
5210     outs() << " (not in an __OBJC section)\n";
5211 }
5212 
5213 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5214                                        struct DisassembleInfo *info) {
5215   uint32_t offset, left;
5216   const char *name;
5217   SectionRef S;
5218 
5219   outs() << "\t       category name "
5220          << format("0x%08" PRIx32, objc_category->category_name);
5221   if (info->verbose) {
5222     name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5223                           true);
5224     if (name != nullptr)
5225       outs() << format(" %.*s", left, name);
5226     else
5227       outs() << " (not in an __OBJC section)";
5228   }
5229   outs() << "\n";
5230 
5231   outs() << "\t\t  class name "
5232          << format("0x%08" PRIx32, objc_category->class_name);
5233   if (info->verbose) {
5234     name =
5235         get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5236     if (name != nullptr)
5237       outs() << format(" %.*s", left, name);
5238     else
5239       outs() << " (not in an __OBJC section)";
5240   }
5241   outs() << "\n";
5242 
5243   outs() << "\t    instance methods "
5244          << format("0x%08" PRIx32, objc_category->instance_methods);
5245   if (print_method_list(objc_category->instance_methods, info))
5246     outs() << " (not in an __OBJC section)\n";
5247 
5248   outs() << "\t       class methods "
5249          << format("0x%08" PRIx32, objc_category->class_methods);
5250   if (print_method_list(objc_category->class_methods, info))
5251     outs() << " (not in an __OBJC section)\n";
5252 }
5253 
5254 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5255   struct category64_t c;
5256   const char *r;
5257   uint32_t offset, xoffset, left;
5258   SectionRef S, xS;
5259   const char *name, *sym_name;
5260   uint64_t n_value;
5261 
5262   r = get_pointer_64(p, offset, left, S, info);
5263   if (r == nullptr)
5264     return;
5265   memset(&c, '\0', sizeof(struct category64_t));
5266   if (left < sizeof(struct category64_t)) {
5267     memcpy(&c, r, left);
5268     outs() << "   (category_t entends past the end of the section)\n";
5269   } else
5270     memcpy(&c, r, sizeof(struct category64_t));
5271   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5272     swapStruct(c);
5273 
5274   outs() << "              name ";
5275   sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5276                            info, n_value, c.name);
5277   if (n_value != 0) {
5278     if (info->verbose && sym_name != nullptr)
5279       outs() << sym_name;
5280     else
5281       outs() << format("0x%" PRIx64, n_value);
5282     if (c.name != 0)
5283       outs() << " + " << format("0x%" PRIx64, c.name);
5284   } else
5285     outs() << format("0x%" PRIx64, c.name);
5286   name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5287   if (name != nullptr)
5288     outs() << format(" %.*s", left, name);
5289   outs() << "\n";
5290 
5291   outs() << "               cls ";
5292   sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5293                            n_value, c.cls);
5294   if (n_value != 0) {
5295     if (info->verbose && sym_name != nullptr)
5296       outs() << sym_name;
5297     else
5298       outs() << format("0x%" PRIx64, n_value);
5299     if (c.cls != 0)
5300       outs() << " + " << format("0x%" PRIx64, c.cls);
5301   } else
5302     outs() << format("0x%" PRIx64, c.cls);
5303   outs() << "\n";
5304   if (c.cls + n_value != 0)
5305     print_class64_t(c.cls + n_value, info);
5306 
5307   outs() << "   instanceMethods ";
5308   sym_name =
5309       get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5310                     info, n_value, c.instanceMethods);
5311   if (n_value != 0) {
5312     if (info->verbose && sym_name != nullptr)
5313       outs() << sym_name;
5314     else
5315       outs() << format("0x%" PRIx64, n_value);
5316     if (c.instanceMethods != 0)
5317       outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5318   } else
5319     outs() << format("0x%" PRIx64, c.instanceMethods);
5320   outs() << "\n";
5321   if (c.instanceMethods + n_value != 0)
5322     print_method_list64_t(c.instanceMethods + n_value, info, "");
5323 
5324   outs() << "      classMethods ";
5325   sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5326                            S, info, n_value, c.classMethods);
5327   if (n_value != 0) {
5328     if (info->verbose && sym_name != nullptr)
5329       outs() << sym_name;
5330     else
5331       outs() << format("0x%" PRIx64, n_value);
5332     if (c.classMethods != 0)
5333       outs() << " + " << format("0x%" PRIx64, c.classMethods);
5334   } else
5335     outs() << format("0x%" PRIx64, c.classMethods);
5336   outs() << "\n";
5337   if (c.classMethods + n_value != 0)
5338     print_method_list64_t(c.classMethods + n_value, info, "");
5339 
5340   outs() << "         protocols ";
5341   sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5342                            info, n_value, c.protocols);
5343   if (n_value != 0) {
5344     if (info->verbose && sym_name != nullptr)
5345       outs() << sym_name;
5346     else
5347       outs() << format("0x%" PRIx64, n_value);
5348     if (c.protocols != 0)
5349       outs() << " + " << format("0x%" PRIx64, c.protocols);
5350   } else
5351     outs() << format("0x%" PRIx64, c.protocols);
5352   outs() << "\n";
5353   if (c.protocols + n_value != 0)
5354     print_protocol_list64_t(c.protocols + n_value, info);
5355 
5356   outs() << "instanceProperties ";
5357   sym_name =
5358       get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5359                     S, info, n_value, c.instanceProperties);
5360   if (n_value != 0) {
5361     if (info->verbose && sym_name != nullptr)
5362       outs() << sym_name;
5363     else
5364       outs() << format("0x%" PRIx64, n_value);
5365     if (c.instanceProperties != 0)
5366       outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5367   } else
5368     outs() << format("0x%" PRIx64, c.instanceProperties);
5369   outs() << "\n";
5370   if (c.instanceProperties + n_value != 0)
5371     print_objc_property_list64(c.instanceProperties + n_value, info);
5372 }
5373 
5374 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5375   struct category32_t c;
5376   const char *r;
5377   uint32_t offset, left;
5378   SectionRef S, xS;
5379   const char *name;
5380 
5381   r = get_pointer_32(p, offset, left, S, info);
5382   if (r == nullptr)
5383     return;
5384   memset(&c, '\0', sizeof(struct category32_t));
5385   if (left < sizeof(struct category32_t)) {
5386     memcpy(&c, r, left);
5387     outs() << "   (category_t entends past the end of the section)\n";
5388   } else
5389     memcpy(&c, r, sizeof(struct category32_t));
5390   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5391     swapStruct(c);
5392 
5393   outs() << "              name " << format("0x%" PRIx32, c.name);
5394   name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5395                        c.name);
5396   if (name)
5397     outs() << " " << name;
5398   outs() << "\n";
5399 
5400   outs() << "               cls " << format("0x%" PRIx32, c.cls) << "\n";
5401   if (c.cls != 0)
5402     print_class32_t(c.cls, info);
5403   outs() << "   instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5404          << "\n";
5405   if (c.instanceMethods != 0)
5406     print_method_list32_t(c.instanceMethods, info, "");
5407   outs() << "      classMethods " << format("0x%" PRIx32, c.classMethods)
5408          << "\n";
5409   if (c.classMethods != 0)
5410     print_method_list32_t(c.classMethods, info, "");
5411   outs() << "         protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5412   if (c.protocols != 0)
5413     print_protocol_list32_t(c.protocols, info);
5414   outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5415          << "\n";
5416   if (c.instanceProperties != 0)
5417     print_objc_property_list32(c.instanceProperties, info);
5418 }
5419 
5420 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5421   uint32_t i, left, offset, xoffset;
5422   uint64_t p, n_value;
5423   struct message_ref64 mr;
5424   const char *name, *sym_name;
5425   const char *r;
5426   SectionRef xS;
5427 
5428   if (S == SectionRef())
5429     return;
5430 
5431   StringRef SectName;
5432   S.getName(SectName);
5433   DataRefImpl Ref = S.getRawDataRefImpl();
5434   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5435   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5436   offset = 0;
5437   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5438     p = S.getAddress() + i;
5439     r = get_pointer_64(p, offset, left, S, info);
5440     if (r == nullptr)
5441       return;
5442     memset(&mr, '\0', sizeof(struct message_ref64));
5443     if (left < sizeof(struct message_ref64)) {
5444       memcpy(&mr, r, left);
5445       outs() << "   (message_ref entends past the end of the section)\n";
5446     } else
5447       memcpy(&mr, r, sizeof(struct message_ref64));
5448     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5449       swapStruct(mr);
5450 
5451     outs() << "  imp ";
5452     name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5453                          n_value, mr.imp);
5454     if (n_value != 0) {
5455       outs() << format("0x%" PRIx64, n_value) << " ";
5456       if (mr.imp != 0)
5457         outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5458     } else
5459       outs() << format("0x%" PRIx64, mr.imp) << " ";
5460     if (name != nullptr)
5461       outs() << " " << name;
5462     outs() << "\n";
5463 
5464     outs() << "  sel ";
5465     sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5466                              info, n_value, mr.sel);
5467     if (n_value != 0) {
5468       if (info->verbose && sym_name != nullptr)
5469         outs() << sym_name;
5470       else
5471         outs() << format("0x%" PRIx64, n_value);
5472       if (mr.sel != 0)
5473         outs() << " + " << format("0x%" PRIx64, mr.sel);
5474     } else
5475       outs() << format("0x%" PRIx64, mr.sel);
5476     name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5477     if (name != nullptr)
5478       outs() << format(" %.*s", left, name);
5479     outs() << "\n";
5480 
5481     offset += sizeof(struct message_ref64);
5482   }
5483 }
5484 
5485 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5486   uint32_t i, left, offset, xoffset, p;
5487   struct message_ref32 mr;
5488   const char *name, *r;
5489   SectionRef xS;
5490 
5491   if (S == SectionRef())
5492     return;
5493 
5494   StringRef SectName;
5495   S.getName(SectName);
5496   DataRefImpl Ref = S.getRawDataRefImpl();
5497   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5498   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5499   offset = 0;
5500   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5501     p = S.getAddress() + i;
5502     r = get_pointer_32(p, offset, left, S, info);
5503     if (r == nullptr)
5504       return;
5505     memset(&mr, '\0', sizeof(struct message_ref32));
5506     if (left < sizeof(struct message_ref32)) {
5507       memcpy(&mr, r, left);
5508       outs() << "   (message_ref entends past the end of the section)\n";
5509     } else
5510       memcpy(&mr, r, sizeof(struct message_ref32));
5511     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5512       swapStruct(mr);
5513 
5514     outs() << "  imp " << format("0x%" PRIx32, mr.imp);
5515     name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5516                          mr.imp);
5517     if (name != nullptr)
5518       outs() << " " << name;
5519     outs() << "\n";
5520 
5521     outs() << "  sel " << format("0x%" PRIx32, mr.sel);
5522     name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5523     if (name != nullptr)
5524       outs() << " " << name;
5525     outs() << "\n";
5526 
5527     offset += sizeof(struct message_ref32);
5528   }
5529 }
5530 
5531 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5532   uint32_t left, offset, swift_version;
5533   uint64_t p;
5534   struct objc_image_info64 o;
5535   const char *r;
5536 
5537   if (S == SectionRef())
5538     return;
5539 
5540   StringRef SectName;
5541   S.getName(SectName);
5542   DataRefImpl Ref = S.getRawDataRefImpl();
5543   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5544   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5545   p = S.getAddress();
5546   r = get_pointer_64(p, offset, left, S, info);
5547   if (r == nullptr)
5548     return;
5549   memset(&o, '\0', sizeof(struct objc_image_info64));
5550   if (left < sizeof(struct objc_image_info64)) {
5551     memcpy(&o, r, left);
5552     outs() << "   (objc_image_info entends past the end of the section)\n";
5553   } else
5554     memcpy(&o, r, sizeof(struct objc_image_info64));
5555   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5556     swapStruct(o);
5557   outs() << "  version " << o.version << "\n";
5558   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5559   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5560     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5561   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5562     outs() << " OBJC_IMAGE_SUPPORTS_GC";
5563   swift_version = (o.flags >> 8) & 0xff;
5564   if (swift_version != 0) {
5565     if (swift_version == 1)
5566       outs() << " Swift 1.0";
5567     else if (swift_version == 2)
5568       outs() << " Swift 1.1";
5569     else if(swift_version == 3)
5570       outs() << " Swift 2.0";
5571     else if(swift_version == 4)
5572       outs() << " Swift 3.0";
5573     else if(swift_version == 5)
5574       outs() << " Swift 4.0";
5575     else if(swift_version == 6)
5576       outs() << " Swift 4.1";
5577     else
5578       outs() << " unknown future Swift version (" << swift_version << ")";
5579   }
5580   outs() << "\n";
5581 }
5582 
5583 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5584   uint32_t left, offset, swift_version, p;
5585   struct objc_image_info32 o;
5586   const char *r;
5587 
5588   if (S == SectionRef())
5589     return;
5590 
5591   StringRef SectName;
5592   S.getName(SectName);
5593   DataRefImpl Ref = S.getRawDataRefImpl();
5594   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5595   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5596   p = S.getAddress();
5597   r = get_pointer_32(p, offset, left, S, info);
5598   if (r == nullptr)
5599     return;
5600   memset(&o, '\0', sizeof(struct objc_image_info32));
5601   if (left < sizeof(struct objc_image_info32)) {
5602     memcpy(&o, r, left);
5603     outs() << "   (objc_image_info entends past the end of the section)\n";
5604   } else
5605     memcpy(&o, r, sizeof(struct objc_image_info32));
5606   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5607     swapStruct(o);
5608   outs() << "  version " << o.version << "\n";
5609   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5610   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5611     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5612   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5613     outs() << " OBJC_IMAGE_SUPPORTS_GC";
5614   swift_version = (o.flags >> 8) & 0xff;
5615   if (swift_version != 0) {
5616     if (swift_version == 1)
5617       outs() << " Swift 1.0";
5618     else if (swift_version == 2)
5619       outs() << " Swift 1.1";
5620     else if(swift_version == 3)
5621       outs() << " Swift 2.0";
5622     else if(swift_version == 4)
5623       outs() << " Swift 3.0";
5624     else if(swift_version == 5)
5625       outs() << " Swift 4.0";
5626     else if(swift_version == 6)
5627       outs() << " Swift 4.1";
5628     else
5629       outs() << " unknown future Swift version (" << swift_version << ")";
5630   }
5631   outs() << "\n";
5632 }
5633 
5634 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5635   uint32_t left, offset, p;
5636   struct imageInfo_t o;
5637   const char *r;
5638 
5639   StringRef SectName;
5640   S.getName(SectName);
5641   DataRefImpl Ref = S.getRawDataRefImpl();
5642   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5643   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5644   p = S.getAddress();
5645   r = get_pointer_32(p, offset, left, S, info);
5646   if (r == nullptr)
5647     return;
5648   memset(&o, '\0', sizeof(struct imageInfo_t));
5649   if (left < sizeof(struct imageInfo_t)) {
5650     memcpy(&o, r, left);
5651     outs() << " (imageInfo entends past the end of the section)\n";
5652   } else
5653     memcpy(&o, r, sizeof(struct imageInfo_t));
5654   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5655     swapStruct(o);
5656   outs() << "  version " << o.version << "\n";
5657   outs() << "    flags " << format("0x%" PRIx32, o.flags);
5658   if (o.flags & 0x1)
5659     outs() << "  F&C";
5660   if (o.flags & 0x2)
5661     outs() << " GC";
5662   if (o.flags & 0x4)
5663     outs() << " GC-only";
5664   else
5665     outs() << " RR";
5666   outs() << "\n";
5667 }
5668 
5669 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5670   SymbolAddressMap AddrMap;
5671   if (verbose)
5672     CreateSymbolAddressMap(O, &AddrMap);
5673 
5674   std::vector<SectionRef> Sections;
5675   for (const SectionRef &Section : O->sections()) {
5676     StringRef SectName;
5677     Section.getName(SectName);
5678     Sections.push_back(Section);
5679   }
5680 
5681   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
5682 
5683   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5684   if (CL == SectionRef())
5685     CL = get_section(O, "__DATA", "__objc_classlist");
5686   if (CL == SectionRef())
5687     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5688   if (CL == SectionRef())
5689     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5690   info.S = CL;
5691   walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5692 
5693   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5694   if (CR == SectionRef())
5695     CR = get_section(O, "__DATA", "__objc_classrefs");
5696   if (CR == SectionRef())
5697     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5698   if (CR == SectionRef())
5699     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5700   info.S = CR;
5701   walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5702 
5703   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5704   if (SR == SectionRef())
5705     SR = get_section(O, "__DATA", "__objc_superrefs");
5706   if (SR == SectionRef())
5707     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5708   if (SR == SectionRef())
5709     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5710   info.S = SR;
5711   walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5712 
5713   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5714   if (CA == SectionRef())
5715     CA = get_section(O, "__DATA", "__objc_catlist");
5716   if (CA == SectionRef())
5717     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5718   if (CA == SectionRef())
5719     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5720   info.S = CA;
5721   walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5722 
5723   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5724   if (PL == SectionRef())
5725     PL = get_section(O, "__DATA", "__objc_protolist");
5726   if (PL == SectionRef())
5727     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5728   if (PL == SectionRef())
5729     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5730   info.S = PL;
5731   walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5732 
5733   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5734   if (MR == SectionRef())
5735     MR = get_section(O, "__DATA", "__objc_msgrefs");
5736   if (MR == SectionRef())
5737     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5738   if (MR == SectionRef())
5739     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5740   info.S = MR;
5741   print_message_refs64(MR, &info);
5742 
5743   SectionRef II = get_section(O, "__OBJC2", "__image_info");
5744   if (II == SectionRef())
5745     II = get_section(O, "__DATA", "__objc_imageinfo");
5746   if (II == SectionRef())
5747     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5748   if (II == SectionRef())
5749     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5750   info.S = II;
5751   print_image_info64(II, &info);
5752 }
5753 
5754 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5755   SymbolAddressMap AddrMap;
5756   if (verbose)
5757     CreateSymbolAddressMap(O, &AddrMap);
5758 
5759   std::vector<SectionRef> Sections;
5760   for (const SectionRef &Section : O->sections()) {
5761     StringRef SectName;
5762     Section.getName(SectName);
5763     Sections.push_back(Section);
5764   }
5765 
5766   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
5767 
5768   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5769   if (CL == SectionRef())
5770     CL = get_section(O, "__DATA", "__objc_classlist");
5771   if (CL == SectionRef())
5772     CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5773   if (CL == SectionRef())
5774     CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5775   info.S = CL;
5776   walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5777 
5778   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5779   if (CR == SectionRef())
5780     CR = get_section(O, "__DATA", "__objc_classrefs");
5781   if (CR == SectionRef())
5782     CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5783   if (CR == SectionRef())
5784     CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5785   info.S = CR;
5786   walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5787 
5788   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5789   if (SR == SectionRef())
5790     SR = get_section(O, "__DATA", "__objc_superrefs");
5791   if (SR == SectionRef())
5792     SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5793   if (SR == SectionRef())
5794     SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5795   info.S = SR;
5796   walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5797 
5798   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5799   if (CA == SectionRef())
5800     CA = get_section(O, "__DATA", "__objc_catlist");
5801   if (CA == SectionRef())
5802     CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5803   if (CA == SectionRef())
5804     CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5805   info.S = CA;
5806   walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5807 
5808   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5809   if (PL == SectionRef())
5810     PL = get_section(O, "__DATA", "__objc_protolist");
5811   if (PL == SectionRef())
5812     PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5813   if (PL == SectionRef())
5814     PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5815   info.S = PL;
5816   walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5817 
5818   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5819   if (MR == SectionRef())
5820     MR = get_section(O, "__DATA", "__objc_msgrefs");
5821   if (MR == SectionRef())
5822     MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5823   if (MR == SectionRef())
5824     MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5825   info.S = MR;
5826   print_message_refs32(MR, &info);
5827 
5828   SectionRef II = get_section(O, "__OBJC2", "__image_info");
5829   if (II == SectionRef())
5830     II = get_section(O, "__DATA", "__objc_imageinfo");
5831   if (II == SectionRef())
5832     II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5833   if (II == SectionRef())
5834     II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5835   info.S = II;
5836   print_image_info32(II, &info);
5837 }
5838 
5839 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5840   uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5841   const char *r, *name, *defs;
5842   struct objc_module_t module;
5843   SectionRef S, xS;
5844   struct objc_symtab_t symtab;
5845   struct objc_class_t objc_class;
5846   struct objc_category_t objc_category;
5847 
5848   outs() << "Objective-C segment\n";
5849   S = get_section(O, "__OBJC", "__module_info");
5850   if (S == SectionRef())
5851     return false;
5852 
5853   SymbolAddressMap AddrMap;
5854   if (verbose)
5855     CreateSymbolAddressMap(O, &AddrMap);
5856 
5857   std::vector<SectionRef> Sections;
5858   for (const SectionRef &Section : O->sections()) {
5859     StringRef SectName;
5860     Section.getName(SectName);
5861     Sections.push_back(Section);
5862   }
5863 
5864   struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
5865 
5866   for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5867     p = S.getAddress() + i;
5868     r = get_pointer_32(p, offset, left, S, &info, true);
5869     if (r == nullptr)
5870       return true;
5871     memset(&module, '\0', sizeof(struct objc_module_t));
5872     if (left < sizeof(struct objc_module_t)) {
5873       memcpy(&module, r, left);
5874       outs() << "   (module extends past end of __module_info section)\n";
5875     } else
5876       memcpy(&module, r, sizeof(struct objc_module_t));
5877     if (O->isLittleEndian() != sys::IsLittleEndianHost)
5878       swapStruct(module);
5879 
5880     outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5881     outs() << "    version " << module.version << "\n";
5882     outs() << "       size " << module.size << "\n";
5883     outs() << "       name ";
5884     name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5885     if (name != nullptr)
5886       outs() << format("%.*s", left, name);
5887     else
5888       outs() << format("0x%08" PRIx32, module.name)
5889              << "(not in an __OBJC section)";
5890     outs() << "\n";
5891 
5892     r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5893     if (module.symtab == 0 || r == nullptr) {
5894       outs() << "     symtab " << format("0x%08" PRIx32, module.symtab)
5895              << " (not in an __OBJC section)\n";
5896       continue;
5897     }
5898     outs() << "     symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5899     memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5900     defs_left = 0;
5901     defs = nullptr;
5902     if (left < sizeof(struct objc_symtab_t)) {
5903       memcpy(&symtab, r, left);
5904       outs() << "\tsymtab extends past end of an __OBJC section)\n";
5905     } else {
5906       memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5907       if (left > sizeof(struct objc_symtab_t)) {
5908         defs_left = left - sizeof(struct objc_symtab_t);
5909         defs = r + sizeof(struct objc_symtab_t);
5910       }
5911     }
5912     if (O->isLittleEndian() != sys::IsLittleEndianHost)
5913       swapStruct(symtab);
5914 
5915     outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5916     r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5917     outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5918     if (r == nullptr)
5919       outs() << " (not in an __OBJC section)";
5920     outs() << "\n";
5921     outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5922     outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5923     if (symtab.cls_def_cnt > 0)
5924       outs() << "\tClass Definitions\n";
5925     for (j = 0; j < symtab.cls_def_cnt; j++) {
5926       if ((j + 1) * sizeof(uint32_t) > defs_left) {
5927         outs() << "\t(remaining class defs entries entends past the end of the "
5928                << "section)\n";
5929         break;
5930       }
5931       memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5932       if (O->isLittleEndian() != sys::IsLittleEndianHost)
5933         sys::swapByteOrder(def);
5934 
5935       r = get_pointer_32(def, xoffset, left, xS, &info, true);
5936       outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5937       if (r != nullptr) {
5938         if (left > sizeof(struct objc_class_t)) {
5939           outs() << "\n";
5940           memcpy(&objc_class, r, sizeof(struct objc_class_t));
5941         } else {
5942           outs() << " (entends past the end of the section)\n";
5943           memset(&objc_class, '\0', sizeof(struct objc_class_t));
5944           memcpy(&objc_class, r, left);
5945         }
5946         if (O->isLittleEndian() != sys::IsLittleEndianHost)
5947           swapStruct(objc_class);
5948         print_objc_class_t(&objc_class, &info);
5949       } else {
5950         outs() << "(not in an __OBJC section)\n";
5951       }
5952 
5953       if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5954         outs() << "\tMeta Class";
5955         r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5956         if (r != nullptr) {
5957           if (left > sizeof(struct objc_class_t)) {
5958             outs() << "\n";
5959             memcpy(&objc_class, r, sizeof(struct objc_class_t));
5960           } else {
5961             outs() << " (entends past the end of the section)\n";
5962             memset(&objc_class, '\0', sizeof(struct objc_class_t));
5963             memcpy(&objc_class, r, left);
5964           }
5965           if (O->isLittleEndian() != sys::IsLittleEndianHost)
5966             swapStruct(objc_class);
5967           print_objc_class_t(&objc_class, &info);
5968         } else {
5969           outs() << "(not in an __OBJC section)\n";
5970         }
5971       }
5972     }
5973     if (symtab.cat_def_cnt > 0)
5974       outs() << "\tCategory Definitions\n";
5975     for (j = 0; j < symtab.cat_def_cnt; j++) {
5976       if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5977         outs() << "\t(remaining category defs entries entends past the end of "
5978                << "the section)\n";
5979         break;
5980       }
5981       memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5982              sizeof(uint32_t));
5983       if (O->isLittleEndian() != sys::IsLittleEndianHost)
5984         sys::swapByteOrder(def);
5985 
5986       r = get_pointer_32(def, xoffset, left, xS, &info, true);
5987       outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5988              << format("0x%08" PRIx32, def);
5989       if (r != nullptr) {
5990         if (left > sizeof(struct objc_category_t)) {
5991           outs() << "\n";
5992           memcpy(&objc_category, r, sizeof(struct objc_category_t));
5993         } else {
5994           outs() << " (entends past the end of the section)\n";
5995           memset(&objc_category, '\0', sizeof(struct objc_category_t));
5996           memcpy(&objc_category, r, left);
5997         }
5998         if (O->isLittleEndian() != sys::IsLittleEndianHost)
5999           swapStruct(objc_category);
6000         print_objc_objc_category_t(&objc_category, &info);
6001       } else {
6002         outs() << "(not in an __OBJC section)\n";
6003       }
6004     }
6005   }
6006   const SectionRef II = get_section(O, "__OBJC", "__image_info");
6007   if (II != SectionRef())
6008     print_image_info(II, &info);
6009 
6010   return true;
6011 }
6012 
6013 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6014                                 uint32_t size, uint32_t addr) {
6015   SymbolAddressMap AddrMap;
6016   CreateSymbolAddressMap(O, &AddrMap);
6017 
6018   std::vector<SectionRef> Sections;
6019   for (const SectionRef &Section : O->sections()) {
6020     StringRef SectName;
6021     Section.getName(SectName);
6022     Sections.push_back(Section);
6023   }
6024 
6025   struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6026 
6027   const char *p;
6028   struct objc_protocol_t protocol;
6029   uint32_t left, paddr;
6030   for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6031     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6032     left = size - (p - sect);
6033     if (left < sizeof(struct objc_protocol_t)) {
6034       outs() << "Protocol extends past end of __protocol section\n";
6035       memcpy(&protocol, p, left);
6036     } else
6037       memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6038     if (O->isLittleEndian() != sys::IsLittleEndianHost)
6039       swapStruct(protocol);
6040     paddr = addr + (p - sect);
6041     outs() << "Protocol " << format("0x%" PRIx32, paddr);
6042     if (print_protocol(paddr, 0, &info))
6043       outs() << "(not in an __OBJC section)\n";
6044   }
6045 }
6046 
6047 #ifdef HAVE_LIBXAR
6048 inline void swapStruct(struct xar_header &xar) {
6049   sys::swapByteOrder(xar.magic);
6050   sys::swapByteOrder(xar.size);
6051   sys::swapByteOrder(xar.version);
6052   sys::swapByteOrder(xar.toc_length_compressed);
6053   sys::swapByteOrder(xar.toc_length_uncompressed);
6054   sys::swapByteOrder(xar.cksum_alg);
6055 }
6056 
6057 static void PrintModeVerbose(uint32_t mode) {
6058   switch(mode & S_IFMT){
6059   case S_IFDIR:
6060     outs() << "d";
6061     break;
6062   case S_IFCHR:
6063     outs() << "c";
6064     break;
6065   case S_IFBLK:
6066     outs() << "b";
6067     break;
6068   case S_IFREG:
6069     outs() << "-";
6070     break;
6071   case S_IFLNK:
6072     outs() << "l";
6073     break;
6074   case S_IFSOCK:
6075     outs() << "s";
6076     break;
6077   default:
6078     outs() << "?";
6079     break;
6080   }
6081 
6082   /* owner permissions */
6083   if(mode & S_IREAD)
6084     outs() << "r";
6085   else
6086     outs() << "-";
6087   if(mode & S_IWRITE)
6088     outs() << "w";
6089   else
6090     outs() << "-";
6091   if(mode & S_ISUID)
6092     outs() << "s";
6093   else if(mode & S_IEXEC)
6094     outs() << "x";
6095   else
6096     outs() << "-";
6097 
6098   /* group permissions */
6099   if(mode & (S_IREAD >> 3))
6100     outs() << "r";
6101   else
6102     outs() << "-";
6103   if(mode & (S_IWRITE >> 3))
6104     outs() << "w";
6105   else
6106     outs() << "-";
6107   if(mode & S_ISGID)
6108     outs() << "s";
6109   else if(mode & (S_IEXEC >> 3))
6110     outs() << "x";
6111   else
6112     outs() << "-";
6113 
6114   /* other permissions */
6115   if(mode & (S_IREAD >> 6))
6116     outs() << "r";
6117   else
6118     outs() << "-";
6119   if(mode & (S_IWRITE >> 6))
6120     outs() << "w";
6121   else
6122     outs() << "-";
6123   if(mode & S_ISVTX)
6124     outs() << "t";
6125   else if(mode & (S_IEXEC >> 6))
6126     outs() << "x";
6127   else
6128     outs() << "-";
6129 }
6130 
6131 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6132   xar_file_t xf;
6133   const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6134   char *endp;
6135   uint32_t mode_value;
6136 
6137   ScopedXarIter xi;
6138   if (!xi) {
6139     errs() << "Can't obtain an xar iterator for xar archive "
6140            << XarFilename << "\n";
6141     return;
6142   }
6143 
6144   // Go through the xar's files.
6145   for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6146     ScopedXarIter xp;
6147     if(!xp){
6148       errs() << "Can't obtain an xar iterator for xar archive "
6149              << XarFilename << "\n";
6150       return;
6151     }
6152     type = nullptr;
6153     mode = nullptr;
6154     user = nullptr;
6155     group = nullptr;
6156     size = nullptr;
6157     mtime = nullptr;
6158     name = nullptr;
6159     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6160       const char *val = nullptr;
6161       xar_prop_get(xf, key, &val);
6162 #if 0 // Useful for debugging.
6163       outs() << "key: " << key << " value: " << val << "\n";
6164 #endif
6165       if(strcmp(key, "type") == 0)
6166         type = val;
6167       if(strcmp(key, "mode") == 0)
6168         mode = val;
6169       if(strcmp(key, "user") == 0)
6170         user = val;
6171       if(strcmp(key, "group") == 0)
6172         group = val;
6173       if(strcmp(key, "data/size") == 0)
6174         size = val;
6175       if(strcmp(key, "mtime") == 0)
6176         mtime = val;
6177       if(strcmp(key, "name") == 0)
6178         name = val;
6179     }
6180     if(mode != nullptr){
6181       mode_value = strtoul(mode, &endp, 8);
6182       if(*endp != '\0')
6183         outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6184       if(strcmp(type, "file") == 0)
6185         mode_value |= S_IFREG;
6186       PrintModeVerbose(mode_value);
6187       outs() << " ";
6188     }
6189     if(user != nullptr)
6190       outs() << format("%10s/", user);
6191     if(group != nullptr)
6192       outs() << format("%-10s ", group);
6193     if(size != nullptr)
6194       outs() << format("%7s ", size);
6195     if(mtime != nullptr){
6196       for(m = mtime; *m != 'T' && *m != '\0'; m++)
6197         outs() << *m;
6198       if(*m == 'T')
6199         m++;
6200       outs() << " ";
6201       for( ; *m != 'Z' && *m != '\0'; m++)
6202         outs() << *m;
6203       outs() << " ";
6204     }
6205     if(name != nullptr)
6206       outs() << name;
6207     outs() << "\n";
6208   }
6209 }
6210 
6211 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6212                                 uint32_t size, bool verbose,
6213                                 bool PrintXarHeader, bool PrintXarFileHeaders,
6214                                 std::string XarMemberName) {
6215   if(size < sizeof(struct xar_header)) {
6216     outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6217               "of struct xar_header)\n";
6218     return;
6219   }
6220   struct xar_header XarHeader;
6221   memcpy(&XarHeader, sect, sizeof(struct xar_header));
6222   if (sys::IsLittleEndianHost)
6223     swapStruct(XarHeader);
6224   if (PrintXarHeader) {
6225     if (!XarMemberName.empty())
6226       outs() << "In xar member " << XarMemberName << ": ";
6227     else
6228       outs() << "For (__LLVM,__bundle) section: ";
6229     outs() << "xar header\n";
6230     if (XarHeader.magic == XAR_HEADER_MAGIC)
6231       outs() << "                  magic XAR_HEADER_MAGIC\n";
6232     else
6233       outs() << "                  magic "
6234              << format_hex(XarHeader.magic, 10, true)
6235              << " (not XAR_HEADER_MAGIC)\n";
6236     outs() << "                   size " << XarHeader.size << "\n";
6237     outs() << "                version " << XarHeader.version << "\n";
6238     outs() << "  toc_length_compressed " << XarHeader.toc_length_compressed
6239            << "\n";
6240     outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6241            << "\n";
6242     outs() << "              cksum_alg ";
6243     switch (XarHeader.cksum_alg) {
6244       case XAR_CKSUM_NONE:
6245         outs() << "XAR_CKSUM_NONE\n";
6246         break;
6247       case XAR_CKSUM_SHA1:
6248         outs() << "XAR_CKSUM_SHA1\n";
6249         break;
6250       case XAR_CKSUM_MD5:
6251         outs() << "XAR_CKSUM_MD5\n";
6252         break;
6253 #ifdef XAR_CKSUM_SHA256
6254       case XAR_CKSUM_SHA256:
6255         outs() << "XAR_CKSUM_SHA256\n";
6256         break;
6257 #endif
6258 #ifdef XAR_CKSUM_SHA512
6259       case XAR_CKSUM_SHA512:
6260         outs() << "XAR_CKSUM_SHA512\n";
6261         break;
6262 #endif
6263       default:
6264         outs() << XarHeader.cksum_alg << "\n";
6265     }
6266   }
6267 
6268   SmallString<128> XarFilename;
6269   int FD;
6270   std::error_code XarEC =
6271       sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6272   if (XarEC) {
6273     errs() << XarEC.message() << "\n";
6274     return;
6275   }
6276   ToolOutputFile XarFile(XarFilename, FD);
6277   raw_fd_ostream &XarOut = XarFile.os();
6278   StringRef XarContents(sect, size);
6279   XarOut << XarContents;
6280   XarOut.close();
6281   if (XarOut.has_error())
6282     return;
6283 
6284   ScopedXarFile xar(XarFilename.c_str(), READ);
6285   if (!xar) {
6286     errs() << "Can't create temporary xar archive " << XarFilename << "\n";
6287     return;
6288   }
6289 
6290   SmallString<128> TocFilename;
6291   std::error_code TocEC =
6292       sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6293   if (TocEC) {
6294     errs() << TocEC.message() << "\n";
6295     return;
6296   }
6297   xar_serialize(xar, TocFilename.c_str());
6298 
6299   if (PrintXarFileHeaders) {
6300     if (!XarMemberName.empty())
6301       outs() << "In xar member " << XarMemberName << ": ";
6302     else
6303       outs() << "For (__LLVM,__bundle) section: ";
6304     outs() << "xar archive files:\n";
6305     PrintXarFilesSummary(XarFilename.c_str(), xar);
6306   }
6307 
6308   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6309     MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6310   if (std::error_code EC = FileOrErr.getError()) {
6311     errs() << EC.message() << "\n";
6312     return;
6313   }
6314   std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6315 
6316   if (!XarMemberName.empty())
6317     outs() << "In xar member " << XarMemberName << ": ";
6318   else
6319     outs() << "For (__LLVM,__bundle) section: ";
6320   outs() << "xar table of contents:\n";
6321   outs() << Buffer->getBuffer() << "\n";
6322 
6323   // TODO: Go through the xar's files.
6324   ScopedXarIter xi;
6325   if(!xi){
6326     errs() << "Can't obtain an xar iterator for xar archive "
6327            << XarFilename.c_str() << "\n";
6328     return;
6329   }
6330   for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6331     const char *key;
6332     const char *member_name, *member_type, *member_size_string;
6333     size_t member_size;
6334 
6335     ScopedXarIter xp;
6336     if(!xp){
6337       errs() << "Can't obtain an xar iterator for xar archive "
6338              << XarFilename.c_str() << "\n";
6339       return;
6340     }
6341     member_name = NULL;
6342     member_type = NULL;
6343     member_size_string = NULL;
6344     for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6345       const char *val = nullptr;
6346       xar_prop_get(xf, key, &val);
6347 #if 0 // Useful for debugging.
6348       outs() << "key: " << key << " value: " << val << "\n";
6349 #endif
6350       if (strcmp(key, "name") == 0)
6351         member_name = val;
6352       if (strcmp(key, "type") == 0)
6353         member_type = val;
6354       if (strcmp(key, "data/size") == 0)
6355         member_size_string = val;
6356     }
6357     /*
6358      * If we find a file with a name, date/size and type properties
6359      * and with the type being "file" see if that is a xar file.
6360      */
6361     if (member_name != NULL && member_type != NULL &&
6362         strcmp(member_type, "file") == 0 &&
6363         member_size_string != NULL){
6364       // Extract the file into a buffer.
6365       char *endptr;
6366       member_size = strtoul(member_size_string, &endptr, 10);
6367       if (*endptr == '\0' && member_size != 0) {
6368         char *buffer;
6369         if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6370 #if 0 // Useful for debugging.
6371           outs() << "xar member: " << member_name << " extracted\n";
6372 #endif
6373           // Set the XarMemberName we want to see printed in the header.
6374           std::string OldXarMemberName;
6375           // If XarMemberName is already set this is nested. So
6376           // save the old name and create the nested name.
6377           if (!XarMemberName.empty()) {
6378             OldXarMemberName = XarMemberName;
6379             XarMemberName =
6380                 (Twine("[") + XarMemberName + "]" + member_name).str();
6381           } else {
6382             OldXarMemberName = "";
6383             XarMemberName = member_name;
6384           }
6385           // See if this is could be a xar file (nested).
6386           if (member_size >= sizeof(struct xar_header)) {
6387 #if 0 // Useful for debugging.
6388             outs() << "could be a xar file: " << member_name << "\n";
6389 #endif
6390             memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6391             if (sys::IsLittleEndianHost)
6392               swapStruct(XarHeader);
6393             if (XarHeader.magic == XAR_HEADER_MAGIC)
6394               DumpBitcodeSection(O, buffer, member_size, verbose,
6395                                  PrintXarHeader, PrintXarFileHeaders,
6396                                  XarMemberName);
6397           }
6398           XarMemberName = OldXarMemberName;
6399           delete buffer;
6400         }
6401       }
6402     }
6403   }
6404 }
6405 #endif // defined(HAVE_LIBXAR)
6406 
6407 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6408   if (O->is64Bit())
6409     printObjc2_64bit_MetaData(O, verbose);
6410   else {
6411     MachO::mach_header H;
6412     H = O->getHeader();
6413     if (H.cputype == MachO::CPU_TYPE_ARM)
6414       printObjc2_32bit_MetaData(O, verbose);
6415     else {
6416       // This is the 32-bit non-arm cputype case.  Which is normally
6417       // the first Objective-C ABI.  But it may be the case of a
6418       // binary for the iOS simulator which is the second Objective-C
6419       // ABI.  In that case printObjc1_32bit_MetaData() will determine that
6420       // and return false.
6421       if (!printObjc1_32bit_MetaData(O, verbose))
6422         printObjc2_32bit_MetaData(O, verbose);
6423     }
6424   }
6425 }
6426 
6427 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6428 // for the address passed in as ReferenceValue for printing as a comment with
6429 // the instruction and also returns the corresponding type of that item
6430 // indirectly through ReferenceType.
6431 //
6432 // If ReferenceValue is an address of literal cstring then a pointer to the
6433 // cstring is returned and ReferenceType is set to
6434 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6435 //
6436 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6437 // Class ref that name is returned and the ReferenceType is set accordingly.
6438 //
6439 // Lastly, literals which are Symbol address in a literal pool are looked for
6440 // and if found the symbol name is returned and ReferenceType is set to
6441 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6442 //
6443 // If there is no item in the Mach-O file for the address passed in as
6444 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6445 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6446                                        uint64_t ReferencePC,
6447                                        uint64_t *ReferenceType,
6448                                        struct DisassembleInfo *info) {
6449   // First see if there is an external relocation entry at the ReferencePC.
6450   if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6451     uint64_t sect_addr = info->S.getAddress();
6452     uint64_t sect_offset = ReferencePC - sect_addr;
6453     bool reloc_found = false;
6454     DataRefImpl Rel;
6455     MachO::any_relocation_info RE;
6456     bool isExtern = false;
6457     SymbolRef Symbol;
6458     for (const RelocationRef &Reloc : info->S.relocations()) {
6459       uint64_t RelocOffset = Reloc.getOffset();
6460       if (RelocOffset == sect_offset) {
6461         Rel = Reloc.getRawDataRefImpl();
6462         RE = info->O->getRelocation(Rel);
6463         if (info->O->isRelocationScattered(RE))
6464           continue;
6465         isExtern = info->O->getPlainRelocationExternal(RE);
6466         if (isExtern) {
6467           symbol_iterator RelocSym = Reloc.getSymbol();
6468           Symbol = *RelocSym;
6469         }
6470         reloc_found = true;
6471         break;
6472       }
6473     }
6474     // If there is an external relocation entry for a symbol in a section
6475     // then used that symbol's value for the value of the reference.
6476     if (reloc_found && isExtern) {
6477       if (info->O->getAnyRelocationPCRel(RE)) {
6478         unsigned Type = info->O->getAnyRelocationType(RE);
6479         if (Type == MachO::X86_64_RELOC_SIGNED) {
6480           ReferenceValue = Symbol.getValue();
6481         }
6482       }
6483     }
6484   }
6485 
6486   // Look for literals such as Objective-C CFStrings refs, Selector refs,
6487   // Message refs and Class refs.
6488   bool classref, selref, msgref, cfstring;
6489   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6490                                                selref, msgref, cfstring);
6491   if (classref && pointer_value == 0) {
6492     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6493     // And the pointer_value in that section is typically zero as it will be
6494     // set by dyld as part of the "bind information".
6495     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6496     if (name != nullptr) {
6497       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6498       const char *class_name = strrchr(name, '$');
6499       if (class_name != nullptr && class_name[1] == '_' &&
6500           class_name[2] != '\0') {
6501         info->class_name = class_name + 2;
6502         return name;
6503       }
6504     }
6505   }
6506 
6507   if (classref) {
6508     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6509     const char *name =
6510         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6511     if (name != nullptr)
6512       info->class_name = name;
6513     else
6514       name = "bad class ref";
6515     return name;
6516   }
6517 
6518   if (cfstring) {
6519     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6520     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6521     return name;
6522   }
6523 
6524   if (selref && pointer_value == 0)
6525     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6526 
6527   if (pointer_value != 0)
6528     ReferenceValue = pointer_value;
6529 
6530   const char *name = GuessCstringPointer(ReferenceValue, info);
6531   if (name) {
6532     if (pointer_value != 0 && selref) {
6533       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6534       info->selector_name = name;
6535     } else if (pointer_value != 0 && msgref) {
6536       info->class_name = nullptr;
6537       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6538       info->selector_name = name;
6539     } else
6540       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6541     return name;
6542   }
6543 
6544   // Lastly look for an indirect symbol with this ReferenceValue which is in
6545   // a literal pool.  If found return that symbol name.
6546   name = GuessIndirectSymbol(ReferenceValue, info);
6547   if (name) {
6548     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6549     return name;
6550   }
6551 
6552   return nullptr;
6553 }
6554 
6555 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6556 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
6557 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6558 // is created and returns the symbol name that matches the ReferenceValue or
6559 // nullptr if none.  The ReferenceType is passed in for the IN type of
6560 // reference the instruction is making from the values in defined in the header
6561 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
6562 // Out type and the ReferenceName will also be set which is added as a comment
6563 // to the disassembled instruction.
6564 //
6565 // If the symbol name is a C++ mangled name then the demangled name is
6566 // returned through ReferenceName and ReferenceType is set to
6567 // LLVMDisassembler_ReferenceType_DeMangled_Name .
6568 //
6569 // When this is called to get a symbol name for a branch target then the
6570 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6571 // SymbolValue will be looked for in the indirect symbol table to determine if
6572 // it is an address for a symbol stub.  If so then the symbol name for that
6573 // stub is returned indirectly through ReferenceName and then ReferenceType is
6574 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6575 //
6576 // When this is called with an value loaded via a PC relative load then
6577 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6578 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
6579 // or an Objective-C meta data reference.  If so the output ReferenceType is
6580 // set to correspond to that as well as setting the ReferenceName.
6581 static const char *SymbolizerSymbolLookUp(void *DisInfo,
6582                                           uint64_t ReferenceValue,
6583                                           uint64_t *ReferenceType,
6584                                           uint64_t ReferencePC,
6585                                           const char **ReferenceName) {
6586   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
6587   // If no verbose symbolic information is wanted then just return nullptr.
6588   if (!info->verbose) {
6589     *ReferenceName = nullptr;
6590     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6591     return nullptr;
6592   }
6593 
6594   const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
6595 
6596   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6597     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
6598     if (*ReferenceName != nullptr) {
6599       method_reference(info, ReferenceType, ReferenceName);
6600       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6601         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
6602     } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6603       if (info->demangled_name != nullptr)
6604         free(info->demangled_name);
6605       int status;
6606       info->demangled_name =
6607           itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
6608       if (info->demangled_name != nullptr) {
6609         *ReferenceName = info->demangled_name;
6610         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6611       } else
6612         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6613     } else
6614       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6615   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6616     *ReferenceName =
6617         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6618     if (*ReferenceName)
6619       method_reference(info, ReferenceType, ReferenceName);
6620     else
6621       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6622     // If this is arm64 and the reference is an adrp instruction save the
6623     // instruction, passed in ReferenceValue and the address of the instruction
6624     // for use later if we see and add immediate instruction.
6625   } else if (info->O->getArch() == Triple::aarch64 &&
6626              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6627     info->adrp_inst = ReferenceValue;
6628     info->adrp_addr = ReferencePC;
6629     SymbolName = nullptr;
6630     *ReferenceName = nullptr;
6631     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6632     // If this is arm64 and reference is an add immediate instruction and we
6633     // have
6634     // seen an adrp instruction just before it and the adrp's Xd register
6635     // matches
6636     // this add's Xn register reconstruct the value being referenced and look to
6637     // see if it is a literal pointer.  Note the add immediate instruction is
6638     // passed in ReferenceValue.
6639   } else if (info->O->getArch() == Triple::aarch64 &&
6640              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6641              ReferencePC - 4 == info->adrp_addr &&
6642              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6643              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6644     uint32_t addxri_inst;
6645     uint64_t adrp_imm, addxri_imm;
6646 
6647     adrp_imm =
6648         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6649     if (info->adrp_inst & 0x0200000)
6650       adrp_imm |= 0xfffffffffc000000LL;
6651 
6652     addxri_inst = ReferenceValue;
6653     addxri_imm = (addxri_inst >> 10) & 0xfff;
6654     if (((addxri_inst >> 22) & 0x3) == 1)
6655       addxri_imm <<= 12;
6656 
6657     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6658                      (adrp_imm << 12) + addxri_imm;
6659 
6660     *ReferenceName =
6661         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6662     if (*ReferenceName == nullptr)
6663       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6664     // If this is arm64 and the reference is a load register instruction and we
6665     // have seen an adrp instruction just before it and the adrp's Xd register
6666     // matches this add's Xn register reconstruct the value being referenced and
6667     // look to see if it is a literal pointer.  Note the load register
6668     // instruction is passed in ReferenceValue.
6669   } else if (info->O->getArch() == Triple::aarch64 &&
6670              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6671              ReferencePC - 4 == info->adrp_addr &&
6672              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6673              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6674     uint32_t ldrxui_inst;
6675     uint64_t adrp_imm, ldrxui_imm;
6676 
6677     adrp_imm =
6678         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6679     if (info->adrp_inst & 0x0200000)
6680       adrp_imm |= 0xfffffffffc000000LL;
6681 
6682     ldrxui_inst = ReferenceValue;
6683     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6684 
6685     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6686                      (adrp_imm << 12) + (ldrxui_imm << 3);
6687 
6688     *ReferenceName =
6689         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6690     if (*ReferenceName == nullptr)
6691       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6692   }
6693   // If this arm64 and is an load register (PC-relative) instruction the
6694   // ReferenceValue is the PC plus the immediate value.
6695   else if (info->O->getArch() == Triple::aarch64 &&
6696            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6697             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6698     *ReferenceName =
6699         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6700     if (*ReferenceName == nullptr)
6701       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6702   } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6703     if (info->demangled_name != nullptr)
6704       free(info->demangled_name);
6705     int status;
6706     info->demangled_name =
6707         itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
6708     if (info->demangled_name != nullptr) {
6709       *ReferenceName = info->demangled_name;
6710       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6711     }
6712   }
6713   else {
6714     *ReferenceName = nullptr;
6715     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6716   }
6717 
6718   return SymbolName;
6719 }
6720 
6721 /// \brief Emits the comments that are stored in the CommentStream.
6722 /// Each comment in the CommentStream must end with a newline.
6723 static void emitComments(raw_svector_ostream &CommentStream,
6724                          SmallString<128> &CommentsToEmit,
6725                          formatted_raw_ostream &FormattedOS,
6726                          const MCAsmInfo &MAI) {
6727   // Flush the stream before taking its content.
6728   StringRef Comments = CommentsToEmit.str();
6729   // Get the default information for printing a comment.
6730   StringRef CommentBegin = MAI.getCommentString();
6731   unsigned CommentColumn = MAI.getCommentColumn();
6732   bool IsFirst = true;
6733   while (!Comments.empty()) {
6734     if (!IsFirst)
6735       FormattedOS << '\n';
6736     // Emit a line of comments.
6737     FormattedOS.PadToColumn(CommentColumn);
6738     size_t Position = Comments.find('\n');
6739     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6740     // Move after the newline character.
6741     Comments = Comments.substr(Position + 1);
6742     IsFirst = false;
6743   }
6744   FormattedOS.flush();
6745 
6746   // Tell the comment stream that the vector changed underneath it.
6747   CommentsToEmit.clear();
6748 }
6749 
6750 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6751                              StringRef DisSegName, StringRef DisSectName) {
6752   const char *McpuDefault = nullptr;
6753   const Target *ThumbTarget = nullptr;
6754   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
6755   if (!TheTarget) {
6756     // GetTarget prints out stuff.
6757     return;
6758   }
6759   std::string MachOMCPU;
6760   if (MCPU.empty() && McpuDefault)
6761     MachOMCPU = McpuDefault;
6762   else
6763     MachOMCPU = MCPU;
6764 
6765   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
6766   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
6767   if (ThumbTarget)
6768     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
6769 
6770   // Package up features to be passed to target/subtarget
6771   std::string FeaturesStr;
6772   if (MAttrs.size()) {
6773     SubtargetFeatures Features;
6774     for (unsigned i = 0; i != MAttrs.size(); ++i)
6775       Features.AddFeature(MAttrs[i]);
6776     FeaturesStr = Features.getString();
6777   }
6778 
6779   // Set up disassembler.
6780   std::unique_ptr<const MCRegisterInfo> MRI(
6781       TheTarget->createMCRegInfo(TripleName));
6782   std::unique_ptr<const MCAsmInfo> AsmInfo(
6783       TheTarget->createMCAsmInfo(*MRI, TripleName));
6784   std::unique_ptr<const MCSubtargetInfo> STI(
6785       TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
6786   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
6787   std::unique_ptr<MCDisassembler> DisAsm(
6788       TheTarget->createMCDisassembler(*STI, Ctx));
6789   std::unique_ptr<MCSymbolizer> Symbolizer;
6790   struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
6791   std::unique_ptr<MCRelocationInfo> RelInfo(
6792       TheTarget->createMCRelocationInfo(TripleName, Ctx));
6793   if (RelInfo) {
6794     Symbolizer.reset(TheTarget->createMCSymbolizer(
6795         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
6796         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
6797     DisAsm->setSymbolizer(std::move(Symbolizer));
6798   }
6799   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
6800   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
6801       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
6802   // Set the display preference for hex vs. decimal immediates.
6803   IP->setPrintImmHex(PrintImmHex);
6804   // Comment stream and backing vector.
6805   SmallString<128> CommentsToEmit;
6806   raw_svector_ostream CommentStream(CommentsToEmit);
6807   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6808   // if it is done then arm64 comments for string literals don't get printed
6809   // and some constant get printed instead and not setting it causes intel
6810   // (32-bit and 64-bit) comments printed with different spacing before the
6811   // comment causing different diffs with the 'C' disassembler library API.
6812   // IP->setCommentStream(CommentStream);
6813 
6814   if (!AsmInfo || !STI || !DisAsm || !IP) {
6815     errs() << "error: couldn't initialize disassembler for target "
6816            << TripleName << '\n';
6817     return;
6818   }
6819 
6820   // Set up separate thumb disassembler if needed.
6821   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6822   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6823   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
6824   std::unique_ptr<MCDisassembler> ThumbDisAsm;
6825   std::unique_ptr<MCInstPrinter> ThumbIP;
6826   std::unique_ptr<MCContext> ThumbCtx;
6827   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6828   struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
6829   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
6830   if (ThumbTarget) {
6831     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6832     ThumbAsmInfo.reset(
6833         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6834     ThumbSTI.reset(
6835         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
6836                                            FeaturesStr));
6837     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6838     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
6839     MCContext *PtrThumbCtx = ThumbCtx.get();
6840     ThumbRelInfo.reset(
6841         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6842     if (ThumbRelInfo) {
6843       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6844           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
6845           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
6846       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6847     }
6848     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6849     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
6850         Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6851         *ThumbInstrInfo, *ThumbMRI));
6852     // Set the display preference for hex vs. decimal immediates.
6853     ThumbIP->setPrintImmHex(PrintImmHex);
6854   }
6855 
6856   if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
6857     errs() << "error: couldn't initialize disassembler for target "
6858            << ThumbTripleName << '\n';
6859     return;
6860   }
6861 
6862   MachO::mach_header Header = MachOOF->getHeader();
6863 
6864   // FIXME: Using the -cfg command line option, this code used to be able to
6865   // annotate relocations with the referenced symbol's name, and if this was
6866   // inside a __[cf]string section, the data it points to. This is now replaced
6867   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
6868   std::vector<SectionRef> Sections;
6869   std::vector<SymbolRef> Symbols;
6870   SmallVector<uint64_t, 8> FoundFns;
6871   uint64_t BaseSegmentAddress;
6872 
6873   getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6874                         BaseSegmentAddress);
6875 
6876   // Sort the symbols by address, just in case they didn't come in that way.
6877   std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6878 
6879   // Build a data in code table that is sorted on by the address of each entry.
6880   uint64_t BaseAddress = 0;
6881   if (Header.filetype == MachO::MH_OBJECT)
6882     BaseAddress = Sections[0].getAddress();
6883   else
6884     BaseAddress = BaseSegmentAddress;
6885   DiceTable Dices;
6886   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6887        DI != DE; ++DI) {
6888     uint32_t Offset;
6889     DI->getOffset(Offset);
6890     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6891   }
6892   array_pod_sort(Dices.begin(), Dices.end());
6893 
6894 #ifndef NDEBUG
6895   raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6896 #else
6897   raw_ostream &DebugOut = nulls();
6898 #endif
6899 
6900   std::unique_ptr<DIContext> diContext;
6901   ObjectFile *DbgObj = MachOOF;
6902   // Try to find debug info and set up the DIContext for it.
6903   if (UseDbg) {
6904     // A separate DSym file path was specified, parse it as a macho file,
6905     // get the sections and supply it to the section name parsing machinery.
6906     if (!DSYMFile.empty()) {
6907       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6908           MemoryBuffer::getFileOrSTDIN(DSYMFile);
6909       if (std::error_code EC = BufOrErr.getError()) {
6910         errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6911         return;
6912       }
6913       DbgObj =
6914           ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6915               .get()
6916               .release();
6917     }
6918 
6919     // Setup the DIContext
6920     diContext = DWARFContext::create(*DbgObj);
6921   }
6922 
6923   if (FilterSections.size() == 0)
6924     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6925 
6926   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6927     StringRef SectName;
6928     if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6929       continue;
6930 
6931     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6932 
6933     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6934     if (SegmentName != DisSegName)
6935       continue;
6936 
6937     StringRef BytesStr;
6938     Sections[SectIdx].getContents(BytesStr);
6939     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6940                             BytesStr.size());
6941     uint64_t SectAddress = Sections[SectIdx].getAddress();
6942 
6943     bool symbolTableWorked = false;
6944 
6945     // Create a map of symbol addresses to symbol names for use by
6946     // the SymbolizerSymbolLookUp() routine.
6947     SymbolAddressMap AddrMap;
6948     bool DisSymNameFound = false;
6949     for (const SymbolRef &Symbol : MachOOF->symbols()) {
6950       Expected<SymbolRef::Type> STOrErr = Symbol.getType();
6951       if (!STOrErr)
6952         report_error(MachOOF->getFileName(), STOrErr.takeError());
6953       SymbolRef::Type ST = *STOrErr;
6954       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6955           ST == SymbolRef::ST_Other) {
6956         uint64_t Address = Symbol.getValue();
6957         Expected<StringRef> SymNameOrErr = Symbol.getName();
6958         if (!SymNameOrErr)
6959           report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
6960         StringRef SymName = *SymNameOrErr;
6961         AddrMap[Address] = SymName;
6962         if (!DisSymName.empty() && DisSymName == SymName)
6963           DisSymNameFound = true;
6964       }
6965     }
6966     if (!DisSymName.empty() && !DisSymNameFound) {
6967       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6968       return;
6969     }
6970     // Set up the block of info used by the Symbolizer call backs.
6971     SymbolizerInfo.verbose = !NoSymbolicOperands;
6972     SymbolizerInfo.O = MachOOF;
6973     SymbolizerInfo.S = Sections[SectIdx];
6974     SymbolizerInfo.AddrMap = &AddrMap;
6975     SymbolizerInfo.Sections = &Sections;
6976     // Same for the ThumbSymbolizer
6977     ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6978     ThumbSymbolizerInfo.O = MachOOF;
6979     ThumbSymbolizerInfo.S = Sections[SectIdx];
6980     ThumbSymbolizerInfo.AddrMap = &AddrMap;
6981     ThumbSymbolizerInfo.Sections = &Sections;
6982 
6983     unsigned int Arch = MachOOF->getArch();
6984 
6985     // Skip all symbols if this is a stubs file.
6986     if (Bytes.size() == 0)
6987       return;
6988 
6989     // If the section has symbols but no symbol at the start of the section
6990     // these are used to make sure the bytes before the first symbol are
6991     // disassembled.
6992     bool FirstSymbol = true;
6993     bool FirstSymbolAtSectionStart = true;
6994 
6995     // Disassemble symbol by symbol.
6996     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6997       Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6998       if (!SymNameOrErr)
6999         report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
7000       StringRef SymName = *SymNameOrErr;
7001 
7002       Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
7003       if (!STOrErr)
7004         report_error(MachOOF->getFileName(), STOrErr.takeError());
7005       SymbolRef::Type ST = *STOrErr;
7006       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7007         continue;
7008 
7009       // Make sure the symbol is defined in this section.
7010       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7011       if (!containsSym) {
7012         if (!DisSymName.empty() && DisSymName == SymName) {
7013           outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7014           return;
7015         }
7016         continue;
7017       }
7018       // The __mh_execute_header is special and we need to deal with that fact
7019       // this symbol is before the start of the (__TEXT,__text) section and at the
7020       // address of the start of the __TEXT segment.  This is because this symbol
7021       // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7022       // start of the section in a standard MH_EXECUTE filetype.
7023       if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7024         outs() << "-dis-symname: __mh_execute_header not in any section\n";
7025         return;
7026       }
7027       // When this code is trying to disassemble a symbol at a time and in the
7028       // case there is only the __mh_execute_header symbol left as in a stripped
7029       // executable, we need to deal with this by ignoring this symbol so the
7030       // whole section is disassembled and this symbol is then not displayed.
7031       if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7032           SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7033           SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7034         continue;
7035 
7036       // If we are only disassembling one symbol see if this is that symbol.
7037       if (!DisSymName.empty() && DisSymName != SymName)
7038         continue;
7039 
7040       // Start at the address of the symbol relative to the section's address.
7041       uint64_t SectSize = Sections[SectIdx].getSize();
7042       uint64_t Start = Symbols[SymIdx].getValue();
7043       uint64_t SectionAddress = Sections[SectIdx].getAddress();
7044       Start -= SectionAddress;
7045 
7046       if (Start > SectSize) {
7047         outs() << "section data ends, " << SymName
7048                << " lies outside valid range\n";
7049         return;
7050       }
7051 
7052       // Stop disassembling either at the beginning of the next symbol or at
7053       // the end of the section.
7054       bool containsNextSym = false;
7055       uint64_t NextSym = 0;
7056       uint64_t NextSymIdx = SymIdx + 1;
7057       while (Symbols.size() > NextSymIdx) {
7058         Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
7059         if (!STOrErr)
7060           report_error(MachOOF->getFileName(), STOrErr.takeError());
7061         SymbolRef::Type NextSymType = *STOrErr;
7062         if (NextSymType == SymbolRef::ST_Function) {
7063           containsNextSym =
7064               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7065           NextSym = Symbols[NextSymIdx].getValue();
7066           NextSym -= SectionAddress;
7067           break;
7068         }
7069         ++NextSymIdx;
7070       }
7071 
7072       uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7073       uint64_t Size;
7074 
7075       symbolTableWorked = true;
7076 
7077       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7078       bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7079 
7080       // We only need the dedicated Thumb target if there's a real choice
7081       // (i.e. we're not targeting M-class) and the function is Thumb.
7082       bool UseThumbTarget = IsThumb && ThumbTarget;
7083 
7084       // If we are not specifying a symbol to start disassembly with and this
7085       // is the first symbol in the section but not at the start of the section
7086       // then move the disassembly index to the start of the section and
7087       // don't print the symbol name just yet.  This is so the bytes before the
7088       // first symbol are disassembled.
7089       uint64_t SymbolStart = Start;
7090       if (DisSymName.empty() && FirstSymbol && Start != 0) {
7091         FirstSymbolAtSectionStart = false;
7092         Start = 0;
7093       }
7094       else
7095         outs() << SymName << ":\n";
7096 
7097       DILineInfo lastLine;
7098       for (uint64_t Index = Start; Index < End; Index += Size) {
7099         MCInst Inst;
7100 
7101         // If this is the first symbol in the section and it was not at the
7102         // start of the section, see if we are at its Index now and if so print
7103         // the symbol name.
7104         if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7105           outs() << SymName << ":\n";
7106 
7107         uint64_t PC = SectAddress + Index;
7108         if (!NoLeadingAddr) {
7109           if (FullLeadingAddr) {
7110             if (MachOOF->is64Bit())
7111               outs() << format("%016" PRIx64, PC);
7112             else
7113               outs() << format("%08" PRIx64, PC);
7114           } else {
7115             outs() << format("%8" PRIx64 ":", PC);
7116           }
7117         }
7118         if (!NoShowRawInsn || Arch == Triple::arm)
7119           outs() << "\t";
7120 
7121         // Check the data in code table here to see if this is data not an
7122         // instruction to be disassembled.
7123         DiceTable Dice;
7124         Dice.push_back(std::make_pair(PC, DiceRef()));
7125         dice_table_iterator DTI =
7126             std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7127                         compareDiceTableEntries);
7128         if (DTI != Dices.end()) {
7129           uint16_t Length;
7130           DTI->second.getLength(Length);
7131           uint16_t Kind;
7132           DTI->second.getKind(Kind);
7133           Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
7134           if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7135               (PC == (DTI->first + Length - 1)) && (Length & 1))
7136             Size++;
7137           continue;
7138         }
7139 
7140         SmallVector<char, 64> AnnotationsBytes;
7141         raw_svector_ostream Annotations(AnnotationsBytes);
7142 
7143         bool gotInst;
7144         if (UseThumbTarget)
7145           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7146                                                 PC, DebugOut, Annotations);
7147         else
7148           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7149                                            DebugOut, Annotations);
7150         if (gotInst) {
7151           if (!NoShowRawInsn || Arch == Triple::arm) {
7152             dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7153           }
7154           formatted_raw_ostream FormattedOS(outs());
7155           StringRef AnnotationsStr = Annotations.str();
7156           if (UseThumbTarget)
7157             ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
7158           else
7159             IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
7160           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7161 
7162           // Print debug info.
7163           if (diContext) {
7164             DILineInfo dli = diContext->getLineInfoForAddress(PC);
7165             // Print valid line info if it changed.
7166             if (dli != lastLine && dli.Line != 0)
7167               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7168                      << dli.Column;
7169             lastLine = dli;
7170           }
7171           outs() << "\n";
7172         } else {
7173           unsigned int Arch = MachOOF->getArch();
7174           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7175             outs() << format("\t.byte 0x%02x #bad opcode\n",
7176                              *(Bytes.data() + Index) & 0xff);
7177             Size = 1; // skip exactly one illegible byte and move on.
7178           } else if (Arch == Triple::aarch64 ||
7179                      (Arch == Triple::arm && !IsThumb)) {
7180             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7181                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7182                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7183                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
7184             outs() << format("\t.long\t0x%08x\n", opcode);
7185             Size = 4;
7186           } else if (Arch == Triple::arm) {
7187             assert(IsThumb && "ARM mode should have been dealt with above");
7188             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7189                               (*(Bytes.data() + Index + 1) & 0xff) << 8;
7190             outs() << format("\t.short\t0x%04x\n", opcode);
7191             Size = 2;
7192           } else{
7193             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7194             if (Size == 0)
7195               Size = 1; // skip illegible bytes
7196           }
7197         }
7198       }
7199       // Now that we are done disassembled the first symbol set the bool that
7200       // were doing this to false.
7201       FirstSymbol = false;
7202     }
7203     if (!symbolTableWorked) {
7204       // Reading the symbol table didn't work, disassemble the whole section.
7205       uint64_t SectAddress = Sections[SectIdx].getAddress();
7206       uint64_t SectSize = Sections[SectIdx].getSize();
7207       uint64_t InstSize;
7208       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7209         MCInst Inst;
7210 
7211         uint64_t PC = SectAddress + Index;
7212         SmallVector<char, 64> AnnotationsBytes;
7213         raw_svector_ostream Annotations(AnnotationsBytes);
7214         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7215                                    DebugOut, Annotations)) {
7216           if (!NoLeadingAddr) {
7217             if (FullLeadingAddr) {
7218               if (MachOOF->is64Bit())
7219                 outs() << format("%016" PRIx64, PC);
7220               else
7221                 outs() << format("%08" PRIx64, PC);
7222             } else {
7223               outs() << format("%8" PRIx64 ":", PC);
7224             }
7225           }
7226           if (!NoShowRawInsn || Arch == Triple::arm) {
7227             outs() << "\t";
7228             dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7229           }
7230           StringRef AnnotationsStr = Annotations.str();
7231           IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
7232           outs() << "\n";
7233         } else {
7234           unsigned int Arch = MachOOF->getArch();
7235           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7236             outs() << format("\t.byte 0x%02x #bad opcode\n",
7237                              *(Bytes.data() + Index) & 0xff);
7238             InstSize = 1; // skip exactly one illegible byte and move on.
7239           } else {
7240             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7241             if (InstSize == 0)
7242               InstSize = 1; // skip illegible bytes
7243           }
7244         }
7245       }
7246     }
7247     // The TripleName's need to be reset if we are called again for a different
7248     // archtecture.
7249     TripleName = "";
7250     ThumbTripleName = "";
7251 
7252     if (SymbolizerInfo.method != nullptr)
7253       delete[] SymbolizerInfo.method;
7254     if (SymbolizerInfo.demangled_name != nullptr)
7255       free(SymbolizerInfo.demangled_name);
7256     if (ThumbSymbolizerInfo.method != nullptr)
7257       delete[] ThumbSymbolizerInfo.method;
7258     if (ThumbSymbolizerInfo.demangled_name != nullptr)
7259       free(ThumbSymbolizerInfo.demangled_name);
7260   }
7261 }
7262 
7263 //===----------------------------------------------------------------------===//
7264 // __compact_unwind section dumping
7265 //===----------------------------------------------------------------------===//
7266 
7267 namespace {
7268 
7269 template <typename T>
7270 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7271   using llvm::support::little;
7272   using llvm::support::unaligned;
7273 
7274   if (Offset + sizeof(T) > Contents.size()) {
7275     outs() << "warning: attempt to read past end of buffer\n";
7276     return T();
7277   }
7278 
7279   uint64_t Val =
7280       support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7281   return Val;
7282 }
7283 
7284 template <typename T>
7285 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7286   T Val = read<T>(Contents, Offset);
7287   Offset += sizeof(T);
7288   return Val;
7289 }
7290 
7291 struct CompactUnwindEntry {
7292   uint32_t OffsetInSection;
7293 
7294   uint64_t FunctionAddr;
7295   uint32_t Length;
7296   uint32_t CompactEncoding;
7297   uint64_t PersonalityAddr;
7298   uint64_t LSDAAddr;
7299 
7300   RelocationRef FunctionReloc;
7301   RelocationRef PersonalityReloc;
7302   RelocationRef LSDAReloc;
7303 
7304   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7305       : OffsetInSection(Offset) {
7306     if (Is64)
7307       read<uint64_t>(Contents, Offset);
7308     else
7309       read<uint32_t>(Contents, Offset);
7310   }
7311 
7312 private:
7313   template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7314     FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7315     Length = readNext<uint32_t>(Contents, Offset);
7316     CompactEncoding = readNext<uint32_t>(Contents, Offset);
7317     PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7318     LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7319   }
7320 };
7321 }
7322 
7323 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7324 /// and data being relocated, determine the best base Name and Addend to use for
7325 /// display purposes.
7326 ///
7327 /// 1. An Extern relocation will directly reference a symbol (and the data is
7328 ///    then already an addend), so use that.
7329 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7330 //     a symbol before it in the same section, and use the offset from there.
7331 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7332 ///    referenced section.
7333 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7334                                       std::map<uint64_t, SymbolRef> &Symbols,
7335                                       const RelocationRef &Reloc, uint64_t Addr,
7336                                       StringRef &Name, uint64_t &Addend) {
7337   if (Reloc.getSymbol() != Obj->symbol_end()) {
7338     Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
7339     if (!NameOrErr)
7340       report_error(Obj->getFileName(), NameOrErr.takeError());
7341     Name = *NameOrErr;
7342     Addend = Addr;
7343     return;
7344   }
7345 
7346   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7347   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7348 
7349   uint64_t SectionAddr = RelocSection.getAddress();
7350 
7351   auto Sym = Symbols.upper_bound(Addr);
7352   if (Sym == Symbols.begin()) {
7353     // The first symbol in the object is after this reference, the best we can
7354     // do is section-relative notation.
7355     RelocSection.getName(Name);
7356     Addend = Addr - SectionAddr;
7357     return;
7358   }
7359 
7360   // Go back one so that SymbolAddress <= Addr.
7361   --Sym;
7362 
7363   auto SectOrErr = Sym->second.getSection();
7364   if (!SectOrErr)
7365     report_error(Obj->getFileName(), SectOrErr.takeError());
7366   section_iterator SymSection = *SectOrErr;
7367   if (RelocSection == *SymSection) {
7368     // There's a valid symbol in the same section before this reference.
7369     Expected<StringRef> NameOrErr = Sym->second.getName();
7370     if (!NameOrErr)
7371       report_error(Obj->getFileName(), NameOrErr.takeError());
7372     Name = *NameOrErr;
7373     Addend = Addr - Sym->first;
7374     return;
7375   }
7376 
7377   // There is a symbol before this reference, but it's in a different
7378   // section. Probably not helpful to mention it, so use the section name.
7379   RelocSection.getName(Name);
7380   Addend = Addr - SectionAddr;
7381 }
7382 
7383 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7384                                  std::map<uint64_t, SymbolRef> &Symbols,
7385                                  const RelocationRef &Reloc, uint64_t Addr) {
7386   StringRef Name;
7387   uint64_t Addend;
7388 
7389   if (!Reloc.getObject())
7390     return;
7391 
7392   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7393 
7394   outs() << Name;
7395   if (Addend)
7396     outs() << " + " << format("0x%" PRIx64, Addend);
7397 }
7398 
7399 static void
7400 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7401                                std::map<uint64_t, SymbolRef> &Symbols,
7402                                const SectionRef &CompactUnwind) {
7403 
7404   if (!Obj->isLittleEndian()) {
7405     outs() << "Skipping big-endian __compact_unwind section\n";
7406     return;
7407   }
7408 
7409   bool Is64 = Obj->is64Bit();
7410   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7411   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7412 
7413   StringRef Contents;
7414   CompactUnwind.getContents(Contents);
7415 
7416   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7417 
7418   // First populate the initial raw offsets, encodings and so on from the entry.
7419   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7420     CompactUnwindEntry Entry(Contents, Offset, Is64);
7421     CompactUnwinds.push_back(Entry);
7422   }
7423 
7424   // Next we need to look at the relocations to find out what objects are
7425   // actually being referred to.
7426   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7427     uint64_t RelocAddress = Reloc.getOffset();
7428 
7429     uint32_t EntryIdx = RelocAddress / EntrySize;
7430     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7431     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7432 
7433     if (OffsetInEntry == 0)
7434       Entry.FunctionReloc = Reloc;
7435     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7436       Entry.PersonalityReloc = Reloc;
7437     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7438       Entry.LSDAReloc = Reloc;
7439     else {
7440       outs() << "Invalid relocation in __compact_unwind section\n";
7441       return;
7442     }
7443   }
7444 
7445   // Finally, we're ready to print the data we've gathered.
7446   outs() << "Contents of __compact_unwind section:\n";
7447   for (auto &Entry : CompactUnwinds) {
7448     outs() << "  Entry at offset "
7449            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7450 
7451     // 1. Start of the region this entry applies to.
7452     outs() << "    start:                " << format("0x%" PRIx64,
7453                                                      Entry.FunctionAddr) << ' ';
7454     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7455     outs() << '\n';
7456 
7457     // 2. Length of the region this entry applies to.
7458     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
7459            << '\n';
7460     // 3. The 32-bit compact encoding.
7461     outs() << "    compact encoding:     "
7462            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7463 
7464     // 4. The personality function, if present.
7465     if (Entry.PersonalityReloc.getObject()) {
7466       outs() << "    personality function: "
7467              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7468       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7469                            Entry.PersonalityAddr);
7470       outs() << '\n';
7471     }
7472 
7473     // 5. This entry's language-specific data area.
7474     if (Entry.LSDAReloc.getObject()) {
7475       outs() << "    LSDA:                 " << format("0x%" PRIx64,
7476                                                        Entry.LSDAAddr) << ' ';
7477       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7478       outs() << '\n';
7479     }
7480   }
7481 }
7482 
7483 //===----------------------------------------------------------------------===//
7484 // __unwind_info section dumping
7485 //===----------------------------------------------------------------------===//
7486 
7487 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7488   ptrdiff_t Pos = 0;
7489   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7490   (void)Kind;
7491   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7492 
7493   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7494   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7495 
7496   Pos = EntriesStart;
7497   for (unsigned i = 0; i < NumEntries; ++i) {
7498     uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7499     uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
7500 
7501     outs() << "      [" << i << "]: "
7502            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7503            << ", "
7504            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7505   }
7506 }
7507 
7508 static void printCompressedSecondLevelUnwindPage(
7509     StringRef PageData, uint32_t FunctionBase,
7510     const SmallVectorImpl<uint32_t> &CommonEncodings) {
7511   ptrdiff_t Pos = 0;
7512   uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7513   (void)Kind;
7514   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7515 
7516   uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7517   uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7518 
7519   uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7520   readNext<uint16_t>(PageData, Pos);
7521   StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
7522 
7523   Pos = EntriesStart;
7524   for (unsigned i = 0; i < NumEntries; ++i) {
7525     uint32_t Entry = readNext<uint32_t>(PageData, Pos);
7526     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7527     uint32_t EncodingIdx = Entry >> 24;
7528 
7529     uint32_t Encoding;
7530     if (EncodingIdx < CommonEncodings.size())
7531       Encoding = CommonEncodings[EncodingIdx];
7532     else
7533       Encoding = read<uint32_t>(PageEncodings,
7534                                 sizeof(uint32_t) *
7535                                     (EncodingIdx - CommonEncodings.size()));
7536 
7537     outs() << "      [" << i << "]: "
7538            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7539            << ", "
7540            << "encoding[" << EncodingIdx
7541            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
7542   }
7543 }
7544 
7545 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7546                                         std::map<uint64_t, SymbolRef> &Symbols,
7547                                         const SectionRef &UnwindInfo) {
7548 
7549   if (!Obj->isLittleEndian()) {
7550     outs() << "Skipping big-endian __unwind_info section\n";
7551     return;
7552   }
7553 
7554   outs() << "Contents of __unwind_info section:\n";
7555 
7556   StringRef Contents;
7557   UnwindInfo.getContents(Contents);
7558   ptrdiff_t Pos = 0;
7559 
7560   //===----------------------------------
7561   // Section header
7562   //===----------------------------------
7563 
7564   uint32_t Version = readNext<uint32_t>(Contents, Pos);
7565   outs() << "  Version:                                   "
7566          << format("0x%" PRIx32, Version) << '\n';
7567   if (Version != 1) {
7568     outs() << "    Skipping section with unknown version\n";
7569     return;
7570   }
7571 
7572   uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
7573   outs() << "  Common encodings array section offset:     "
7574          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7575   uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
7576   outs() << "  Number of common encodings in array:       "
7577          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7578 
7579   uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
7580   outs() << "  Personality function array section offset: "
7581          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7582   uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
7583   outs() << "  Number of personality functions in array:  "
7584          << format("0x%" PRIx32, NumPersonalities) << '\n';
7585 
7586   uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
7587   outs() << "  Index array section offset:                "
7588          << format("0x%" PRIx32, IndicesStart) << '\n';
7589   uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
7590   outs() << "  Number of indices in array:                "
7591          << format("0x%" PRIx32, NumIndices) << '\n';
7592 
7593   //===----------------------------------
7594   // A shared list of common encodings
7595   //===----------------------------------
7596 
7597   // These occupy indices in the range [0, N] whenever an encoding is referenced
7598   // from a compressed 2nd level index table. In practice the linker only
7599   // creates ~128 of these, so that indices are available to embed encodings in
7600   // the 2nd level index.
7601 
7602   SmallVector<uint32_t, 64> CommonEncodings;
7603   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
7604   Pos = CommonEncodingsStart;
7605   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7606     uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
7607     CommonEncodings.push_back(Encoding);
7608 
7609     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7610            << '\n';
7611   }
7612 
7613   //===----------------------------------
7614   // Personality functions used in this executable
7615   //===----------------------------------
7616 
7617   // There should be only a handful of these (one per source language,
7618   // roughly). Particularly since they only get 2 bits in the compact encoding.
7619 
7620   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
7621   Pos = PersonalitiesStart;
7622   for (unsigned i = 0; i < NumPersonalities; ++i) {
7623     uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
7624     outs() << "    personality[" << i + 1
7625            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7626   }
7627 
7628   //===----------------------------------
7629   // The level 1 index entries
7630   //===----------------------------------
7631 
7632   // These specify an approximate place to start searching for the more detailed
7633   // information, sorted by PC.
7634 
7635   struct IndexEntry {
7636     uint32_t FunctionOffset;
7637     uint32_t SecondLevelPageStart;
7638     uint32_t LSDAStart;
7639   };
7640 
7641   SmallVector<IndexEntry, 4> IndexEntries;
7642 
7643   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
7644   Pos = IndicesStart;
7645   for (unsigned i = 0; i < NumIndices; ++i) {
7646     IndexEntry Entry;
7647 
7648     Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7649     Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7650     Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
7651     IndexEntries.push_back(Entry);
7652 
7653     outs() << "    [" << i << "]: "
7654            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7655            << ", "
7656            << "2nd level page offset="
7657            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
7658            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
7659   }
7660 
7661   //===----------------------------------
7662   // Next come the LSDA tables
7663   //===----------------------------------
7664 
7665   // The LSDA layout is rather implicit: it's a contiguous array of entries from
7666   // the first top-level index's LSDAOffset to the last (sentinel).
7667 
7668   outs() << "  LSDA descriptors:\n";
7669   Pos = IndexEntries[0].LSDAStart;
7670   const uint32_t LSDASize = 2 * sizeof(uint32_t);
7671   int NumLSDAs =
7672       (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7673 
7674   for (int i = 0; i < NumLSDAs; ++i) {
7675     uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7676     uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
7677     outs() << "    [" << i << "]: "
7678            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7679            << ", "
7680            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
7681   }
7682 
7683   //===----------------------------------
7684   // Finally, the 2nd level indices
7685   //===----------------------------------
7686 
7687   // Generally these are 4K in size, and have 2 possible forms:
7688   //   + Regular stores up to 511 entries with disparate encodings
7689   //   + Compressed stores up to 1021 entries if few enough compact encoding
7690   //     values are used.
7691   outs() << "  Second level indices:\n";
7692   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7693     // The final sentinel top-level index has no associated 2nd level page
7694     if (IndexEntries[i].SecondLevelPageStart == 0)
7695       break;
7696 
7697     outs() << "    Second level index[" << i << "]: "
7698            << "offset in section="
7699            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7700            << ", "
7701            << "base function offset="
7702            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7703 
7704     Pos = IndexEntries[i].SecondLevelPageStart;
7705     if (Pos + sizeof(uint32_t) > Contents.size()) {
7706       outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7707       continue;
7708     }
7709 
7710     uint32_t Kind =
7711         *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
7712     if (Kind == 2)
7713       printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
7714     else if (Kind == 3)
7715       printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7716                                            IndexEntries[i].FunctionOffset,
7717                                            CommonEncodings);
7718     else
7719       outs() << "    Skipping 2nd level page with unknown kind " << Kind
7720              << '\n';
7721   }
7722 }
7723 
7724 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7725   std::map<uint64_t, SymbolRef> Symbols;
7726   for (const SymbolRef &SymRef : Obj->symbols()) {
7727     // Discard any undefined or absolute symbols. They're not going to take part
7728     // in the convenience lookup for unwind info and just take up resources.
7729     auto SectOrErr = SymRef.getSection();
7730     if (!SectOrErr) {
7731       // TODO: Actually report errors helpfully.
7732       consumeError(SectOrErr.takeError());
7733       continue;
7734     }
7735     section_iterator Section = *SectOrErr;
7736     if (Section == Obj->section_end())
7737       continue;
7738 
7739     uint64_t Addr = SymRef.getValue();
7740     Symbols.insert(std::make_pair(Addr, SymRef));
7741   }
7742 
7743   for (const SectionRef &Section : Obj->sections()) {
7744     StringRef SectName;
7745     Section.getName(SectName);
7746     if (SectName == "__compact_unwind")
7747       printMachOCompactUnwindSection(Obj, Symbols, Section);
7748     else if (SectName == "__unwind_info")
7749       printMachOUnwindInfoSection(Obj, Symbols, Section);
7750   }
7751 }
7752 
7753 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7754                             uint32_t cpusubtype, uint32_t filetype,
7755                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7756                             bool verbose) {
7757   outs() << "Mach header\n";
7758   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
7759             "sizeofcmds      flags\n";
7760   if (verbose) {
7761     if (magic == MachO::MH_MAGIC)
7762       outs() << "   MH_MAGIC";
7763     else if (magic == MachO::MH_MAGIC_64)
7764       outs() << "MH_MAGIC_64";
7765     else
7766       outs() << format(" 0x%08" PRIx32, magic);
7767     switch (cputype) {
7768     case MachO::CPU_TYPE_I386:
7769       outs() << "    I386";
7770       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7771       case MachO::CPU_SUBTYPE_I386_ALL:
7772         outs() << "        ALL";
7773         break;
7774       default:
7775         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7776         break;
7777       }
7778       break;
7779     case MachO::CPU_TYPE_X86_64:
7780       outs() << "  X86_64";
7781       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7782       case MachO::CPU_SUBTYPE_X86_64_ALL:
7783         outs() << "        ALL";
7784         break;
7785       case MachO::CPU_SUBTYPE_X86_64_H:
7786         outs() << "    Haswell";
7787         break;
7788       default:
7789         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7790         break;
7791       }
7792       break;
7793     case MachO::CPU_TYPE_ARM:
7794       outs() << "     ARM";
7795       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7796       case MachO::CPU_SUBTYPE_ARM_ALL:
7797         outs() << "        ALL";
7798         break;
7799       case MachO::CPU_SUBTYPE_ARM_V4T:
7800         outs() << "        V4T";
7801         break;
7802       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7803         outs() << "      V5TEJ";
7804         break;
7805       case MachO::CPU_SUBTYPE_ARM_XSCALE:
7806         outs() << "     XSCALE";
7807         break;
7808       case MachO::CPU_SUBTYPE_ARM_V6:
7809         outs() << "         V6";
7810         break;
7811       case MachO::CPU_SUBTYPE_ARM_V6M:
7812         outs() << "        V6M";
7813         break;
7814       case MachO::CPU_SUBTYPE_ARM_V7:
7815         outs() << "         V7";
7816         break;
7817       case MachO::CPU_SUBTYPE_ARM_V7EM:
7818         outs() << "       V7EM";
7819         break;
7820       case MachO::CPU_SUBTYPE_ARM_V7K:
7821         outs() << "        V7K";
7822         break;
7823       case MachO::CPU_SUBTYPE_ARM_V7M:
7824         outs() << "        V7M";
7825         break;
7826       case MachO::CPU_SUBTYPE_ARM_V7S:
7827         outs() << "        V7S";
7828         break;
7829       default:
7830         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7831         break;
7832       }
7833       break;
7834     case MachO::CPU_TYPE_ARM64:
7835       outs() << "   ARM64";
7836       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7837       case MachO::CPU_SUBTYPE_ARM64_ALL:
7838         outs() << "        ALL";
7839         break;
7840       default:
7841         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7842         break;
7843       }
7844       break;
7845     case MachO::CPU_TYPE_POWERPC:
7846       outs() << "     PPC";
7847       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7848       case MachO::CPU_SUBTYPE_POWERPC_ALL:
7849         outs() << "        ALL";
7850         break;
7851       default:
7852         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7853         break;
7854       }
7855       break;
7856     case MachO::CPU_TYPE_POWERPC64:
7857       outs() << "   PPC64";
7858       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7859       case MachO::CPU_SUBTYPE_POWERPC_ALL:
7860         outs() << "        ALL";
7861         break;
7862       default:
7863         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7864         break;
7865       }
7866       break;
7867     default:
7868       outs() << format(" %7d", cputype);
7869       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7870       break;
7871     }
7872     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
7873       outs() << " LIB64";
7874     } else {
7875       outs() << format("  0x%02" PRIx32,
7876                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7877     }
7878     switch (filetype) {
7879     case MachO::MH_OBJECT:
7880       outs() << "      OBJECT";
7881       break;
7882     case MachO::MH_EXECUTE:
7883       outs() << "     EXECUTE";
7884       break;
7885     case MachO::MH_FVMLIB:
7886       outs() << "      FVMLIB";
7887       break;
7888     case MachO::MH_CORE:
7889       outs() << "        CORE";
7890       break;
7891     case MachO::MH_PRELOAD:
7892       outs() << "     PRELOAD";
7893       break;
7894     case MachO::MH_DYLIB:
7895       outs() << "       DYLIB";
7896       break;
7897     case MachO::MH_DYLIB_STUB:
7898       outs() << "  DYLIB_STUB";
7899       break;
7900     case MachO::MH_DYLINKER:
7901       outs() << "    DYLINKER";
7902       break;
7903     case MachO::MH_BUNDLE:
7904       outs() << "      BUNDLE";
7905       break;
7906     case MachO::MH_DSYM:
7907       outs() << "        DSYM";
7908       break;
7909     case MachO::MH_KEXT_BUNDLE:
7910       outs() << "  KEXTBUNDLE";
7911       break;
7912     default:
7913       outs() << format("  %10u", filetype);
7914       break;
7915     }
7916     outs() << format(" %5u", ncmds);
7917     outs() << format(" %10u", sizeofcmds);
7918     uint32_t f = flags;
7919     if (f & MachO::MH_NOUNDEFS) {
7920       outs() << "   NOUNDEFS";
7921       f &= ~MachO::MH_NOUNDEFS;
7922     }
7923     if (f & MachO::MH_INCRLINK) {
7924       outs() << " INCRLINK";
7925       f &= ~MachO::MH_INCRLINK;
7926     }
7927     if (f & MachO::MH_DYLDLINK) {
7928       outs() << " DYLDLINK";
7929       f &= ~MachO::MH_DYLDLINK;
7930     }
7931     if (f & MachO::MH_BINDATLOAD) {
7932       outs() << " BINDATLOAD";
7933       f &= ~MachO::MH_BINDATLOAD;
7934     }
7935     if (f & MachO::MH_PREBOUND) {
7936       outs() << " PREBOUND";
7937       f &= ~MachO::MH_PREBOUND;
7938     }
7939     if (f & MachO::MH_SPLIT_SEGS) {
7940       outs() << " SPLIT_SEGS";
7941       f &= ~MachO::MH_SPLIT_SEGS;
7942     }
7943     if (f & MachO::MH_LAZY_INIT) {
7944       outs() << " LAZY_INIT";
7945       f &= ~MachO::MH_LAZY_INIT;
7946     }
7947     if (f & MachO::MH_TWOLEVEL) {
7948       outs() << " TWOLEVEL";
7949       f &= ~MachO::MH_TWOLEVEL;
7950     }
7951     if (f & MachO::MH_FORCE_FLAT) {
7952       outs() << " FORCE_FLAT";
7953       f &= ~MachO::MH_FORCE_FLAT;
7954     }
7955     if (f & MachO::MH_NOMULTIDEFS) {
7956       outs() << " NOMULTIDEFS";
7957       f &= ~MachO::MH_NOMULTIDEFS;
7958     }
7959     if (f & MachO::MH_NOFIXPREBINDING) {
7960       outs() << " NOFIXPREBINDING";
7961       f &= ~MachO::MH_NOFIXPREBINDING;
7962     }
7963     if (f & MachO::MH_PREBINDABLE) {
7964       outs() << " PREBINDABLE";
7965       f &= ~MachO::MH_PREBINDABLE;
7966     }
7967     if (f & MachO::MH_ALLMODSBOUND) {
7968       outs() << " ALLMODSBOUND";
7969       f &= ~MachO::MH_ALLMODSBOUND;
7970     }
7971     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7972       outs() << " SUBSECTIONS_VIA_SYMBOLS";
7973       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7974     }
7975     if (f & MachO::MH_CANONICAL) {
7976       outs() << " CANONICAL";
7977       f &= ~MachO::MH_CANONICAL;
7978     }
7979     if (f & MachO::MH_WEAK_DEFINES) {
7980       outs() << " WEAK_DEFINES";
7981       f &= ~MachO::MH_WEAK_DEFINES;
7982     }
7983     if (f & MachO::MH_BINDS_TO_WEAK) {
7984       outs() << " BINDS_TO_WEAK";
7985       f &= ~MachO::MH_BINDS_TO_WEAK;
7986     }
7987     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7988       outs() << " ALLOW_STACK_EXECUTION";
7989       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7990     }
7991     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7992       outs() << " DEAD_STRIPPABLE_DYLIB";
7993       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7994     }
7995     if (f & MachO::MH_PIE) {
7996       outs() << " PIE";
7997       f &= ~MachO::MH_PIE;
7998     }
7999     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8000       outs() << " NO_REEXPORTED_DYLIBS";
8001       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8002     }
8003     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8004       outs() << " MH_HAS_TLV_DESCRIPTORS";
8005       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8006     }
8007     if (f & MachO::MH_NO_HEAP_EXECUTION) {
8008       outs() << " MH_NO_HEAP_EXECUTION";
8009       f &= ~MachO::MH_NO_HEAP_EXECUTION;
8010     }
8011     if (f & MachO::MH_APP_EXTENSION_SAFE) {
8012       outs() << " APP_EXTENSION_SAFE";
8013       f &= ~MachO::MH_APP_EXTENSION_SAFE;
8014     }
8015     if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8016       outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8017       f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8018     }
8019     if (f != 0 || flags == 0)
8020       outs() << format(" 0x%08" PRIx32, f);
8021   } else {
8022     outs() << format(" 0x%08" PRIx32, magic);
8023     outs() << format(" %7d", cputype);
8024     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8025     outs() << format("  0x%02" PRIx32,
8026                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8027     outs() << format("  %10u", filetype);
8028     outs() << format(" %5u", ncmds);
8029     outs() << format(" %10u", sizeofcmds);
8030     outs() << format(" 0x%08" PRIx32, flags);
8031   }
8032   outs() << "\n";
8033 }
8034 
8035 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8036                                 StringRef SegName, uint64_t vmaddr,
8037                                 uint64_t vmsize, uint64_t fileoff,
8038                                 uint64_t filesize, uint32_t maxprot,
8039                                 uint32_t initprot, uint32_t nsects,
8040                                 uint32_t flags, uint32_t object_size,
8041                                 bool verbose) {
8042   uint64_t expected_cmdsize;
8043   if (cmd == MachO::LC_SEGMENT) {
8044     outs() << "      cmd LC_SEGMENT\n";
8045     expected_cmdsize = nsects;
8046     expected_cmdsize *= sizeof(struct MachO::section);
8047     expected_cmdsize += sizeof(struct MachO::segment_command);
8048   } else {
8049     outs() << "      cmd LC_SEGMENT_64\n";
8050     expected_cmdsize = nsects;
8051     expected_cmdsize *= sizeof(struct MachO::section_64);
8052     expected_cmdsize += sizeof(struct MachO::segment_command_64);
8053   }
8054   outs() << "  cmdsize " << cmdsize;
8055   if (cmdsize != expected_cmdsize)
8056     outs() << " Inconsistent size\n";
8057   else
8058     outs() << "\n";
8059   outs() << "  segname " << SegName << "\n";
8060   if (cmd == MachO::LC_SEGMENT_64) {
8061     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8062     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8063   } else {
8064     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8065     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8066   }
8067   outs() << "  fileoff " << fileoff;
8068   if (fileoff > object_size)
8069     outs() << " (past end of file)\n";
8070   else
8071     outs() << "\n";
8072   outs() << " filesize " << filesize;
8073   if (fileoff + filesize > object_size)
8074     outs() << " (past end of file)\n";
8075   else
8076     outs() << "\n";
8077   if (verbose) {
8078     if ((maxprot &
8079          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8080            MachO::VM_PROT_EXECUTE)) != 0)
8081       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8082     else {
8083       outs() << "  maxprot ";
8084       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8085       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8086       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8087     }
8088     if ((initprot &
8089          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8090            MachO::VM_PROT_EXECUTE)) != 0)
8091       outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8092     else {
8093       outs() << " initprot ";
8094       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8095       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8096       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8097     }
8098   } else {
8099     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8100     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8101   }
8102   outs() << "   nsects " << nsects << "\n";
8103   if (verbose) {
8104     outs() << "    flags";
8105     if (flags == 0)
8106       outs() << " (none)\n";
8107     else {
8108       if (flags & MachO::SG_HIGHVM) {
8109         outs() << " HIGHVM";
8110         flags &= ~MachO::SG_HIGHVM;
8111       }
8112       if (flags & MachO::SG_FVMLIB) {
8113         outs() << " FVMLIB";
8114         flags &= ~MachO::SG_FVMLIB;
8115       }
8116       if (flags & MachO::SG_NORELOC) {
8117         outs() << " NORELOC";
8118         flags &= ~MachO::SG_NORELOC;
8119       }
8120       if (flags & MachO::SG_PROTECTED_VERSION_1) {
8121         outs() << " PROTECTED_VERSION_1";
8122         flags &= ~MachO::SG_PROTECTED_VERSION_1;
8123       }
8124       if (flags)
8125         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8126       else
8127         outs() << "\n";
8128     }
8129   } else {
8130     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
8131   }
8132 }
8133 
8134 static void PrintSection(const char *sectname, const char *segname,
8135                          uint64_t addr, uint64_t size, uint32_t offset,
8136                          uint32_t align, uint32_t reloff, uint32_t nreloc,
8137                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8138                          uint32_t cmd, const char *sg_segname,
8139                          uint32_t filetype, uint32_t object_size,
8140                          bool verbose) {
8141   outs() << "Section\n";
8142   outs() << "  sectname " << format("%.16s\n", sectname);
8143   outs() << "   segname " << format("%.16s", segname);
8144   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8145     outs() << " (does not match segment)\n";
8146   else
8147     outs() << "\n";
8148   if (cmd == MachO::LC_SEGMENT_64) {
8149     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
8150     outs() << "      size " << format("0x%016" PRIx64, size);
8151   } else {
8152     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
8153     outs() << "      size " << format("0x%08" PRIx64, size);
8154   }
8155   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8156     outs() << " (past end of file)\n";
8157   else
8158     outs() << "\n";
8159   outs() << "    offset " << offset;
8160   if (offset > object_size)
8161     outs() << " (past end of file)\n";
8162   else
8163     outs() << "\n";
8164   uint32_t align_shifted = 1 << align;
8165   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
8166   outs() << "    reloff " << reloff;
8167   if (reloff > object_size)
8168     outs() << " (past end of file)\n";
8169   else
8170     outs() << "\n";
8171   outs() << "    nreloc " << nreloc;
8172   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8173     outs() << " (past end of file)\n";
8174   else
8175     outs() << "\n";
8176   uint32_t section_type = flags & MachO::SECTION_TYPE;
8177   if (verbose) {
8178     outs() << "      type";
8179     if (section_type == MachO::S_REGULAR)
8180       outs() << " S_REGULAR\n";
8181     else if (section_type == MachO::S_ZEROFILL)
8182       outs() << " S_ZEROFILL\n";
8183     else if (section_type == MachO::S_CSTRING_LITERALS)
8184       outs() << " S_CSTRING_LITERALS\n";
8185     else if (section_type == MachO::S_4BYTE_LITERALS)
8186       outs() << " S_4BYTE_LITERALS\n";
8187     else if (section_type == MachO::S_8BYTE_LITERALS)
8188       outs() << " S_8BYTE_LITERALS\n";
8189     else if (section_type == MachO::S_16BYTE_LITERALS)
8190       outs() << " S_16BYTE_LITERALS\n";
8191     else if (section_type == MachO::S_LITERAL_POINTERS)
8192       outs() << " S_LITERAL_POINTERS\n";
8193     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8194       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8195     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8196       outs() << " S_LAZY_SYMBOL_POINTERS\n";
8197     else if (section_type == MachO::S_SYMBOL_STUBS)
8198       outs() << " S_SYMBOL_STUBS\n";
8199     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8200       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8201     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8202       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8203     else if (section_type == MachO::S_COALESCED)
8204       outs() << " S_COALESCED\n";
8205     else if (section_type == MachO::S_INTERPOSING)
8206       outs() << " S_INTERPOSING\n";
8207     else if (section_type == MachO::S_DTRACE_DOF)
8208       outs() << " S_DTRACE_DOF\n";
8209     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8210       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8211     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8212       outs() << " S_THREAD_LOCAL_REGULAR\n";
8213     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8214       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8215     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8216       outs() << " S_THREAD_LOCAL_VARIABLES\n";
8217     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8218       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8219     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8220       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8221     else
8222       outs() << format("0x%08" PRIx32, section_type) << "\n";
8223     outs() << "attributes";
8224     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8225     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8226       outs() << " PURE_INSTRUCTIONS";
8227     if (section_attributes & MachO::S_ATTR_NO_TOC)
8228       outs() << " NO_TOC";
8229     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8230       outs() << " STRIP_STATIC_SYMS";
8231     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8232       outs() << " NO_DEAD_STRIP";
8233     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8234       outs() << " LIVE_SUPPORT";
8235     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8236       outs() << " SELF_MODIFYING_CODE";
8237     if (section_attributes & MachO::S_ATTR_DEBUG)
8238       outs() << " DEBUG";
8239     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8240       outs() << " SOME_INSTRUCTIONS";
8241     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8242       outs() << " EXT_RELOC";
8243     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8244       outs() << " LOC_RELOC";
8245     if (section_attributes == 0)
8246       outs() << " (none)";
8247     outs() << "\n";
8248   } else
8249     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
8250   outs() << " reserved1 " << reserved1;
8251   if (section_type == MachO::S_SYMBOL_STUBS ||
8252       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8253       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8254       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8255       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8256     outs() << " (index into indirect symbol table)\n";
8257   else
8258     outs() << "\n";
8259   outs() << " reserved2 " << reserved2;
8260   if (section_type == MachO::S_SYMBOL_STUBS)
8261     outs() << " (size of stubs)\n";
8262   else
8263     outs() << "\n";
8264 }
8265 
8266 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8267                                    uint32_t object_size) {
8268   outs() << "     cmd LC_SYMTAB\n";
8269   outs() << " cmdsize " << st.cmdsize;
8270   if (st.cmdsize != sizeof(struct MachO::symtab_command))
8271     outs() << " Incorrect size\n";
8272   else
8273     outs() << "\n";
8274   outs() << "  symoff " << st.symoff;
8275   if (st.symoff > object_size)
8276     outs() << " (past end of file)\n";
8277   else
8278     outs() << "\n";
8279   outs() << "   nsyms " << st.nsyms;
8280   uint64_t big_size;
8281   if (Is64Bit) {
8282     big_size = st.nsyms;
8283     big_size *= sizeof(struct MachO::nlist_64);
8284     big_size += st.symoff;
8285     if (big_size > object_size)
8286       outs() << " (past end of file)\n";
8287     else
8288       outs() << "\n";
8289   } else {
8290     big_size = st.nsyms;
8291     big_size *= sizeof(struct MachO::nlist);
8292     big_size += st.symoff;
8293     if (big_size > object_size)
8294       outs() << " (past end of file)\n";
8295     else
8296       outs() << "\n";
8297   }
8298   outs() << "  stroff " << st.stroff;
8299   if (st.stroff > object_size)
8300     outs() << " (past end of file)\n";
8301   else
8302     outs() << "\n";
8303   outs() << " strsize " << st.strsize;
8304   big_size = st.stroff;
8305   big_size += st.strsize;
8306   if (big_size > object_size)
8307     outs() << " (past end of file)\n";
8308   else
8309     outs() << "\n";
8310 }
8311 
8312 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8313                                      uint32_t nsyms, uint32_t object_size,
8314                                      bool Is64Bit) {
8315   outs() << "            cmd LC_DYSYMTAB\n";
8316   outs() << "        cmdsize " << dyst.cmdsize;
8317   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8318     outs() << " Incorrect size\n";
8319   else
8320     outs() << "\n";
8321   outs() << "      ilocalsym " << dyst.ilocalsym;
8322   if (dyst.ilocalsym > nsyms)
8323     outs() << " (greater than the number of symbols)\n";
8324   else
8325     outs() << "\n";
8326   outs() << "      nlocalsym " << dyst.nlocalsym;
8327   uint64_t big_size;
8328   big_size = dyst.ilocalsym;
8329   big_size += dyst.nlocalsym;
8330   if (big_size > nsyms)
8331     outs() << " (past the end of the symbol table)\n";
8332   else
8333     outs() << "\n";
8334   outs() << "     iextdefsym " << dyst.iextdefsym;
8335   if (dyst.iextdefsym > nsyms)
8336     outs() << " (greater than the number of symbols)\n";
8337   else
8338     outs() << "\n";
8339   outs() << "     nextdefsym " << dyst.nextdefsym;
8340   big_size = dyst.iextdefsym;
8341   big_size += dyst.nextdefsym;
8342   if (big_size > nsyms)
8343     outs() << " (past the end of the symbol table)\n";
8344   else
8345     outs() << "\n";
8346   outs() << "      iundefsym " << dyst.iundefsym;
8347   if (dyst.iundefsym > nsyms)
8348     outs() << " (greater than the number of symbols)\n";
8349   else
8350     outs() << "\n";
8351   outs() << "      nundefsym " << dyst.nundefsym;
8352   big_size = dyst.iundefsym;
8353   big_size += dyst.nundefsym;
8354   if (big_size > nsyms)
8355     outs() << " (past the end of the symbol table)\n";
8356   else
8357     outs() << "\n";
8358   outs() << "         tocoff " << dyst.tocoff;
8359   if (dyst.tocoff > object_size)
8360     outs() << " (past end of file)\n";
8361   else
8362     outs() << "\n";
8363   outs() << "           ntoc " << dyst.ntoc;
8364   big_size = dyst.ntoc;
8365   big_size *= sizeof(struct MachO::dylib_table_of_contents);
8366   big_size += dyst.tocoff;
8367   if (big_size > object_size)
8368     outs() << " (past end of file)\n";
8369   else
8370     outs() << "\n";
8371   outs() << "      modtaboff " << dyst.modtaboff;
8372   if (dyst.modtaboff > object_size)
8373     outs() << " (past end of file)\n";
8374   else
8375     outs() << "\n";
8376   outs() << "        nmodtab " << dyst.nmodtab;
8377   uint64_t modtabend;
8378   if (Is64Bit) {
8379     modtabend = dyst.nmodtab;
8380     modtabend *= sizeof(struct MachO::dylib_module_64);
8381     modtabend += dyst.modtaboff;
8382   } else {
8383     modtabend = dyst.nmodtab;
8384     modtabend *= sizeof(struct MachO::dylib_module);
8385     modtabend += dyst.modtaboff;
8386   }
8387   if (modtabend > object_size)
8388     outs() << " (past end of file)\n";
8389   else
8390     outs() << "\n";
8391   outs() << "   extrefsymoff " << dyst.extrefsymoff;
8392   if (dyst.extrefsymoff > object_size)
8393     outs() << " (past end of file)\n";
8394   else
8395     outs() << "\n";
8396   outs() << "    nextrefsyms " << dyst.nextrefsyms;
8397   big_size = dyst.nextrefsyms;
8398   big_size *= sizeof(struct MachO::dylib_reference);
8399   big_size += dyst.extrefsymoff;
8400   if (big_size > object_size)
8401     outs() << " (past end of file)\n";
8402   else
8403     outs() << "\n";
8404   outs() << " indirectsymoff " << dyst.indirectsymoff;
8405   if (dyst.indirectsymoff > object_size)
8406     outs() << " (past end of file)\n";
8407   else
8408     outs() << "\n";
8409   outs() << "  nindirectsyms " << dyst.nindirectsyms;
8410   big_size = dyst.nindirectsyms;
8411   big_size *= sizeof(uint32_t);
8412   big_size += dyst.indirectsymoff;
8413   if (big_size > object_size)
8414     outs() << " (past end of file)\n";
8415   else
8416     outs() << "\n";
8417   outs() << "      extreloff " << dyst.extreloff;
8418   if (dyst.extreloff > object_size)
8419     outs() << " (past end of file)\n";
8420   else
8421     outs() << "\n";
8422   outs() << "        nextrel " << dyst.nextrel;
8423   big_size = dyst.nextrel;
8424   big_size *= sizeof(struct MachO::relocation_info);
8425   big_size += dyst.extreloff;
8426   if (big_size > object_size)
8427     outs() << " (past end of file)\n";
8428   else
8429     outs() << "\n";
8430   outs() << "      locreloff " << dyst.locreloff;
8431   if (dyst.locreloff > object_size)
8432     outs() << " (past end of file)\n";
8433   else
8434     outs() << "\n";
8435   outs() << "        nlocrel " << dyst.nlocrel;
8436   big_size = dyst.nlocrel;
8437   big_size *= sizeof(struct MachO::relocation_info);
8438   big_size += dyst.locreloff;
8439   if (big_size > object_size)
8440     outs() << " (past end of file)\n";
8441   else
8442     outs() << "\n";
8443 }
8444 
8445 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8446                                      uint32_t object_size) {
8447   if (dc.cmd == MachO::LC_DYLD_INFO)
8448     outs() << "            cmd LC_DYLD_INFO\n";
8449   else
8450     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
8451   outs() << "        cmdsize " << dc.cmdsize;
8452   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8453     outs() << " Incorrect size\n";
8454   else
8455     outs() << "\n";
8456   outs() << "     rebase_off " << dc.rebase_off;
8457   if (dc.rebase_off > object_size)
8458     outs() << " (past end of file)\n";
8459   else
8460     outs() << "\n";
8461   outs() << "    rebase_size " << dc.rebase_size;
8462   uint64_t big_size;
8463   big_size = dc.rebase_off;
8464   big_size += dc.rebase_size;
8465   if (big_size > object_size)
8466     outs() << " (past end of file)\n";
8467   else
8468     outs() << "\n";
8469   outs() << "       bind_off " << dc.bind_off;
8470   if (dc.bind_off > object_size)
8471     outs() << " (past end of file)\n";
8472   else
8473     outs() << "\n";
8474   outs() << "      bind_size " << dc.bind_size;
8475   big_size = dc.bind_off;
8476   big_size += dc.bind_size;
8477   if (big_size > object_size)
8478     outs() << " (past end of file)\n";
8479   else
8480     outs() << "\n";
8481   outs() << "  weak_bind_off " << dc.weak_bind_off;
8482   if (dc.weak_bind_off > object_size)
8483     outs() << " (past end of file)\n";
8484   else
8485     outs() << "\n";
8486   outs() << " weak_bind_size " << dc.weak_bind_size;
8487   big_size = dc.weak_bind_off;
8488   big_size += dc.weak_bind_size;
8489   if (big_size > object_size)
8490     outs() << " (past end of file)\n";
8491   else
8492     outs() << "\n";
8493   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
8494   if (dc.lazy_bind_off > object_size)
8495     outs() << " (past end of file)\n";
8496   else
8497     outs() << "\n";
8498   outs() << " lazy_bind_size " << dc.lazy_bind_size;
8499   big_size = dc.lazy_bind_off;
8500   big_size += dc.lazy_bind_size;
8501   if (big_size > object_size)
8502     outs() << " (past end of file)\n";
8503   else
8504     outs() << "\n";
8505   outs() << "     export_off " << dc.export_off;
8506   if (dc.export_off > object_size)
8507     outs() << " (past end of file)\n";
8508   else
8509     outs() << "\n";
8510   outs() << "    export_size " << dc.export_size;
8511   big_size = dc.export_off;
8512   big_size += dc.export_size;
8513   if (big_size > object_size)
8514     outs() << " (past end of file)\n";
8515   else
8516     outs() << "\n";
8517 }
8518 
8519 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8520                                  const char *Ptr) {
8521   if (dyld.cmd == MachO::LC_ID_DYLINKER)
8522     outs() << "          cmd LC_ID_DYLINKER\n";
8523   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8524     outs() << "          cmd LC_LOAD_DYLINKER\n";
8525   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8526     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
8527   else
8528     outs() << "          cmd ?(" << dyld.cmd << ")\n";
8529   outs() << "      cmdsize " << dyld.cmdsize;
8530   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8531     outs() << " Incorrect size\n";
8532   else
8533     outs() << "\n";
8534   if (dyld.name >= dyld.cmdsize)
8535     outs() << "         name ?(bad offset " << dyld.name << ")\n";
8536   else {
8537     const char *P = (const char *)(Ptr) + dyld.name;
8538     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
8539   }
8540 }
8541 
8542 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8543   outs() << "     cmd LC_UUID\n";
8544   outs() << " cmdsize " << uuid.cmdsize;
8545   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8546     outs() << " Incorrect size\n";
8547   else
8548     outs() << "\n";
8549   outs() << "    uuid ";
8550   for (int i = 0; i < 16; ++i) {
8551     outs() << format("%02" PRIX32, uuid.uuid[i]);
8552     if (i == 3 || i == 5 || i == 7 || i == 9)
8553       outs() << "-";
8554   }
8555   outs() << "\n";
8556 }
8557 
8558 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
8559   outs() << "          cmd LC_RPATH\n";
8560   outs() << "      cmdsize " << rpath.cmdsize;
8561   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8562     outs() << " Incorrect size\n";
8563   else
8564     outs() << "\n";
8565   if (rpath.path >= rpath.cmdsize)
8566     outs() << "         path ?(bad offset " << rpath.path << ")\n";
8567   else {
8568     const char *P = (const char *)(Ptr) + rpath.path;
8569     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
8570   }
8571 }
8572 
8573 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
8574   StringRef LoadCmdName;
8575   switch (vd.cmd) {
8576   case MachO::LC_VERSION_MIN_MACOSX:
8577     LoadCmdName = "LC_VERSION_MIN_MACOSX";
8578     break;
8579   case MachO::LC_VERSION_MIN_IPHONEOS:
8580     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8581     break;
8582   case MachO::LC_VERSION_MIN_TVOS:
8583     LoadCmdName = "LC_VERSION_MIN_TVOS";
8584     break;
8585   case MachO::LC_VERSION_MIN_WATCHOS:
8586     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8587     break;
8588   default:
8589     llvm_unreachable("Unknown version min load command");
8590   }
8591 
8592   outs() << "      cmd " << LoadCmdName << '\n';
8593   outs() << "  cmdsize " << vd.cmdsize;
8594   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8595     outs() << " Incorrect size\n";
8596   else
8597     outs() << "\n";
8598   outs() << "  version "
8599          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8600          << MachOObjectFile::getVersionMinMinor(vd, false);
8601   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8602   if (Update != 0)
8603     outs() << "." << Update;
8604   outs() << "\n";
8605   if (vd.sdk == 0)
8606     outs() << "      sdk n/a";
8607   else {
8608     outs() << "      sdk "
8609            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8610            << MachOObjectFile::getVersionMinMinor(vd, true);
8611   }
8612   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8613   if (Update != 0)
8614     outs() << "." << Update;
8615   outs() << "\n";
8616 }
8617 
8618 static void PrintNoteLoadCommand(MachO::note_command Nt) {
8619   outs() << "       cmd LC_NOTE\n";
8620   outs() << "   cmdsize " << Nt.cmdsize;
8621   if (Nt.cmdsize != sizeof(struct MachO::note_command))
8622     outs() << " Incorrect size\n";
8623   else
8624     outs() << "\n";
8625   const char *d = Nt.data_owner;
8626   outs() << "data_owner " << format("%.16s\n", d);
8627   outs() << "    offset " << Nt.offset << "\n";
8628   outs() << "      size " << Nt.size << "\n";
8629 }
8630 
8631 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8632   outs() << "      tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8633   outs() << "   version " << MachOObjectFile::getVersionString(bv.version)
8634          << "\n";
8635 }
8636 
8637 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8638                                          MachO::build_version_command bd) {
8639   outs() << "       cmd LC_BUILD_VERSION\n";
8640   outs() << "   cmdsize " << bd.cmdsize;
8641   if (bd.cmdsize !=
8642       sizeof(struct MachO::build_version_command) +
8643           bd.ntools * sizeof(struct MachO::build_tool_version))
8644     outs() << " Incorrect size\n";
8645   else
8646     outs() << "\n";
8647   outs() << "  platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8648          << "\n";
8649   if (bd.sdk)
8650     outs() << "       sdk " << MachOObjectFile::getVersionString(bd.sdk)
8651            << "\n";
8652   else
8653     outs() << "       sdk n/a\n";
8654   outs() << "     minos " << MachOObjectFile::getVersionString(bd.minos)
8655          << "\n";
8656   outs() << "    ntools " << bd.ntools << "\n";
8657   for (unsigned i = 0; i < bd.ntools; ++i) {
8658     MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8659     PrintBuildToolVersion(bv);
8660   }
8661 }
8662 
8663 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8664   outs() << "      cmd LC_SOURCE_VERSION\n";
8665   outs() << "  cmdsize " << sd.cmdsize;
8666   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8667     outs() << " Incorrect size\n";
8668   else
8669     outs() << "\n";
8670   uint64_t a = (sd.version >> 40) & 0xffffff;
8671   uint64_t b = (sd.version >> 30) & 0x3ff;
8672   uint64_t c = (sd.version >> 20) & 0x3ff;
8673   uint64_t d = (sd.version >> 10) & 0x3ff;
8674   uint64_t e = sd.version & 0x3ff;
8675   outs() << "  version " << a << "." << b;
8676   if (e != 0)
8677     outs() << "." << c << "." << d << "." << e;
8678   else if (d != 0)
8679     outs() << "." << c << "." << d;
8680   else if (c != 0)
8681     outs() << "." << c;
8682   outs() << "\n";
8683 }
8684 
8685 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8686   outs() << "       cmd LC_MAIN\n";
8687   outs() << "   cmdsize " << ep.cmdsize;
8688   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8689     outs() << " Incorrect size\n";
8690   else
8691     outs() << "\n";
8692   outs() << "  entryoff " << ep.entryoff << "\n";
8693   outs() << " stacksize " << ep.stacksize << "\n";
8694 }
8695 
8696 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8697                                        uint32_t object_size) {
8698   outs() << "          cmd LC_ENCRYPTION_INFO\n";
8699   outs() << "      cmdsize " << ec.cmdsize;
8700   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8701     outs() << " Incorrect size\n";
8702   else
8703     outs() << "\n";
8704   outs() << "     cryptoff " << ec.cryptoff;
8705   if (ec.cryptoff > object_size)
8706     outs() << " (past end of file)\n";
8707   else
8708     outs() << "\n";
8709   outs() << "    cryptsize " << ec.cryptsize;
8710   if (ec.cryptsize > object_size)
8711     outs() << " (past end of file)\n";
8712   else
8713     outs() << "\n";
8714   outs() << "      cryptid " << ec.cryptid << "\n";
8715 }
8716 
8717 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
8718                                          uint32_t object_size) {
8719   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
8720   outs() << "      cmdsize " << ec.cmdsize;
8721   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8722     outs() << " Incorrect size\n";
8723   else
8724     outs() << "\n";
8725   outs() << "     cryptoff " << ec.cryptoff;
8726   if (ec.cryptoff > object_size)
8727     outs() << " (past end of file)\n";
8728   else
8729     outs() << "\n";
8730   outs() << "    cryptsize " << ec.cryptsize;
8731   if (ec.cryptsize > object_size)
8732     outs() << " (past end of file)\n";
8733   else
8734     outs() << "\n";
8735   outs() << "      cryptid " << ec.cryptid << "\n";
8736   outs() << "          pad " << ec.pad << "\n";
8737 }
8738 
8739 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8740                                      const char *Ptr) {
8741   outs() << "     cmd LC_LINKER_OPTION\n";
8742   outs() << " cmdsize " << lo.cmdsize;
8743   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8744     outs() << " Incorrect size\n";
8745   else
8746     outs() << "\n";
8747   outs() << "   count " << lo.count << "\n";
8748   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8749   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8750   uint32_t i = 0;
8751   while (left > 0) {
8752     while (*string == '\0' && left > 0) {
8753       string++;
8754       left--;
8755     }
8756     if (left > 0) {
8757       i++;
8758       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
8759       uint32_t NullPos = StringRef(string, left).find('\0');
8760       uint32_t len = std::min(NullPos, left) + 1;
8761       string += len;
8762       left -= len;
8763     }
8764   }
8765   if (lo.count != i)
8766     outs() << "   count " << lo.count << " does not match number of strings "
8767            << i << "\n";
8768 }
8769 
8770 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8771                                      const char *Ptr) {
8772   outs() << "          cmd LC_SUB_FRAMEWORK\n";
8773   outs() << "      cmdsize " << sub.cmdsize;
8774   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8775     outs() << " Incorrect size\n";
8776   else
8777     outs() << "\n";
8778   if (sub.umbrella < sub.cmdsize) {
8779     const char *P = Ptr + sub.umbrella;
8780     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
8781   } else {
8782     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
8783   }
8784 }
8785 
8786 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8787                                     const char *Ptr) {
8788   outs() << "          cmd LC_SUB_UMBRELLA\n";
8789   outs() << "      cmdsize " << sub.cmdsize;
8790   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8791     outs() << " Incorrect size\n";
8792   else
8793     outs() << "\n";
8794   if (sub.sub_umbrella < sub.cmdsize) {
8795     const char *P = Ptr + sub.sub_umbrella;
8796     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8797   } else {
8798     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8799   }
8800 }
8801 
8802 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
8803                                    const char *Ptr) {
8804   outs() << "          cmd LC_SUB_LIBRARY\n";
8805   outs() << "      cmdsize " << sub.cmdsize;
8806   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8807     outs() << " Incorrect size\n";
8808   else
8809     outs() << "\n";
8810   if (sub.sub_library < sub.cmdsize) {
8811     const char *P = Ptr + sub.sub_library;
8812     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
8813   } else {
8814     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
8815   }
8816 }
8817 
8818 static void PrintSubClientCommand(MachO::sub_client_command sub,
8819                                   const char *Ptr) {
8820   outs() << "          cmd LC_SUB_CLIENT\n";
8821   outs() << "      cmdsize " << sub.cmdsize;
8822   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8823     outs() << " Incorrect size\n";
8824   else
8825     outs() << "\n";
8826   if (sub.client < sub.cmdsize) {
8827     const char *P = Ptr + sub.client;
8828     outs() << "       client " << P << " (offset " << sub.client << ")\n";
8829   } else {
8830     outs() << "       client ?(bad offset " << sub.client << ")\n";
8831   }
8832 }
8833 
8834 static void PrintRoutinesCommand(MachO::routines_command r) {
8835   outs() << "          cmd LC_ROUTINES\n";
8836   outs() << "      cmdsize " << r.cmdsize;
8837   if (r.cmdsize != sizeof(struct MachO::routines_command))
8838     outs() << " Incorrect size\n";
8839   else
8840     outs() << "\n";
8841   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8842   outs() << "  init_module " << r.init_module << "\n";
8843   outs() << "    reserved1 " << r.reserved1 << "\n";
8844   outs() << "    reserved2 " << r.reserved2 << "\n";
8845   outs() << "    reserved3 " << r.reserved3 << "\n";
8846   outs() << "    reserved4 " << r.reserved4 << "\n";
8847   outs() << "    reserved5 " << r.reserved5 << "\n";
8848   outs() << "    reserved6 " << r.reserved6 << "\n";
8849 }
8850 
8851 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8852   outs() << "          cmd LC_ROUTINES_64\n";
8853   outs() << "      cmdsize " << r.cmdsize;
8854   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8855     outs() << " Incorrect size\n";
8856   else
8857     outs() << "\n";
8858   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8859   outs() << "  init_module " << r.init_module << "\n";
8860   outs() << "    reserved1 " << r.reserved1 << "\n";
8861   outs() << "    reserved2 " << r.reserved2 << "\n";
8862   outs() << "    reserved3 " << r.reserved3 << "\n";
8863   outs() << "    reserved4 " << r.reserved4 << "\n";
8864   outs() << "    reserved5 " << r.reserved5 << "\n";
8865   outs() << "    reserved6 " << r.reserved6 << "\n";
8866 }
8867 
8868 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8869   outs() << "\t    eax " << format("0x%08" PRIx32, cpu32.eax);
8870   outs() << " ebx    " << format("0x%08" PRIx32, cpu32.ebx);
8871   outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8872   outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8873   outs() << "\t    edi " << format("0x%08" PRIx32, cpu32.edi);
8874   outs() << " esi    " << format("0x%08" PRIx32, cpu32.esi);
8875   outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8876   outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8877   outs() << "\t    ss  " << format("0x%08" PRIx32, cpu32.ss);
8878   outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8879   outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8880   outs() << " cs  " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8881   outs() << "\t    ds  " << format("0x%08" PRIx32, cpu32.ds);
8882   outs() << " es     " << format("0x%08" PRIx32, cpu32.es);
8883   outs() << " fs  " << format("0x%08" PRIx32, cpu32.fs);
8884   outs() << " gs  " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8885 }
8886 
8887 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8888   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
8889   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8890   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8891   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
8892   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8893   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8894   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
8895   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8896   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8897   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
8898   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8899   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8900   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
8901   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8902   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8903   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
8904   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8905   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
8906   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
8907   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8908   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8909 }
8910 
8911 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
8912   uint32_t f;
8913   outs() << "\t      mmst_reg  ";
8914   for (f = 0; f < 10; f++)
8915     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8916   outs() << "\n";
8917   outs() << "\t      mmst_rsrv ";
8918   for (f = 0; f < 6; f++)
8919     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8920   outs() << "\n";
8921 }
8922 
8923 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
8924   uint32_t f;
8925   outs() << "\t      xmm_reg ";
8926   for (f = 0; f < 16; f++)
8927     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8928   outs() << "\n";
8929 }
8930 
8931 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8932   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
8933   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8934   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
8935   outs() << " denorm " << fpu.fpu_fcw.denorm;
8936   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8937   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8938   outs() << " undfl " << fpu.fpu_fcw.undfl;
8939   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8940   outs() << "\t\t     pc ";
8941   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8942     outs() << "FP_PREC_24B ";
8943   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8944     outs() << "FP_PREC_53B ";
8945   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8946     outs() << "FP_PREC_64B ";
8947   else
8948     outs() << fpu.fpu_fcw.pc << " ";
8949   outs() << "rc ";
8950   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8951     outs() << "FP_RND_NEAR ";
8952   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8953     outs() << "FP_RND_DOWN ";
8954   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8955     outs() << "FP_RND_UP ";
8956   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
8957     outs() << "FP_CHOP ";
8958   outs() << "\n";
8959   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
8960   outs() << " denorm " << fpu.fpu_fsw.denorm;
8961   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8962   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8963   outs() << " undfl " << fpu.fpu_fsw.undfl;
8964   outs() << " precis " << fpu.fpu_fsw.precis;
8965   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8966   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
8967   outs() << " c0 " << fpu.fpu_fsw.c0;
8968   outs() << " c1 " << fpu.fpu_fsw.c1;
8969   outs() << " c2 " << fpu.fpu_fsw.c2;
8970   outs() << " tos " << fpu.fpu_fsw.tos;
8971   outs() << " c3 " << fpu.fpu_fsw.c3;
8972   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8973   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8974   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8975   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8976   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8977   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8978   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8979   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8980   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8981   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8982   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8983   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8984   outs() << "\n";
8985   outs() << "\t    fpu_stmm0:\n";
8986   Print_mmst_reg(fpu.fpu_stmm0);
8987   outs() << "\t    fpu_stmm1:\n";
8988   Print_mmst_reg(fpu.fpu_stmm1);
8989   outs() << "\t    fpu_stmm2:\n";
8990   Print_mmst_reg(fpu.fpu_stmm2);
8991   outs() << "\t    fpu_stmm3:\n";
8992   Print_mmst_reg(fpu.fpu_stmm3);
8993   outs() << "\t    fpu_stmm4:\n";
8994   Print_mmst_reg(fpu.fpu_stmm4);
8995   outs() << "\t    fpu_stmm5:\n";
8996   Print_mmst_reg(fpu.fpu_stmm5);
8997   outs() << "\t    fpu_stmm6:\n";
8998   Print_mmst_reg(fpu.fpu_stmm6);
8999   outs() << "\t    fpu_stmm7:\n";
9000   Print_mmst_reg(fpu.fpu_stmm7);
9001   outs() << "\t    fpu_xmm0:\n";
9002   Print_xmm_reg(fpu.fpu_xmm0);
9003   outs() << "\t    fpu_xmm1:\n";
9004   Print_xmm_reg(fpu.fpu_xmm1);
9005   outs() << "\t    fpu_xmm2:\n";
9006   Print_xmm_reg(fpu.fpu_xmm2);
9007   outs() << "\t    fpu_xmm3:\n";
9008   Print_xmm_reg(fpu.fpu_xmm3);
9009   outs() << "\t    fpu_xmm4:\n";
9010   Print_xmm_reg(fpu.fpu_xmm4);
9011   outs() << "\t    fpu_xmm5:\n";
9012   Print_xmm_reg(fpu.fpu_xmm5);
9013   outs() << "\t    fpu_xmm6:\n";
9014   Print_xmm_reg(fpu.fpu_xmm6);
9015   outs() << "\t    fpu_xmm7:\n";
9016   Print_xmm_reg(fpu.fpu_xmm7);
9017   outs() << "\t    fpu_xmm8:\n";
9018   Print_xmm_reg(fpu.fpu_xmm8);
9019   outs() << "\t    fpu_xmm9:\n";
9020   Print_xmm_reg(fpu.fpu_xmm9);
9021   outs() << "\t    fpu_xmm10:\n";
9022   Print_xmm_reg(fpu.fpu_xmm10);
9023   outs() << "\t    fpu_xmm11:\n";
9024   Print_xmm_reg(fpu.fpu_xmm11);
9025   outs() << "\t    fpu_xmm12:\n";
9026   Print_xmm_reg(fpu.fpu_xmm12);
9027   outs() << "\t    fpu_xmm13:\n";
9028   Print_xmm_reg(fpu.fpu_xmm13);
9029   outs() << "\t    fpu_xmm14:\n";
9030   Print_xmm_reg(fpu.fpu_xmm14);
9031   outs() << "\t    fpu_xmm15:\n";
9032   Print_xmm_reg(fpu.fpu_xmm15);
9033   outs() << "\t    fpu_rsrv4:\n";
9034   for (uint32_t f = 0; f < 6; f++) {
9035     outs() << "\t            ";
9036     for (uint32_t g = 0; g < 16; g++)
9037       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9038     outs() << "\n";
9039   }
9040   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9041   outs() << "\n";
9042 }
9043 
9044 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9045   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
9046   outs() << " err " << format("0x%08" PRIx32, exc64.err);
9047   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9048 }
9049 
9050 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9051   outs() << "\t    r0  " << format("0x%08" PRIx32, cpu32.r[0]);
9052   outs() << " r1     "   << format("0x%08" PRIx32, cpu32.r[1]);
9053   outs() << " r2  "      << format("0x%08" PRIx32, cpu32.r[2]);
9054   outs() << " r3  "      << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9055   outs() << "\t    r4  " << format("0x%08" PRIx32, cpu32.r[4]);
9056   outs() << " r5     "   << format("0x%08" PRIx32, cpu32.r[5]);
9057   outs() << " r6  "      << format("0x%08" PRIx32, cpu32.r[6]);
9058   outs() << " r7  "      << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9059   outs() << "\t    r8  " << format("0x%08" PRIx32, cpu32.r[8]);
9060   outs() << " r9     "   << format("0x%08" PRIx32, cpu32.r[9]);
9061   outs() << " r10 "      << format("0x%08" PRIx32, cpu32.r[10]);
9062   outs() << " r11 "      << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9063   outs() << "\t    r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9064   outs() << " sp     "   << format("0x%08" PRIx32, cpu32.sp);
9065   outs() << " lr  "      << format("0x%08" PRIx32, cpu32.lr);
9066   outs() << " pc  "      << format("0x%08" PRIx32, cpu32.pc) << "\n";
9067   outs() << "\t   cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9068 }
9069 
9070 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9071   outs() << "\t    x0  " << format("0x%016" PRIx64, cpu64.x[0]);
9072   outs() << " x1  "      << format("0x%016" PRIx64, cpu64.x[1]);
9073   outs() << " x2  "      << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9074   outs() << "\t    x3  " << format("0x%016" PRIx64, cpu64.x[3]);
9075   outs() << " x4  "      << format("0x%016" PRIx64, cpu64.x[4]);
9076   outs() << " x5  "      << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9077   outs() << "\t    x6  " << format("0x%016" PRIx64, cpu64.x[6]);
9078   outs() << " x7  "      << format("0x%016" PRIx64, cpu64.x[7]);
9079   outs() << " x8  "      << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9080   outs() << "\t    x9  " << format("0x%016" PRIx64, cpu64.x[9]);
9081   outs() << " x10 "      << format("0x%016" PRIx64, cpu64.x[10]);
9082   outs() << " x11 "      << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9083   outs() << "\t    x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9084   outs() << " x13 "      << format("0x%016" PRIx64, cpu64.x[13]);
9085   outs() << " x14 "      << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9086   outs() << "\t    x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9087   outs() << " x16 "      << format("0x%016" PRIx64, cpu64.x[16]);
9088   outs() << " x17 "      << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9089   outs() << "\t    x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9090   outs() << " x19 "      << format("0x%016" PRIx64, cpu64.x[19]);
9091   outs() << " x20 "      << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9092   outs() << "\t    x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9093   outs() << " x22 "      << format("0x%016" PRIx64, cpu64.x[22]);
9094   outs() << " x23 "      << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9095   outs() << "\t    x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9096   outs() << " x25 "      << format("0x%016" PRIx64, cpu64.x[25]);
9097   outs() << " x26 "      << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9098   outs() << "\t    x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9099   outs() << " x28 "      << format("0x%016" PRIx64, cpu64.x[28]);
9100   outs() << "  fp "      << format("0x%016" PRIx64, cpu64.fp) << "\n";
9101   outs() << "\t     lr " << format("0x%016" PRIx64, cpu64.lr);
9102   outs() << " sp  "      << format("0x%016" PRIx64, cpu64.sp);
9103   outs() << "  pc "      << format("0x%016" PRIx64, cpu64.pc) << "\n";
9104   outs() << "\t   cpsr " << format("0x%08"  PRIx32, cpu64.cpsr) << "\n";
9105 }
9106 
9107 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9108                                bool isLittleEndian, uint32_t cputype) {
9109   if (t.cmd == MachO::LC_THREAD)
9110     outs() << "        cmd LC_THREAD\n";
9111   else if (t.cmd == MachO::LC_UNIXTHREAD)
9112     outs() << "        cmd LC_UNIXTHREAD\n";
9113   else
9114     outs() << "        cmd " << t.cmd << " (unknown)\n";
9115   outs() << "    cmdsize " << t.cmdsize;
9116   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9117     outs() << " Incorrect size\n";
9118   else
9119     outs() << "\n";
9120 
9121   const char *begin = Ptr + sizeof(struct MachO::thread_command);
9122   const char *end = Ptr + t.cmdsize;
9123   uint32_t flavor, count, left;
9124   if (cputype == MachO::CPU_TYPE_I386) {
9125     while (begin < end) {
9126       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9127         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9128         begin += sizeof(uint32_t);
9129       } else {
9130         flavor = 0;
9131         begin = end;
9132       }
9133       if (isLittleEndian != sys::IsLittleEndianHost)
9134         sys::swapByteOrder(flavor);
9135       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9136         memcpy((char *)&count, begin, sizeof(uint32_t));
9137         begin += sizeof(uint32_t);
9138       } else {
9139         count = 0;
9140         begin = end;
9141       }
9142       if (isLittleEndian != sys::IsLittleEndianHost)
9143         sys::swapByteOrder(count);
9144       if (flavor == MachO::x86_THREAD_STATE32) {
9145         outs() << "     flavor i386_THREAD_STATE\n";
9146         if (count == MachO::x86_THREAD_STATE32_COUNT)
9147           outs() << "      count i386_THREAD_STATE_COUNT\n";
9148         else
9149           outs() << "      count " << count
9150                  << " (not x86_THREAD_STATE32_COUNT)\n";
9151         MachO::x86_thread_state32_t cpu32;
9152         left = end - begin;
9153         if (left >= sizeof(MachO::x86_thread_state32_t)) {
9154           memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9155           begin += sizeof(MachO::x86_thread_state32_t);
9156         } else {
9157           memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9158           memcpy(&cpu32, begin, left);
9159           begin += left;
9160         }
9161         if (isLittleEndian != sys::IsLittleEndianHost)
9162           swapStruct(cpu32);
9163         Print_x86_thread_state32_t(cpu32);
9164       } else if (flavor == MachO::x86_THREAD_STATE) {
9165         outs() << "     flavor x86_THREAD_STATE\n";
9166         if (count == MachO::x86_THREAD_STATE_COUNT)
9167           outs() << "      count x86_THREAD_STATE_COUNT\n";
9168         else
9169           outs() << "      count " << count
9170                  << " (not x86_THREAD_STATE_COUNT)\n";
9171         struct MachO::x86_thread_state_t ts;
9172         left = end - begin;
9173         if (left >= sizeof(MachO::x86_thread_state_t)) {
9174           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9175           begin += sizeof(MachO::x86_thread_state_t);
9176         } else {
9177           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9178           memcpy(&ts, begin, left);
9179           begin += left;
9180         }
9181         if (isLittleEndian != sys::IsLittleEndianHost)
9182           swapStruct(ts);
9183         if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9184           outs() << "\t    tsh.flavor x86_THREAD_STATE32 ";
9185           if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9186             outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9187           else
9188             outs() << "tsh.count " << ts.tsh.count
9189                    << " (not x86_THREAD_STATE32_COUNT\n";
9190           Print_x86_thread_state32_t(ts.uts.ts32);
9191         } else {
9192           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9193                  << ts.tsh.count << "\n";
9194         }
9195       } else {
9196         outs() << "     flavor " << flavor << " (unknown)\n";
9197         outs() << "      count " << count << "\n";
9198         outs() << "      state (unknown)\n";
9199         begin += count * sizeof(uint32_t);
9200       }
9201     }
9202   } else if (cputype == MachO::CPU_TYPE_X86_64) {
9203     while (begin < end) {
9204       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9205         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9206         begin += sizeof(uint32_t);
9207       } else {
9208         flavor = 0;
9209         begin = end;
9210       }
9211       if (isLittleEndian != sys::IsLittleEndianHost)
9212         sys::swapByteOrder(flavor);
9213       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9214         memcpy((char *)&count, begin, sizeof(uint32_t));
9215         begin += sizeof(uint32_t);
9216       } else {
9217         count = 0;
9218         begin = end;
9219       }
9220       if (isLittleEndian != sys::IsLittleEndianHost)
9221         sys::swapByteOrder(count);
9222       if (flavor == MachO::x86_THREAD_STATE64) {
9223         outs() << "     flavor x86_THREAD_STATE64\n";
9224         if (count == MachO::x86_THREAD_STATE64_COUNT)
9225           outs() << "      count x86_THREAD_STATE64_COUNT\n";
9226         else
9227           outs() << "      count " << count
9228                  << " (not x86_THREAD_STATE64_COUNT)\n";
9229         MachO::x86_thread_state64_t cpu64;
9230         left = end - begin;
9231         if (left >= sizeof(MachO::x86_thread_state64_t)) {
9232           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9233           begin += sizeof(MachO::x86_thread_state64_t);
9234         } else {
9235           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9236           memcpy(&cpu64, begin, left);
9237           begin += left;
9238         }
9239         if (isLittleEndian != sys::IsLittleEndianHost)
9240           swapStruct(cpu64);
9241         Print_x86_thread_state64_t(cpu64);
9242       } else if (flavor == MachO::x86_THREAD_STATE) {
9243         outs() << "     flavor x86_THREAD_STATE\n";
9244         if (count == MachO::x86_THREAD_STATE_COUNT)
9245           outs() << "      count x86_THREAD_STATE_COUNT\n";
9246         else
9247           outs() << "      count " << count
9248                  << " (not x86_THREAD_STATE_COUNT)\n";
9249         struct MachO::x86_thread_state_t ts;
9250         left = end - begin;
9251         if (left >= sizeof(MachO::x86_thread_state_t)) {
9252           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9253           begin += sizeof(MachO::x86_thread_state_t);
9254         } else {
9255           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9256           memcpy(&ts, begin, left);
9257           begin += left;
9258         }
9259         if (isLittleEndian != sys::IsLittleEndianHost)
9260           swapStruct(ts);
9261         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9262           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
9263           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9264             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9265           else
9266             outs() << "tsh.count " << ts.tsh.count
9267                    << " (not x86_THREAD_STATE64_COUNT\n";
9268           Print_x86_thread_state64_t(ts.uts.ts64);
9269         } else {
9270           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
9271                  << ts.tsh.count << "\n";
9272         }
9273       } else if (flavor == MachO::x86_FLOAT_STATE) {
9274         outs() << "     flavor x86_FLOAT_STATE\n";
9275         if (count == MachO::x86_FLOAT_STATE_COUNT)
9276           outs() << "      count x86_FLOAT_STATE_COUNT\n";
9277         else
9278           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9279         struct MachO::x86_float_state_t fs;
9280         left = end - begin;
9281         if (left >= sizeof(MachO::x86_float_state_t)) {
9282           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9283           begin += sizeof(MachO::x86_float_state_t);
9284         } else {
9285           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9286           memcpy(&fs, begin, left);
9287           begin += left;
9288         }
9289         if (isLittleEndian != sys::IsLittleEndianHost)
9290           swapStruct(fs);
9291         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9292           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
9293           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9294             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9295           else
9296             outs() << "fsh.count " << fs.fsh.count
9297                    << " (not x86_FLOAT_STATE64_COUNT\n";
9298           Print_x86_float_state_t(fs.ufs.fs64);
9299         } else {
9300           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
9301                  << fs.fsh.count << "\n";
9302         }
9303       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9304         outs() << "     flavor x86_EXCEPTION_STATE\n";
9305         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9306           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
9307         else
9308           outs() << "      count " << count
9309                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
9310         struct MachO::x86_exception_state_t es;
9311         left = end - begin;
9312         if (left >= sizeof(MachO::x86_exception_state_t)) {
9313           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9314           begin += sizeof(MachO::x86_exception_state_t);
9315         } else {
9316           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9317           memcpy(&es, begin, left);
9318           begin += left;
9319         }
9320         if (isLittleEndian != sys::IsLittleEndianHost)
9321           swapStruct(es);
9322         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9323           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
9324           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9325             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
9326           else
9327             outs() << "\t    esh.count " << es.esh.count
9328                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
9329           Print_x86_exception_state_t(es.ues.es64);
9330         } else {
9331           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
9332                  << es.esh.count << "\n";
9333         }
9334       } else {
9335         outs() << "     flavor " << flavor << " (unknown)\n";
9336         outs() << "      count " << count << "\n";
9337         outs() << "      state (unknown)\n";
9338         begin += count * sizeof(uint32_t);
9339       }
9340     }
9341   } else if (cputype == MachO::CPU_TYPE_ARM) {
9342     while (begin < end) {
9343       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9344         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9345         begin += sizeof(uint32_t);
9346       } else {
9347         flavor = 0;
9348         begin = end;
9349       }
9350       if (isLittleEndian != sys::IsLittleEndianHost)
9351         sys::swapByteOrder(flavor);
9352       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9353         memcpy((char *)&count, begin, sizeof(uint32_t));
9354         begin += sizeof(uint32_t);
9355       } else {
9356         count = 0;
9357         begin = end;
9358       }
9359       if (isLittleEndian != sys::IsLittleEndianHost)
9360         sys::swapByteOrder(count);
9361       if (flavor == MachO::ARM_THREAD_STATE) {
9362         outs() << "     flavor ARM_THREAD_STATE\n";
9363         if (count == MachO::ARM_THREAD_STATE_COUNT)
9364           outs() << "      count ARM_THREAD_STATE_COUNT\n";
9365         else
9366           outs() << "      count " << count
9367                  << " (not ARM_THREAD_STATE_COUNT)\n";
9368         MachO::arm_thread_state32_t cpu32;
9369         left = end - begin;
9370         if (left >= sizeof(MachO::arm_thread_state32_t)) {
9371           memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9372           begin += sizeof(MachO::arm_thread_state32_t);
9373         } else {
9374           memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9375           memcpy(&cpu32, begin, left);
9376           begin += left;
9377         }
9378         if (isLittleEndian != sys::IsLittleEndianHost)
9379           swapStruct(cpu32);
9380         Print_arm_thread_state32_t(cpu32);
9381       } else {
9382         outs() << "     flavor " << flavor << " (unknown)\n";
9383         outs() << "      count " << count << "\n";
9384         outs() << "      state (unknown)\n";
9385         begin += count * sizeof(uint32_t);
9386       }
9387     }
9388   } else if (cputype == MachO::CPU_TYPE_ARM64) {
9389     while (begin < end) {
9390       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9391         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9392         begin += sizeof(uint32_t);
9393       } else {
9394         flavor = 0;
9395         begin = end;
9396       }
9397       if (isLittleEndian != sys::IsLittleEndianHost)
9398         sys::swapByteOrder(flavor);
9399       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9400         memcpy((char *)&count, begin, sizeof(uint32_t));
9401         begin += sizeof(uint32_t);
9402       } else {
9403         count = 0;
9404         begin = end;
9405       }
9406       if (isLittleEndian != sys::IsLittleEndianHost)
9407         sys::swapByteOrder(count);
9408       if (flavor == MachO::ARM_THREAD_STATE64) {
9409         outs() << "     flavor ARM_THREAD_STATE64\n";
9410         if (count == MachO::ARM_THREAD_STATE64_COUNT)
9411           outs() << "      count ARM_THREAD_STATE64_COUNT\n";
9412         else
9413           outs() << "      count " << count
9414                  << " (not ARM_THREAD_STATE64_COUNT)\n";
9415         MachO::arm_thread_state64_t cpu64;
9416         left = end - begin;
9417         if (left >= sizeof(MachO::arm_thread_state64_t)) {
9418           memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9419           begin += sizeof(MachO::arm_thread_state64_t);
9420         } else {
9421           memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9422           memcpy(&cpu64, begin, left);
9423           begin += left;
9424         }
9425         if (isLittleEndian != sys::IsLittleEndianHost)
9426           swapStruct(cpu64);
9427         Print_arm_thread_state64_t(cpu64);
9428       } else {
9429         outs() << "     flavor " << flavor << " (unknown)\n";
9430         outs() << "      count " << count << "\n";
9431         outs() << "      state (unknown)\n";
9432         begin += count * sizeof(uint32_t);
9433       }
9434     }
9435   } else {
9436     while (begin < end) {
9437       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9438         memcpy((char *)&flavor, begin, sizeof(uint32_t));
9439         begin += sizeof(uint32_t);
9440       } else {
9441         flavor = 0;
9442         begin = end;
9443       }
9444       if (isLittleEndian != sys::IsLittleEndianHost)
9445         sys::swapByteOrder(flavor);
9446       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9447         memcpy((char *)&count, begin, sizeof(uint32_t));
9448         begin += sizeof(uint32_t);
9449       } else {
9450         count = 0;
9451         begin = end;
9452       }
9453       if (isLittleEndian != sys::IsLittleEndianHost)
9454         sys::swapByteOrder(count);
9455       outs() << "     flavor " << flavor << "\n";
9456       outs() << "      count " << count << "\n";
9457       outs() << "      state (Unknown cputype/cpusubtype)\n";
9458       begin += count * sizeof(uint32_t);
9459     }
9460   }
9461 }
9462 
9463 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9464   if (dl.cmd == MachO::LC_ID_DYLIB)
9465     outs() << "          cmd LC_ID_DYLIB\n";
9466   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9467     outs() << "          cmd LC_LOAD_DYLIB\n";
9468   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9469     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
9470   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9471     outs() << "          cmd LC_REEXPORT_DYLIB\n";
9472   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9473     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
9474   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9475     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
9476   else
9477     outs() << "          cmd " << dl.cmd << " (unknown)\n";
9478   outs() << "      cmdsize " << dl.cmdsize;
9479   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9480     outs() << " Incorrect size\n";
9481   else
9482     outs() << "\n";
9483   if (dl.dylib.name < dl.cmdsize) {
9484     const char *P = (const char *)(Ptr) + dl.dylib.name;
9485     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
9486   } else {
9487     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
9488   }
9489   outs() << "   time stamp " << dl.dylib.timestamp << " ";
9490   time_t t = dl.dylib.timestamp;
9491   outs() << ctime(&t);
9492   outs() << "      current version ";
9493   if (dl.dylib.current_version == 0xffffffff)
9494     outs() << "n/a\n";
9495   else
9496     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9497            << ((dl.dylib.current_version >> 8) & 0xff) << "."
9498            << (dl.dylib.current_version & 0xff) << "\n";
9499   outs() << "compatibility version ";
9500   if (dl.dylib.compatibility_version == 0xffffffff)
9501     outs() << "n/a\n";
9502   else
9503     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9504            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9505            << (dl.dylib.compatibility_version & 0xff) << "\n";
9506 }
9507 
9508 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9509                                      uint32_t object_size) {
9510   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
9511     outs() << "      cmd LC_CODE_SIGNATURE\n";
9512   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9513     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
9514   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9515     outs() << "      cmd LC_FUNCTION_STARTS\n";
9516   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9517     outs() << "      cmd LC_DATA_IN_CODE\n";
9518   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9519     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
9520   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9521     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
9522   else
9523     outs() << "      cmd " << ld.cmd << " (?)\n";
9524   outs() << "  cmdsize " << ld.cmdsize;
9525   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9526     outs() << " Incorrect size\n";
9527   else
9528     outs() << "\n";
9529   outs() << "  dataoff " << ld.dataoff;
9530   if (ld.dataoff > object_size)
9531     outs() << " (past end of file)\n";
9532   else
9533     outs() << "\n";
9534   outs() << " datasize " << ld.datasize;
9535   uint64_t big_size = ld.dataoff;
9536   big_size += ld.datasize;
9537   if (big_size > object_size)
9538     outs() << " (past end of file)\n";
9539   else
9540     outs() << "\n";
9541 }
9542 
9543 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9544                               uint32_t cputype, bool verbose) {
9545   StringRef Buf = Obj->getData();
9546   unsigned Index = 0;
9547   for (const auto &Command : Obj->load_commands()) {
9548     outs() << "Load command " << Index++ << "\n";
9549     if (Command.C.cmd == MachO::LC_SEGMENT) {
9550       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9551       const char *sg_segname = SLC.segname;
9552       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9553                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9554                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9555                           verbose);
9556       for (unsigned j = 0; j < SLC.nsects; j++) {
9557         MachO::section S = Obj->getSection(Command, j);
9558         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9559                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9560                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9561       }
9562     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9563       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9564       const char *sg_segname = SLC_64.segname;
9565       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9566                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9567                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9568                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9569       for (unsigned j = 0; j < SLC_64.nsects; j++) {
9570         MachO::section_64 S_64 = Obj->getSection64(Command, j);
9571         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9572                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9573                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9574                      sg_segname, filetype, Buf.size(), verbose);
9575       }
9576     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9577       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
9578       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
9579     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9580       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9581       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
9582       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9583                                Obj->is64Bit());
9584     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9585                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9586       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9587       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9588     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9589                Command.C.cmd == MachO::LC_ID_DYLINKER ||
9590                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9591       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9592       PrintDyldLoadCommand(Dyld, Command.Ptr);
9593     } else if (Command.C.cmd == MachO::LC_UUID) {
9594       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9595       PrintUuidLoadCommand(Uuid);
9596     } else if (Command.C.cmd == MachO::LC_RPATH) {
9597       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9598       PrintRpathLoadCommand(Rpath, Command.Ptr);
9599     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
9600                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9601                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9602                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
9603       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9604       PrintVersionMinLoadCommand(Vd);
9605     } else if (Command.C.cmd == MachO::LC_NOTE) {
9606       MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9607       PrintNoteLoadCommand(Nt);
9608     } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9609       MachO::build_version_command Bv =
9610           Obj->getBuildVersionLoadCommand(Command);
9611       PrintBuildVersionLoadCommand(Obj, Bv);
9612     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9613       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9614       PrintSourceVersionCommand(Sd);
9615     } else if (Command.C.cmd == MachO::LC_MAIN) {
9616       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9617       PrintEntryPointCommand(Ep);
9618     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
9619       MachO::encryption_info_command Ei =
9620           Obj->getEncryptionInfoCommand(Command);
9621       PrintEncryptionInfoCommand(Ei, Buf.size());
9622     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
9623       MachO::encryption_info_command_64 Ei =
9624           Obj->getEncryptionInfoCommand64(Command);
9625       PrintEncryptionInfoCommand64(Ei, Buf.size());
9626     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
9627       MachO::linker_option_command Lo =
9628           Obj->getLinkerOptionLoadCommand(Command);
9629       PrintLinkerOptionCommand(Lo, Command.Ptr);
9630     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9631       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9632       PrintSubFrameworkCommand(Sf, Command.Ptr);
9633     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9634       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9635       PrintSubUmbrellaCommand(Sf, Command.Ptr);
9636     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9637       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9638       PrintSubLibraryCommand(Sl, Command.Ptr);
9639     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9640       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9641       PrintSubClientCommand(Sc, Command.Ptr);
9642     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9643       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9644       PrintRoutinesCommand(Rc);
9645     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9646       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9647       PrintRoutinesCommand64(Rc);
9648     } else if (Command.C.cmd == MachO::LC_THREAD ||
9649                Command.C.cmd == MachO::LC_UNIXTHREAD) {
9650       MachO::thread_command Tc = Obj->getThreadCommand(Command);
9651       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
9652     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9653                Command.C.cmd == MachO::LC_ID_DYLIB ||
9654                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9655                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9656                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9657                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
9658       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9659       PrintDylibCommand(Dl, Command.Ptr);
9660     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9661                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9662                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9663                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9664                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9665                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9666       MachO::linkedit_data_command Ld =
9667           Obj->getLinkeditDataLoadCommand(Command);
9668       PrintLinkEditDataCommand(Ld, Buf.size());
9669     } else {
9670       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9671              << ")\n";
9672       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
9673       // TODO: get and print the raw bytes of the load command.
9674     }
9675     // TODO: print all the other kinds of load commands.
9676   }
9677 }
9678 
9679 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
9680   if (Obj->is64Bit()) {
9681     MachO::mach_header_64 H_64;
9682     H_64 = Obj->getHeader64();
9683     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9684                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9685   } else {
9686     MachO::mach_header H;
9687     H = Obj->getHeader();
9688     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9689                     H.sizeofcmds, H.flags, verbose);
9690   }
9691 }
9692 
9693 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9694   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
9695   PrintMachHeader(file, !NonVerbose);
9696 }
9697 
9698 void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9699   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
9700   uint32_t filetype = 0;
9701   uint32_t cputype = 0;
9702   if (file->is64Bit()) {
9703     MachO::mach_header_64 H_64;
9704     H_64 = file->getHeader64();
9705     filetype = H_64.filetype;
9706     cputype = H_64.cputype;
9707   } else {
9708     MachO::mach_header H;
9709     H = file->getHeader();
9710     filetype = H.filetype;
9711     cputype = H.cputype;
9712   }
9713   PrintLoadCommands(file, filetype, cputype, !NonVerbose);
9714 }
9715 
9716 //===----------------------------------------------------------------------===//
9717 // export trie dumping
9718 //===----------------------------------------------------------------------===//
9719 
9720 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
9721   uint64_t BaseSegmentAddress = 0;
9722   for (const auto &Command : Obj->load_commands()) {
9723     if (Command.C.cmd == MachO::LC_SEGMENT) {
9724       MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9725       if (Seg.fileoff == 0 && Seg.filesize != 0) {
9726         BaseSegmentAddress = Seg.vmaddr;
9727         break;
9728       }
9729     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9730       MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9731       if (Seg.fileoff == 0 && Seg.filesize != 0) {
9732         BaseSegmentAddress = Seg.vmaddr;
9733         break;
9734       }
9735     }
9736   }
9737   Error Err = Error::success();
9738   for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
9739     uint64_t Flags = Entry.flags();
9740     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9741     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9742     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9743                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9744     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9745                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9746     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9747     if (ReExport)
9748       outs() << "[re-export] ";
9749     else
9750       outs() << format("0x%08llX  ",
9751                        Entry.address() + BaseSegmentAddress);
9752     outs() << Entry.name();
9753     if (WeakDef || ThreadLocal || Resolver || Abs) {
9754       bool NeedsComma = false;
9755       outs() << " [";
9756       if (WeakDef) {
9757         outs() << "weak_def";
9758         NeedsComma = true;
9759       }
9760       if (ThreadLocal) {
9761         if (NeedsComma)
9762           outs() << ", ";
9763         outs() << "per-thread";
9764         NeedsComma = true;
9765       }
9766       if (Abs) {
9767         if (NeedsComma)
9768           outs() << ", ";
9769         outs() << "absolute";
9770         NeedsComma = true;
9771       }
9772       if (Resolver) {
9773         if (NeedsComma)
9774           outs() << ", ";
9775         outs() << format("resolver=0x%08llX", Entry.other());
9776         NeedsComma = true;
9777       }
9778       outs() << "]";
9779     }
9780     if (ReExport) {
9781       StringRef DylibName = "unknown";
9782       int Ordinal = Entry.other() - 1;
9783       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9784       if (Entry.otherName().empty())
9785         outs() << " (from " << DylibName << ")";
9786       else
9787         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
9788     }
9789     outs() << "\n";
9790   }
9791   if (Err)
9792     report_error(Obj->getFileName(), std::move(Err));
9793 }
9794 
9795 //===----------------------------------------------------------------------===//
9796 // rebase table dumping
9797 //===----------------------------------------------------------------------===//
9798 
9799 void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
9800   outs() << "segment  section            address     type\n";
9801   Error Err = Error::success();
9802   for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9803     StringRef SegmentName = Entry.segmentName();
9804     StringRef SectionName = Entry.sectionName();
9805     uint64_t Address = Entry.address();
9806 
9807     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
9808     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
9809                      SegmentName.str().c_str(), SectionName.str().c_str(),
9810                      Address, Entry.typeName().str().c_str());
9811   }
9812   if (Err)
9813     report_error(Obj->getFileName(), std::move(Err));
9814 }
9815 
9816 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9817   StringRef DylibName;
9818   switch (Ordinal) {
9819   case MachO::BIND_SPECIAL_DYLIB_SELF:
9820     return "this-image";
9821   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9822     return "main-executable";
9823   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9824     return "flat-namespace";
9825   default:
9826     if (Ordinal > 0) {
9827       std::error_code EC =
9828           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
9829       if (EC)
9830         return "<<bad library ordinal>>";
9831       return DylibName;
9832     }
9833   }
9834   return "<<unknown special ordinal>>";
9835 }
9836 
9837 //===----------------------------------------------------------------------===//
9838 // bind table dumping
9839 //===----------------------------------------------------------------------===//
9840 
9841 void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
9842   // Build table of sections so names can used in final output.
9843   outs() << "segment  section            address    type       "
9844             "addend dylib            symbol\n";
9845   Error Err = Error::success();
9846   for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
9847     StringRef SegmentName = Entry.segmentName();
9848     StringRef SectionName = Entry.sectionName();
9849     uint64_t Address = Entry.address();
9850 
9851     // Table lines look like:
9852     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
9853     StringRef Attr;
9854     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
9855       Attr = " (weak_import)";
9856     outs() << left_justify(SegmentName, 8) << " "
9857            << left_justify(SectionName, 18) << " "
9858            << format_hex(Address, 10, true) << " "
9859            << left_justify(Entry.typeName(), 8) << " "
9860            << format_decimal(Entry.addend(), 8) << " "
9861            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
9862            << Entry.symbolName() << Attr << "\n";
9863   }
9864   if (Err)
9865     report_error(Obj->getFileName(), std::move(Err));
9866 }
9867 
9868 //===----------------------------------------------------------------------===//
9869 // lazy bind table dumping
9870 //===----------------------------------------------------------------------===//
9871 
9872 void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
9873   outs() << "segment  section            address     "
9874             "dylib            symbol\n";
9875   Error Err = Error::success();
9876   for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
9877     StringRef SegmentName = Entry.segmentName();
9878     StringRef SectionName = Entry.sectionName();
9879     uint64_t Address = Entry.address();
9880 
9881     // Table lines look like:
9882     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
9883     outs() << left_justify(SegmentName, 8) << " "
9884            << left_justify(SectionName, 18) << " "
9885            << format_hex(Address, 10, true) << " "
9886            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
9887            << Entry.symbolName() << "\n";
9888   }
9889   if (Err)
9890     report_error(Obj->getFileName(), std::move(Err));
9891 }
9892 
9893 //===----------------------------------------------------------------------===//
9894 // weak bind table dumping
9895 //===----------------------------------------------------------------------===//
9896 
9897 void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
9898   outs() << "segment  section            address     "
9899             "type       addend   symbol\n";
9900   Error Err = Error::success();
9901   for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
9902     // Strong symbols don't have a location to update.
9903     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
9904       outs() << "                                        strong              "
9905              << Entry.symbolName() << "\n";
9906       continue;
9907     }
9908     StringRef SegmentName = Entry.segmentName();
9909     StringRef SectionName = Entry.sectionName();
9910     uint64_t Address = Entry.address();
9911 
9912     // Table lines look like:
9913     // __DATA  __data  0x00001000  pointer    0   _foo
9914     outs() << left_justify(SegmentName, 8) << " "
9915            << left_justify(SectionName, 18) << " "
9916            << format_hex(Address, 10, true) << " "
9917            << left_justify(Entry.typeName(), 8) << " "
9918            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
9919            << "\n";
9920   }
9921   if (Err)
9922     report_error(Obj->getFileName(), std::move(Err));
9923 }
9924 
9925 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
9926 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9927 // information for that address. If the address is found its binding symbol
9928 // name is returned.  If not nullptr is returned.
9929 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9930                                                  struct DisassembleInfo *info) {
9931   if (info->bindtable == nullptr) {
9932     info->bindtable = llvm::make_unique<SymbolAddressMap>();
9933     Error Err = Error::success();
9934     for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
9935       uint64_t Address = Entry.address();
9936       StringRef name = Entry.symbolName();
9937       if (!name.empty())
9938         (*info->bindtable)[Address] = name;
9939     }
9940     if (Err)
9941       report_error(info->O->getFileName(), std::move(Err));
9942   }
9943   auto name = info->bindtable->lookup(ReferenceValue);
9944   return !name.empty() ? name.data() : nullptr;
9945 }
9946 
9947