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