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