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