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