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