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