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