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