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