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