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