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