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