For llvm-objdump, hook up existing options to work when using -macho (the Mach-O...
[oota-llvm.git] / tools / llvm-objdump / MachODump.cpp
1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the MachO-specific dumper for llvm-objdump.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm-objdump.h"
15 #include "llvm-c/Disassembler.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DIContext.h"
21 #include "llvm/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/MachO.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include <algorithm>
45 #include <cstring>
46 #include <system_error>
47
48 #if HAVE_CXXABI_H
49 #include <cxxabi.h>
50 #endif
51
52 using namespace llvm;
53 using namespace object;
54
55 static cl::opt<bool>
56     UseDbg("g",
57            cl::desc("Print line information from debug info if available"));
58
59 static cl::opt<std::string> DSYMFile("dsym",
60                                      cl::desc("Use .dSYM file for debug info"));
61
62 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
63                                      cl::desc("Print full leading address"));
64
65 static cl::opt<bool>
66     PrintImmHex("print-imm-hex",
67                 cl::desc("Use hex format for immediate values"));
68
69 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
70                                      cl::desc("Print Mach-O universal headers "
71                                               "(requires -macho)"));
72
73 cl::opt<bool>
74     llvm::ArchiveHeaders("archive-headers",
75                          cl::desc("Print archive headers for Mach-O archives "
76                                   "(requires -macho)"));
77
78 static cl::list<std::string>
79     ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
80               cl::ZeroOrMore);
81 bool ArchAll = false;
82
83 static std::string ThumbTripleName;
84
85 static const Target *GetTarget(const MachOObjectFile *MachOObj,
86                                const char **McpuDefault,
87                                const Target **ThumbTarget) {
88   // Figure out the target triple.
89   if (TripleName.empty()) {
90     llvm::Triple TT("unknown-unknown-unknown");
91     llvm::Triple ThumbTriple = Triple();
92     TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
93     TripleName = TT.str();
94     ThumbTripleName = ThumbTriple.str();
95   }
96
97   // Get the target specific parser.
98   std::string Error;
99   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
100   if (TheTarget && ThumbTripleName.empty())
101     return TheTarget;
102
103   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
104   if (*ThumbTarget)
105     return TheTarget;
106
107   errs() << "llvm-objdump: error: unable to get target for '";
108   if (!TheTarget)
109     errs() << TripleName;
110   else
111     errs() << ThumbTripleName;
112   errs() << "', see --version and --triple.\n";
113   return nullptr;
114 }
115
116 struct SymbolSorter {
117   bool operator()(const SymbolRef &A, const SymbolRef &B) {
118     SymbolRef::Type AType, BType;
119     A.getType(AType);
120     B.getType(BType);
121
122     uint64_t AAddr, BAddr;
123     if (AType != SymbolRef::ST_Function)
124       AAddr = 0;
125     else
126       A.getAddress(AAddr);
127     if (BType != SymbolRef::ST_Function)
128       BAddr = 0;
129     else
130       B.getAddress(BAddr);
131     return AAddr < BAddr;
132   }
133 };
134
135 // Types for the storted data in code table that is built before disassembly
136 // and the predicate function to sort them.
137 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
138 typedef std::vector<DiceTableEntry> DiceTable;
139 typedef DiceTable::iterator dice_table_iterator;
140
141 // This is used to search for a data in code table entry for the PC being
142 // disassembled.  The j parameter has the PC in j.first.  A single data in code
143 // table entry can cover many bytes for each of its Kind's.  So if the offset,
144 // aka the i.first value, of the data in code table entry plus its Length
145 // covers the PC being searched for this will return true.  If not it will
146 // return false.
147 static bool compareDiceTableEntries(const DiceTableEntry &i,
148                                     const DiceTableEntry &j) {
149   uint16_t Length;
150   i.second.getLength(Length);
151
152   return j.first >= i.first && j.first < i.first + Length;
153 }
154
155 static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
156                                unsigned short Kind) {
157   uint32_t Value, Size = 1;
158
159   switch (Kind) {
160   default:
161   case MachO::DICE_KIND_DATA:
162     if (Length >= 4) {
163       if (!NoShowRawInsn)
164         DumpBytes(StringRef(bytes, 4));
165       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
166       outs() << "\t.long " << Value;
167       Size = 4;
168     } else if (Length >= 2) {
169       if (!NoShowRawInsn)
170         DumpBytes(StringRef(bytes, 2));
171       Value = bytes[1] << 8 | bytes[0];
172       outs() << "\t.short " << Value;
173       Size = 2;
174     } else {
175       if (!NoShowRawInsn)
176         DumpBytes(StringRef(bytes, 2));
177       Value = bytes[0];
178       outs() << "\t.byte " << Value;
179       Size = 1;
180     }
181     if (Kind == MachO::DICE_KIND_DATA)
182       outs() << "\t@ KIND_DATA\n";
183     else
184       outs() << "\t@ data in code kind = " << Kind << "\n";
185     break;
186   case MachO::DICE_KIND_JUMP_TABLE8:
187     if (!NoShowRawInsn)
188       DumpBytes(StringRef(bytes, 1));
189     Value = bytes[0];
190     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
191     Size = 1;
192     break;
193   case MachO::DICE_KIND_JUMP_TABLE16:
194     if (!NoShowRawInsn)
195       DumpBytes(StringRef(bytes, 2));
196     Value = bytes[1] << 8 | bytes[0];
197     outs() << "\t.short " << format("%5u", Value & 0xffff)
198            << "\t@ KIND_JUMP_TABLE16\n";
199     Size = 2;
200     break;
201   case MachO::DICE_KIND_JUMP_TABLE32:
202   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
203     if (!NoShowRawInsn)
204       DumpBytes(StringRef(bytes, 4));
205     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
206     outs() << "\t.long " << Value;
207     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
208       outs() << "\t@ KIND_JUMP_TABLE32\n";
209     else
210       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
211     Size = 4;
212     break;
213   }
214   return Size;
215 }
216
217 static void getSectionsAndSymbols(const MachO::mach_header Header,
218                                   MachOObjectFile *MachOObj,
219                                   std::vector<SectionRef> &Sections,
220                                   std::vector<SymbolRef> &Symbols,
221                                   SmallVectorImpl<uint64_t> &FoundFns,
222                                   uint64_t &BaseSegmentAddress) {
223   for (const SymbolRef &Symbol : MachOObj->symbols()) {
224     StringRef SymName;
225     Symbol.getName(SymName);
226     if (!SymName.startswith("ltmp"))
227       Symbols.push_back(Symbol);
228   }
229
230   for (const SectionRef &Section : MachOObj->sections()) {
231     StringRef SectName;
232     Section.getName(SectName);
233     Sections.push_back(Section);
234   }
235
236   MachOObjectFile::LoadCommandInfo Command =
237       MachOObj->getFirstLoadCommandInfo();
238   bool BaseSegmentAddressSet = false;
239   for (unsigned i = 0;; ++i) {
240     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
241       // We found a function starts segment, parse the addresses for later
242       // consumption.
243       MachO::linkedit_data_command LLC =
244           MachOObj->getLinkeditDataLoadCommand(Command);
245
246       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
247     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
248       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
249       StringRef SegName = SLC.segname;
250       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
251         BaseSegmentAddressSet = true;
252         BaseSegmentAddress = SLC.vmaddr;
253       }
254     }
255
256     if (i == Header.ncmds - 1)
257       break;
258     else
259       Command = MachOObj->getNextLoadCommandInfo(Command);
260   }
261 }
262
263 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
264 // and if it is and there is a list of architecture flags is specified then
265 // check to make sure this Mach-O file is one of those architectures or all
266 // architectures were specified.  If not then an error is generated and this
267 // routine returns false.  Else it returns true.
268 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
269   if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
270     MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
271     bool ArchFound = false;
272     MachO::mach_header H;
273     MachO::mach_header_64 H_64;
274     Triple T;
275     if (MachO->is64Bit()) {
276       H_64 = MachO->MachOObjectFile::getHeader64();
277       T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
278     } else {
279       H = MachO->MachOObjectFile::getHeader();
280       T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
281     }
282     unsigned i;
283     for (i = 0; i < ArchFlags.size(); ++i) {
284       if (ArchFlags[i] == T.getArchName())
285         ArchFound = true;
286       break;
287     }
288     if (!ArchFound) {
289       errs() << "llvm-objdump: file: " + Filename + " does not contain "
290              << "architecture: " + ArchFlags[i] + "\n";
291       return false;
292     }
293   }
294   return true;
295 }
296
297 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF);
298
299 // ProcessMachO() is passed a single opened Mach-O file, which may be an
300 // archive member and or in a slice of a universal file.  It prints the
301 // the file name and header info and then processes it according to the
302 // command line options.
303 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
304                          StringRef ArchiveMemberName = StringRef(),
305                          StringRef ArchitectureName = StringRef()) {
306   // If we are doing some processing here on the Mach-O file print the header
307   // info.  And don't print it otherwise like in the case of printing the
308   // UniversalHeaders.
309   if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
310       LazyBind || WeakBind) {
311     outs() << Filename;
312     if (!ArchiveMemberName.empty())
313       outs() << '(' << ArchiveMemberName << ')';
314     if (!ArchitectureName.empty())
315       outs() << " (architecture " << ArchitectureName << ")";
316     outs() << ":\n";
317   }
318
319   if (Disassemble)
320     DisassembleMachO(Filename, MachOOF);
321   if (Relocations)
322     PrintRelocations(MachOOF);
323   if (SectionHeaders)
324     PrintSectionHeaders(MachOOF);
325   if (SectionContents)
326     PrintSectionContents(MachOOF);
327   if (SymbolTable)
328     PrintSymbolTable(MachOOF);
329   if (UnwindInfo)
330     printMachOUnwindInfo(MachOOF);
331   if (PrivateHeaders)
332     printMachOFileHeader(MachOOF);
333   if (ExportsTrie)
334     printExportsTrie(MachOOF);
335   if (Rebase)
336     printRebaseTable(MachOOF);
337   if (Bind)
338     printBindTable(MachOOF);
339   if (LazyBind)
340     printLazyBindTable(MachOOF);
341   if (WeakBind)
342     printWeakBindTable(MachOOF);
343 }
344
345 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
346 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
347   outs() << "    cputype (" << cputype << ")\n";
348   outs() << "    cpusubtype (" << cpusubtype << ")\n";
349 }
350
351 // printCPUType() helps print_fat_headers by printing the cputype and
352 // pusubtype (symbolically for the one's it knows about).
353 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
354   switch (cputype) {
355   case MachO::CPU_TYPE_I386:
356     switch (cpusubtype) {
357     case MachO::CPU_SUBTYPE_I386_ALL:
358       outs() << "    cputype CPU_TYPE_I386\n";
359       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
360       break;
361     default:
362       printUnknownCPUType(cputype, cpusubtype);
363       break;
364     }
365     break;
366   case MachO::CPU_TYPE_X86_64:
367     switch (cpusubtype) {
368     case MachO::CPU_SUBTYPE_X86_64_ALL:
369       outs() << "    cputype CPU_TYPE_X86_64\n";
370       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
371       break;
372     case MachO::CPU_SUBTYPE_X86_64_H:
373       outs() << "    cputype CPU_TYPE_X86_64\n";
374       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
375       break;
376     default:
377       printUnknownCPUType(cputype, cpusubtype);
378       break;
379     }
380     break;
381   case MachO::CPU_TYPE_ARM:
382     switch (cpusubtype) {
383     case MachO::CPU_SUBTYPE_ARM_ALL:
384       outs() << "    cputype CPU_TYPE_ARM\n";
385       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
386       break;
387     case MachO::CPU_SUBTYPE_ARM_V4T:
388       outs() << "    cputype CPU_TYPE_ARM\n";
389       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
390       break;
391     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
392       outs() << "    cputype CPU_TYPE_ARM\n";
393       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
394       break;
395     case MachO::CPU_SUBTYPE_ARM_XSCALE:
396       outs() << "    cputype CPU_TYPE_ARM\n";
397       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
398       break;
399     case MachO::CPU_SUBTYPE_ARM_V6:
400       outs() << "    cputype CPU_TYPE_ARM\n";
401       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
402       break;
403     case MachO::CPU_SUBTYPE_ARM_V6M:
404       outs() << "    cputype CPU_TYPE_ARM\n";
405       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
406       break;
407     case MachO::CPU_SUBTYPE_ARM_V7:
408       outs() << "    cputype CPU_TYPE_ARM\n";
409       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
410       break;
411     case MachO::CPU_SUBTYPE_ARM_V7EM:
412       outs() << "    cputype CPU_TYPE_ARM\n";
413       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
414       break;
415     case MachO::CPU_SUBTYPE_ARM_V7K:
416       outs() << "    cputype CPU_TYPE_ARM\n";
417       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
418       break;
419     case MachO::CPU_SUBTYPE_ARM_V7M:
420       outs() << "    cputype CPU_TYPE_ARM\n";
421       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
422       break;
423     case MachO::CPU_SUBTYPE_ARM_V7S:
424       outs() << "    cputype CPU_TYPE_ARM\n";
425       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
426       break;
427     default:
428       printUnknownCPUType(cputype, cpusubtype);
429       break;
430     }
431     break;
432   case MachO::CPU_TYPE_ARM64:
433     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
434     case MachO::CPU_SUBTYPE_ARM64_ALL:
435       outs() << "    cputype CPU_TYPE_ARM64\n";
436       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
437       break;
438     default:
439       printUnknownCPUType(cputype, cpusubtype);
440       break;
441     }
442     break;
443   default:
444     printUnknownCPUType(cputype, cpusubtype);
445     break;
446   }
447 }
448
449 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
450                                        bool verbose) {
451   outs() << "Fat headers\n";
452   if (verbose)
453     outs() << "fat_magic FAT_MAGIC\n";
454   else
455     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
456
457   uint32_t nfat_arch = UB->getNumberOfObjects();
458   StringRef Buf = UB->getData();
459   uint64_t size = Buf.size();
460   uint64_t big_size = sizeof(struct MachO::fat_header) +
461                       nfat_arch * sizeof(struct MachO::fat_arch);
462   outs() << "nfat_arch " << UB->getNumberOfObjects();
463   if (nfat_arch == 0)
464     outs() << " (malformed, contains zero architecture types)\n";
465   else if (big_size > size)
466     outs() << " (malformed, architectures past end of file)\n";
467   else
468     outs() << "\n";
469
470   for (uint32_t i = 0; i < nfat_arch; ++i) {
471     MachOUniversalBinary::ObjectForArch OFA(UB, i);
472     uint32_t cputype = OFA.getCPUType();
473     uint32_t cpusubtype = OFA.getCPUSubType();
474     outs() << "architecture ";
475     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
476       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
477       uint32_t other_cputype = other_OFA.getCPUType();
478       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
479       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
480           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
481               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
482         outs() << "(illegal duplicate architecture) ";
483         break;
484       }
485     }
486     if (verbose) {
487       outs() << OFA.getArchTypeName() << "\n";
488       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
489     } else {
490       outs() << i << "\n";
491       outs() << "    cputype " << cputype << "\n";
492       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
493              << "\n";
494     }
495     if (verbose &&
496         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
497       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
498     else
499       outs() << "    capabilities "
500              << format("0x%" PRIx32,
501                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
502     outs() << "    offset " << OFA.getOffset();
503     if (OFA.getOffset() > size)
504       outs() << " (past end of file)";
505     if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
506       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
507     outs() << "\n";
508     outs() << "    size " << OFA.getSize();
509     big_size = OFA.getOffset() + OFA.getSize();
510     if (big_size > size)
511       outs() << " (past end of file)";
512     outs() << "\n";
513     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
514            << ")\n";
515   }
516 }
517
518 static void printArchiveChild(Archive::Child &C, bool verbose,
519                               bool print_offset) {
520   if (print_offset)
521     outs() << C.getChildOffset() << "\t";
522   sys::fs::perms Mode = C.getAccessMode();
523   if (verbose) {
524     // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
525     // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
526     outs() << "-";
527     if (Mode & sys::fs::owner_read)
528       outs() << "r";
529     else
530       outs() << "-";
531     if (Mode & sys::fs::owner_write)
532       outs() << "w";
533     else
534       outs() << "-";
535     if (Mode & sys::fs::owner_exe)
536       outs() << "x";
537     else
538       outs() << "-";
539     if (Mode & sys::fs::group_read)
540       outs() << "r";
541     else
542       outs() << "-";
543     if (Mode & sys::fs::group_write)
544       outs() << "w";
545     else
546       outs() << "-";
547     if (Mode & sys::fs::group_exe)
548       outs() << "x";
549     else
550       outs() << "-";
551     if (Mode & sys::fs::others_read)
552       outs() << "r";
553     else
554       outs() << "-";
555     if (Mode & sys::fs::others_write)
556       outs() << "w";
557     else
558       outs() << "-";
559     if (Mode & sys::fs::others_exe)
560       outs() << "x";
561     else
562       outs() << "-";
563   } else {
564     outs() << format("0%o ", Mode);
565   }
566
567   unsigned UID = C.getUID();
568   outs() << format("%3d/", UID);
569   unsigned GID = C.getGID();
570   outs() << format("%-3d ", GID);
571   uint64_t Size = C.getRawSize();
572   outs() << format("%5d ", Size);
573
574   StringRef RawLastModified = C.getRawLastModified();
575   if (verbose) {
576     unsigned Seconds;
577     if (RawLastModified.getAsInteger(10, Seconds))
578       outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
579     else {
580       // Since cime(3) returns a 26 character string of the form:
581       // "Sun Sep 16 01:03:52 1973\n\0"
582       // just print 24 characters.
583       time_t t = Seconds;
584       outs() << format("%.24s ", ctime(&t));
585     }
586   } else {
587     outs() << RawLastModified << " ";
588   }
589
590   if (verbose) {
591     ErrorOr<StringRef> NameOrErr = C.getName();
592     if (NameOrErr.getError()) {
593       StringRef RawName = C.getRawName();
594       outs() << RawName << "\n";
595     } else {
596       StringRef Name = NameOrErr.get();
597       outs() << Name << "\n";
598     }
599   } else {
600     StringRef RawName = C.getRawName();
601     outs() << RawName << "\n";
602   }
603 }
604
605 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
606   if (A->hasSymbolTable()) {
607     Archive::child_iterator S = A->getSymbolTableChild();
608     Archive::Child C = *S;
609     printArchiveChild(C, verbose, print_offset);
610   }
611   for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
612        ++I) {
613     Archive::Child C = *I;
614     printArchiveChild(C, verbose, print_offset);
615   }
616 }
617
618 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
619 // -arch flags selecting just those slices as specified by them and also parses
620 // archive files.  Then for each individual Mach-O file ProcessMachO() is
621 // called to process the file based on the command line options.
622 void llvm::ParseInputMachO(StringRef Filename) {
623   // Check for -arch all and verifiy the -arch flags are valid.
624   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
625     if (ArchFlags[i] == "all") {
626       ArchAll = true;
627     } else {
628       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
629         errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
630                       "'for the -arch option\n";
631         return;
632       }
633     }
634   }
635
636   // Attempt to open the binary.
637   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
638   if (std::error_code EC = BinaryOrErr.getError()) {
639     errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
640     return;
641   }
642   Binary &Bin = *BinaryOrErr.get().getBinary();
643
644   if (Archive *A = dyn_cast<Archive>(&Bin)) {
645     outs() << "Archive : " << Filename << "\n";
646     if (ArchiveHeaders)
647       printArchiveHeaders(A, true, false);
648     for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
649          I != E; ++I) {
650       ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
651       if (ChildOrErr.getError())
652         continue;
653       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
654         if (!checkMachOAndArchFlags(O, Filename))
655           return;
656         ProcessMachO(Filename, O, O->getFileName());
657       }
658     }
659     return;
660   }
661   if (UniversalHeaders) {
662     if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
663       printMachOUniversalHeaders(UB, true);
664   }
665   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
666     // If we have a list of architecture flags specified dump only those.
667     if (!ArchAll && ArchFlags.size() != 0) {
668       // Look for a slice in the universal binary that matches each ArchFlag.
669       bool ArchFound;
670       for (unsigned i = 0; i < ArchFlags.size(); ++i) {
671         ArchFound = false;
672         for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
673                                                    E = UB->end_objects();
674              I != E; ++I) {
675           if (ArchFlags[i] == I->getArchTypeName()) {
676             ArchFound = true;
677             ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
678                 I->getAsObjectFile();
679             std::string ArchitectureName = "";
680             if (ArchFlags.size() > 1)
681               ArchitectureName = I->getArchTypeName();
682             if (ObjOrErr) {
683               ObjectFile &O = *ObjOrErr.get();
684               if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
685                 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
686             } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
687                            I->getAsArchive()) {
688               std::unique_ptr<Archive> &A = *AOrErr;
689               outs() << "Archive : " << Filename;
690               if (!ArchitectureName.empty())
691                 outs() << " (architecture " << ArchitectureName << ")";
692               outs() << "\n";
693               if (ArchiveHeaders)
694                 printArchiveHeaders(A.get(), true, false);
695               for (Archive::child_iterator AI = A->child_begin(),
696                                            AE = A->child_end();
697                    AI != AE; ++AI) {
698                 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
699                 if (ChildOrErr.getError())
700                   continue;
701                 if (MachOObjectFile *O =
702                         dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
703                   ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
704               }
705             }
706           }
707         }
708         if (!ArchFound) {
709           errs() << "llvm-objdump: file: " + Filename + " does not contain "
710                  << "architecture: " + ArchFlags[i] + "\n";
711           return;
712         }
713       }
714       return;
715     }
716     // No architecture flags were specified so if this contains a slice that
717     // matches the host architecture dump only that.
718     if (!ArchAll) {
719       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
720                                                  E = UB->end_objects();
721            I != E; ++I) {
722         if (MachOObjectFile::getHostArch().getArchName() ==
723             I->getArchTypeName()) {
724           ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
725           std::string ArchiveName;
726           ArchiveName.clear();
727           if (ObjOrErr) {
728             ObjectFile &O = *ObjOrErr.get();
729             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
730               ProcessMachO(Filename, MachOOF);
731           } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
732                          I->getAsArchive()) {
733             std::unique_ptr<Archive> &A = *AOrErr;
734             outs() << "Archive : " << Filename << "\n";
735             if (ArchiveHeaders)
736               printArchiveHeaders(A.get(), true, false);
737             for (Archive::child_iterator AI = A->child_begin(),
738                                          AE = A->child_end();
739                  AI != AE; ++AI) {
740               ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
741               if (ChildOrErr.getError())
742                 continue;
743               if (MachOObjectFile *O =
744                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
745                 ProcessMachO(Filename, O, O->getFileName());
746             }
747           }
748           return;
749         }
750       }
751     }
752     // Either all architectures have been specified or none have been specified
753     // and this does not contain the host architecture so dump all the slices.
754     bool moreThanOneArch = UB->getNumberOfObjects() > 1;
755     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
756                                                E = UB->end_objects();
757          I != E; ++I) {
758       ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
759       std::string ArchitectureName = "";
760       if (moreThanOneArch)
761         ArchitectureName = I->getArchTypeName();
762       if (ObjOrErr) {
763         ObjectFile &Obj = *ObjOrErr.get();
764         if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
765           ProcessMachO(Filename, MachOOF, "", ArchitectureName);
766       } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
767         std::unique_ptr<Archive> &A = *AOrErr;
768         outs() << "Archive : " << Filename;
769         if (!ArchitectureName.empty())
770           outs() << " (architecture " << ArchitectureName << ")";
771         outs() << "\n";
772         if (ArchiveHeaders)
773           printArchiveHeaders(A.get(), true, false);
774         for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
775              AI != AE; ++AI) {
776           ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
777           if (ChildOrErr.getError())
778             continue;
779           if (MachOObjectFile *O =
780                   dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
781             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
782               ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
783                            ArchitectureName);
784           }
785         }
786       }
787     }
788     return;
789   }
790   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
791     if (!checkMachOAndArchFlags(O, Filename))
792       return;
793     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
794       ProcessMachO(Filename, MachOOF);
795     } else
796       errs() << "llvm-objdump: '" << Filename << "': "
797              << "Object is not a Mach-O file type.\n";
798   } else
799     errs() << "llvm-objdump: '" << Filename << "': "
800            << "Unrecognized file type.\n";
801 }
802
803 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
804 typedef std::pair<uint64_t, const char *> BindInfoEntry;
805 typedef std::vector<BindInfoEntry> BindTable;
806 typedef BindTable::iterator bind_table_iterator;
807
808 // The block of info used by the Symbolizer call backs.
809 struct DisassembleInfo {
810   bool verbose;
811   MachOObjectFile *O;
812   SectionRef S;
813   SymbolAddressMap *AddrMap;
814   std::vector<SectionRef> *Sections;
815   const char *class_name;
816   const char *selector_name;
817   char *method;
818   char *demangled_name;
819   uint64_t adrp_addr;
820   uint32_t adrp_inst;
821   BindTable *bindtable;
822 };
823
824 // GuessSymbolName is passed the address of what might be a symbol and a
825 // pointer to the DisassembleInfo struct.  It returns the name of a symbol
826 // with that address or nullptr if no symbol is found with that address.
827 static const char *GuessSymbolName(uint64_t value,
828                                    struct DisassembleInfo *info) {
829   const char *SymbolName = nullptr;
830   // A DenseMap can't lookup up some values.
831   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
832     StringRef name = info->AddrMap->lookup(value);
833     if (!name.empty())
834       SymbolName = name.data();
835   }
836   return SymbolName;
837 }
838
839 // SymbolizerGetOpInfo() is the operand information call back function.
840 // This is called to get the symbolic information for operand(s) of an
841 // instruction when it is being done.  This routine does this from
842 // the relocation information, symbol table, etc. That block of information
843 // is a pointer to the struct DisassembleInfo that was passed when the
844 // disassembler context was created and passed to back to here when
845 // called back by the disassembler for instruction operands that could have
846 // relocation information. The address of the instruction containing operand is
847 // at the Pc parameter.  The immediate value the operand has is passed in
848 // op_info->Value and is at Offset past the start of the instruction and has a
849 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
850 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
851 // names and addends of the symbolic expression to add for the operand.  The
852 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
853 // information is returned then this function returns 1 else it returns 0.
854 int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
855                         uint64_t Size, int TagType, void *TagBuf) {
856   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
857   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
858   uint64_t value = op_info->Value;
859
860   // Make sure all fields returned are zero if we don't set them.
861   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
862   op_info->Value = value;
863
864   // If the TagType is not the value 1 which it code knows about or if no
865   // verbose symbolic information is wanted then just return 0, indicating no
866   // information is being returned.
867   if (TagType != 1 || info->verbose == false)
868     return 0;
869
870   unsigned int Arch = info->O->getArch();
871   if (Arch == Triple::x86) {
872     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
873       return 0;
874     // First search the section's relocation entries (if any) for an entry
875     // for this section offset.
876     uint32_t sect_addr = info->S.getAddress();
877     uint32_t sect_offset = (Pc + Offset) - sect_addr;
878     bool reloc_found = false;
879     DataRefImpl Rel;
880     MachO::any_relocation_info RE;
881     bool isExtern = false;
882     SymbolRef Symbol;
883     bool r_scattered = false;
884     uint32_t r_value, pair_r_value, r_type;
885     for (const RelocationRef &Reloc : info->S.relocations()) {
886       uint64_t RelocOffset;
887       Reloc.getOffset(RelocOffset);
888       if (RelocOffset == sect_offset) {
889         Rel = Reloc.getRawDataRefImpl();
890         RE = info->O->getRelocation(Rel);
891         r_type = info->O->getAnyRelocationType(RE);
892         r_scattered = info->O->isRelocationScattered(RE);
893         if (r_scattered) {
894           r_value = info->O->getScatteredRelocationValue(RE);
895           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
896               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
897             DataRefImpl RelNext = Rel;
898             info->O->moveRelocationNext(RelNext);
899             MachO::any_relocation_info RENext;
900             RENext = info->O->getRelocation(RelNext);
901             if (info->O->isRelocationScattered(RENext))
902               pair_r_value = info->O->getScatteredRelocationValue(RENext);
903             else
904               return 0;
905           }
906         } else {
907           isExtern = info->O->getPlainRelocationExternal(RE);
908           if (isExtern) {
909             symbol_iterator RelocSym = Reloc.getSymbol();
910             Symbol = *RelocSym;
911           }
912         }
913         reloc_found = true;
914         break;
915       }
916     }
917     if (reloc_found && isExtern) {
918       StringRef SymName;
919       Symbol.getName(SymName);
920       const char *name = SymName.data();
921       op_info->AddSymbol.Present = 1;
922       op_info->AddSymbol.Name = name;
923       // For i386 extern relocation entries the value in the instruction is
924       // the offset from the symbol, and value is already set in op_info->Value.
925       return 1;
926     }
927     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
928                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
929       const char *add = GuessSymbolName(r_value, info);
930       const char *sub = GuessSymbolName(pair_r_value, info);
931       uint32_t offset = value - (r_value - pair_r_value);
932       op_info->AddSymbol.Present = 1;
933       if (add != nullptr)
934         op_info->AddSymbol.Name = add;
935       else
936         op_info->AddSymbol.Value = r_value;
937       op_info->SubtractSymbol.Present = 1;
938       if (sub != nullptr)
939         op_info->SubtractSymbol.Name = sub;
940       else
941         op_info->SubtractSymbol.Value = pair_r_value;
942       op_info->Value = offset;
943       return 1;
944     }
945     // TODO:
946     // Second search the external relocation entries of a fully linked image
947     // (if any) for an entry that matches this segment offset.
948     // uint32_t seg_offset = (Pc + Offset);
949     return 0;
950   } else if (Arch == Triple::x86_64) {
951     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
952       return 0;
953     // First search the section's relocation entries (if any) for an entry
954     // for this section offset.
955     uint64_t sect_addr = info->S.getAddress();
956     uint64_t sect_offset = (Pc + Offset) - sect_addr;
957     bool reloc_found = false;
958     DataRefImpl Rel;
959     MachO::any_relocation_info RE;
960     bool isExtern = false;
961     SymbolRef Symbol;
962     for (const RelocationRef &Reloc : info->S.relocations()) {
963       uint64_t RelocOffset;
964       Reloc.getOffset(RelocOffset);
965       if (RelocOffset == sect_offset) {
966         Rel = Reloc.getRawDataRefImpl();
967         RE = info->O->getRelocation(Rel);
968         // NOTE: Scattered relocations don't exist on x86_64.
969         isExtern = info->O->getPlainRelocationExternal(RE);
970         if (isExtern) {
971           symbol_iterator RelocSym = Reloc.getSymbol();
972           Symbol = *RelocSym;
973         }
974         reloc_found = true;
975         break;
976       }
977     }
978     if (reloc_found && isExtern) {
979       // The Value passed in will be adjusted by the Pc if the instruction
980       // adds the Pc.  But for x86_64 external relocation entries the Value
981       // is the offset from the external symbol.
982       if (info->O->getAnyRelocationPCRel(RE))
983         op_info->Value -= Pc + Offset + Size;
984       StringRef SymName;
985       Symbol.getName(SymName);
986       const char *name = SymName.data();
987       unsigned Type = info->O->getAnyRelocationType(RE);
988       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
989         DataRefImpl RelNext = Rel;
990         info->O->moveRelocationNext(RelNext);
991         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
992         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
993         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
994         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
995         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
996           op_info->SubtractSymbol.Present = 1;
997           op_info->SubtractSymbol.Name = name;
998           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
999           Symbol = *RelocSymNext;
1000           StringRef SymNameNext;
1001           Symbol.getName(SymNameNext);
1002           name = SymNameNext.data();
1003         }
1004       }
1005       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1006       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1007       op_info->AddSymbol.Present = 1;
1008       op_info->AddSymbol.Name = name;
1009       return 1;
1010     }
1011     // TODO:
1012     // Second search the external relocation entries of a fully linked image
1013     // (if any) for an entry that matches this segment offset.
1014     // uint64_t seg_offset = (Pc + Offset);
1015     return 0;
1016   } else if (Arch == Triple::arm) {
1017     if (Offset != 0 || (Size != 4 && Size != 2))
1018       return 0;
1019     // First search the section's relocation entries (if any) for an entry
1020     // for this section offset.
1021     uint32_t sect_addr = info->S.getAddress();
1022     uint32_t sect_offset = (Pc + Offset) - sect_addr;
1023     bool reloc_found = false;
1024     DataRefImpl Rel;
1025     MachO::any_relocation_info RE;
1026     bool isExtern = false;
1027     SymbolRef Symbol;
1028     bool r_scattered = false;
1029     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1030     for (const RelocationRef &Reloc : info->S.relocations()) {
1031       uint64_t RelocOffset;
1032       Reloc.getOffset(RelocOffset);
1033       if (RelocOffset == sect_offset) {
1034         Rel = Reloc.getRawDataRefImpl();
1035         RE = info->O->getRelocation(Rel);
1036         r_length = info->O->getAnyRelocationLength(RE);
1037         r_scattered = info->O->isRelocationScattered(RE);
1038         if (r_scattered) {
1039           r_value = info->O->getScatteredRelocationValue(RE);
1040           r_type = info->O->getScatteredRelocationType(RE);
1041         } else {
1042           r_type = info->O->getAnyRelocationType(RE);
1043           isExtern = info->O->getPlainRelocationExternal(RE);
1044           if (isExtern) {
1045             symbol_iterator RelocSym = Reloc.getSymbol();
1046             Symbol = *RelocSym;
1047           }
1048         }
1049         if (r_type == MachO::ARM_RELOC_HALF ||
1050             r_type == MachO::ARM_RELOC_SECTDIFF ||
1051             r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1052             r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1053           DataRefImpl RelNext = Rel;
1054           info->O->moveRelocationNext(RelNext);
1055           MachO::any_relocation_info RENext;
1056           RENext = info->O->getRelocation(RelNext);
1057           other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1058           if (info->O->isRelocationScattered(RENext))
1059             pair_r_value = info->O->getScatteredRelocationValue(RENext);
1060         }
1061         reloc_found = true;
1062         break;
1063       }
1064     }
1065     if (reloc_found && isExtern) {
1066       StringRef SymName;
1067       Symbol.getName(SymName);
1068       const char *name = SymName.data();
1069       op_info->AddSymbol.Present = 1;
1070       op_info->AddSymbol.Name = name;
1071       if (value != 0) {
1072         switch (r_type) {
1073         case MachO::ARM_RELOC_HALF:
1074           if ((r_length & 0x1) == 1) {
1075             op_info->Value = value << 16 | other_half;
1076             op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1077           } else {
1078             op_info->Value = other_half << 16 | value;
1079             op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1080           }
1081           break;
1082         default:
1083           break;
1084         }
1085       } else {
1086         switch (r_type) {
1087         case MachO::ARM_RELOC_HALF:
1088           if ((r_length & 0x1) == 1) {
1089             op_info->Value = value << 16 | other_half;
1090             op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1091           } else {
1092             op_info->Value = other_half << 16 | value;
1093             op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1094           }
1095           break;
1096         default:
1097           break;
1098         }
1099       }
1100       return 1;
1101     }
1102     // If we have a branch that is not an external relocation entry then
1103     // return 0 so the code in tryAddingSymbolicOperand() can use the
1104     // SymbolLookUp call back with the branch target address to look up the
1105     // symbol and possiblity add an annotation for a symbol stub.
1106     if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1107                                          r_type == MachO::ARM_THUMB_RELOC_BR22))
1108       return 0;
1109
1110     uint32_t offset = 0;
1111     if (reloc_found) {
1112       if (r_type == MachO::ARM_RELOC_HALF ||
1113           r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1114         if ((r_length & 0x1) == 1)
1115           value = value << 16 | other_half;
1116         else
1117           value = other_half << 16 | value;
1118       }
1119       if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1120                           r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1121         offset = value - r_value;
1122         value = r_value;
1123       }
1124     }
1125
1126     if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1127       if ((r_length & 0x1) == 1)
1128         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1129       else
1130         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1131       const char *add = GuessSymbolName(r_value, info);
1132       const char *sub = GuessSymbolName(pair_r_value, info);
1133       int32_t offset = value - (r_value - pair_r_value);
1134       op_info->AddSymbol.Present = 1;
1135       if (add != nullptr)
1136         op_info->AddSymbol.Name = add;
1137       else
1138         op_info->AddSymbol.Value = r_value;
1139       op_info->SubtractSymbol.Present = 1;
1140       if (sub != nullptr)
1141         op_info->SubtractSymbol.Name = sub;
1142       else
1143         op_info->SubtractSymbol.Value = pair_r_value;
1144       op_info->Value = offset;
1145       return 1;
1146     }
1147
1148     if (reloc_found == false)
1149       return 0;
1150
1151     op_info->AddSymbol.Present = 1;
1152     op_info->Value = offset;
1153     if (reloc_found) {
1154       if (r_type == MachO::ARM_RELOC_HALF) {
1155         if ((r_length & 0x1) == 1)
1156           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1157         else
1158           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1159       }
1160     }
1161     const char *add = GuessSymbolName(value, info);
1162     if (add != nullptr) {
1163       op_info->AddSymbol.Name = add;
1164       return 1;
1165     }
1166     op_info->AddSymbol.Value = value;
1167     return 1;
1168   } else if (Arch == Triple::aarch64) {
1169     if (Offset != 0 || Size != 4)
1170       return 0;
1171     // First search the section's relocation entries (if any) for an entry
1172     // for this section offset.
1173     uint64_t sect_addr = info->S.getAddress();
1174     uint64_t sect_offset = (Pc + Offset) - sect_addr;
1175     bool reloc_found = false;
1176     DataRefImpl Rel;
1177     MachO::any_relocation_info RE;
1178     bool isExtern = false;
1179     SymbolRef Symbol;
1180     uint32_t r_type = 0;
1181     for (const RelocationRef &Reloc : info->S.relocations()) {
1182       uint64_t RelocOffset;
1183       Reloc.getOffset(RelocOffset);
1184       if (RelocOffset == sect_offset) {
1185         Rel = Reloc.getRawDataRefImpl();
1186         RE = info->O->getRelocation(Rel);
1187         r_type = info->O->getAnyRelocationType(RE);
1188         if (r_type == MachO::ARM64_RELOC_ADDEND) {
1189           DataRefImpl RelNext = Rel;
1190           info->O->moveRelocationNext(RelNext);
1191           MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1192           if (value == 0) {
1193             value = info->O->getPlainRelocationSymbolNum(RENext);
1194             op_info->Value = value;
1195           }
1196         }
1197         // NOTE: Scattered relocations don't exist on arm64.
1198         isExtern = info->O->getPlainRelocationExternal(RE);
1199         if (isExtern) {
1200           symbol_iterator RelocSym = Reloc.getSymbol();
1201           Symbol = *RelocSym;
1202         }
1203         reloc_found = true;
1204         break;
1205       }
1206     }
1207     if (reloc_found && isExtern) {
1208       StringRef SymName;
1209       Symbol.getName(SymName);
1210       const char *name = SymName.data();
1211       op_info->AddSymbol.Present = 1;
1212       op_info->AddSymbol.Name = name;
1213
1214       switch (r_type) {
1215       case MachO::ARM64_RELOC_PAGE21:
1216         /* @page */
1217         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
1218         break;
1219       case MachO::ARM64_RELOC_PAGEOFF12:
1220         /* @pageoff */
1221         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
1222         break;
1223       case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
1224         /* @gotpage */
1225         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
1226         break;
1227       case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1228         /* @gotpageoff */
1229         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
1230         break;
1231       case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
1232         /* @tvlppage is not implemented in llvm-mc */
1233         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
1234         break;
1235       case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
1236         /* @tvlppageoff is not implemented in llvm-mc */
1237         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
1238         break;
1239       default:
1240       case MachO::ARM64_RELOC_BRANCH26:
1241         op_info->VariantKind = LLVMDisassembler_VariantKind_None;
1242         break;
1243       }
1244       return 1;
1245     }
1246     return 0;
1247   } else {
1248     return 0;
1249   }
1250 }
1251
1252 // GuessCstringPointer is passed the address of what might be a pointer to a
1253 // literal string in a cstring section.  If that address is in a cstring section
1254 // it returns a pointer to that string.  Else it returns nullptr.
1255 const char *GuessCstringPointer(uint64_t ReferenceValue,
1256                                 struct DisassembleInfo *info) {
1257   uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1258   MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1259   for (unsigned I = 0;; ++I) {
1260     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1261       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1262       for (unsigned J = 0; J < Seg.nsects; ++J) {
1263         MachO::section_64 Sec = info->O->getSection64(Load, J);
1264         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1265         if (section_type == MachO::S_CSTRING_LITERALS &&
1266             ReferenceValue >= Sec.addr &&
1267             ReferenceValue < Sec.addr + Sec.size) {
1268           uint64_t sect_offset = ReferenceValue - Sec.addr;
1269           uint64_t object_offset = Sec.offset + sect_offset;
1270           StringRef MachOContents = info->O->getData();
1271           uint64_t object_size = MachOContents.size();
1272           const char *object_addr = (const char *)MachOContents.data();
1273           if (object_offset < object_size) {
1274             const char *name = object_addr + object_offset;
1275             return name;
1276           } else {
1277             return nullptr;
1278           }
1279         }
1280       }
1281     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1282       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1283       for (unsigned J = 0; J < Seg.nsects; ++J) {
1284         MachO::section Sec = info->O->getSection(Load, J);
1285         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1286         if (section_type == MachO::S_CSTRING_LITERALS &&
1287             ReferenceValue >= Sec.addr &&
1288             ReferenceValue < Sec.addr + Sec.size) {
1289           uint64_t sect_offset = ReferenceValue - Sec.addr;
1290           uint64_t object_offset = Sec.offset + sect_offset;
1291           StringRef MachOContents = info->O->getData();
1292           uint64_t object_size = MachOContents.size();
1293           const char *object_addr = (const char *)MachOContents.data();
1294           if (object_offset < object_size) {
1295             const char *name = object_addr + object_offset;
1296             return name;
1297           } else {
1298             return nullptr;
1299           }
1300         }
1301       }
1302     }
1303     if (I == LoadCommandCount - 1)
1304       break;
1305     else
1306       Load = info->O->getNextLoadCommandInfo(Load);
1307   }
1308   return nullptr;
1309 }
1310
1311 // GuessIndirectSymbol returns the name of the indirect symbol for the
1312 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
1313 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
1314 // symbol name being referenced by the stub or pointer.
1315 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
1316                                        struct DisassembleInfo *info) {
1317   uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1318   MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1319   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
1320   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
1321   for (unsigned I = 0;; ++I) {
1322     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1323       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1324       for (unsigned J = 0; J < Seg.nsects; ++J) {
1325         MachO::section_64 Sec = info->O->getSection64(Load, J);
1326         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1327         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1328              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1329              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1330              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1331              section_type == MachO::S_SYMBOL_STUBS) &&
1332             ReferenceValue >= Sec.addr &&
1333             ReferenceValue < Sec.addr + Sec.size) {
1334           uint32_t stride;
1335           if (section_type == MachO::S_SYMBOL_STUBS)
1336             stride = Sec.reserved2;
1337           else
1338             stride = 8;
1339           if (stride == 0)
1340             return nullptr;
1341           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1342           if (index < Dysymtab.nindirectsyms) {
1343             uint32_t indirect_symbol =
1344                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1345             if (indirect_symbol < Symtab.nsyms) {
1346               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1347               SymbolRef Symbol = *Sym;
1348               StringRef SymName;
1349               Symbol.getName(SymName);
1350               const char *name = SymName.data();
1351               return name;
1352             }
1353           }
1354         }
1355       }
1356     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1357       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1358       for (unsigned J = 0; J < Seg.nsects; ++J) {
1359         MachO::section Sec = info->O->getSection(Load, J);
1360         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1361         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1362              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1363              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1364              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1365              section_type == MachO::S_SYMBOL_STUBS) &&
1366             ReferenceValue >= Sec.addr &&
1367             ReferenceValue < Sec.addr + Sec.size) {
1368           uint32_t stride;
1369           if (section_type == MachO::S_SYMBOL_STUBS)
1370             stride = Sec.reserved2;
1371           else
1372             stride = 4;
1373           if (stride == 0)
1374             return nullptr;
1375           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1376           if (index < Dysymtab.nindirectsyms) {
1377             uint32_t indirect_symbol =
1378                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1379             if (indirect_symbol < Symtab.nsyms) {
1380               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1381               SymbolRef Symbol = *Sym;
1382               StringRef SymName;
1383               Symbol.getName(SymName);
1384               const char *name = SymName.data();
1385               return name;
1386             }
1387           }
1388         }
1389       }
1390     }
1391     if (I == LoadCommandCount - 1)
1392       break;
1393     else
1394       Load = info->O->getNextLoadCommandInfo(Load);
1395   }
1396   return nullptr;
1397 }
1398
1399 // method_reference() is called passing it the ReferenceName that might be
1400 // a reference it to an Objective-C method call.  If so then it allocates and
1401 // assembles a method call string with the values last seen and saved in
1402 // the DisassembleInfo's class_name and selector_name fields.  This is saved
1403 // into the method field of the info and any previous string is free'ed.
1404 // Then the class_name field in the info is set to nullptr.  The method call
1405 // string is set into ReferenceName and ReferenceType is set to
1406 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
1407 // then both ReferenceType and ReferenceName are left unchanged.
1408 static void method_reference(struct DisassembleInfo *info,
1409                              uint64_t *ReferenceType,
1410                              const char **ReferenceName) {
1411   unsigned int Arch = info->O->getArch();
1412   if (*ReferenceName != nullptr) {
1413     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
1414       if (info->selector_name != nullptr) {
1415         if (info->method != nullptr)
1416           free(info->method);
1417         if (info->class_name != nullptr) {
1418           info->method = (char *)malloc(5 + strlen(info->class_name) +
1419                                         strlen(info->selector_name));
1420           if (info->method != nullptr) {
1421             strcpy(info->method, "+[");
1422             strcat(info->method, info->class_name);
1423             strcat(info->method, " ");
1424             strcat(info->method, info->selector_name);
1425             strcat(info->method, "]");
1426             *ReferenceName = info->method;
1427             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1428           }
1429         } else {
1430           info->method = (char *)malloc(9 + strlen(info->selector_name));
1431           if (info->method != nullptr) {
1432             if (Arch == Triple::x86_64)
1433               strcpy(info->method, "-[%rdi ");
1434             else if (Arch == Triple::aarch64)
1435               strcpy(info->method, "-[x0 ");
1436             else
1437               strcpy(info->method, "-[r? ");
1438             strcat(info->method, info->selector_name);
1439             strcat(info->method, "]");
1440             *ReferenceName = info->method;
1441             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1442           }
1443         }
1444         info->class_name = nullptr;
1445       }
1446     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
1447       if (info->selector_name != nullptr) {
1448         if (info->method != nullptr)
1449           free(info->method);
1450         info->method = (char *)malloc(17 + strlen(info->selector_name));
1451         if (info->method != nullptr) {
1452           if (Arch == Triple::x86_64)
1453             strcpy(info->method, "-[[%rdi super] ");
1454           else if (Arch == Triple::aarch64)
1455             strcpy(info->method, "-[[x0 super] ");
1456           else
1457             strcpy(info->method, "-[[r? super] ");
1458           strcat(info->method, info->selector_name);
1459           strcat(info->method, "]");
1460           *ReferenceName = info->method;
1461           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1462         }
1463         info->class_name = nullptr;
1464       }
1465     }
1466   }
1467 }
1468
1469 // GuessPointerPointer() is passed the address of what might be a pointer to
1470 // a reference to an Objective-C class, selector, message ref or cfstring.
1471 // If so the value of the pointer is returned and one of the booleans are set
1472 // to true.  If not zero is returned and all the booleans are set to false.
1473 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
1474                                     struct DisassembleInfo *info,
1475                                     bool &classref, bool &selref, bool &msgref,
1476                                     bool &cfstring) {
1477   classref = false;
1478   selref = false;
1479   msgref = false;
1480   cfstring = false;
1481   uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1482   MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1483   for (unsigned I = 0;; ++I) {
1484     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1485       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1486       for (unsigned J = 0; J < Seg.nsects; ++J) {
1487         MachO::section_64 Sec = info->O->getSection64(Load, J);
1488         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
1489              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1490              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
1491              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
1492              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
1493             ReferenceValue >= Sec.addr &&
1494             ReferenceValue < Sec.addr + Sec.size) {
1495           uint64_t sect_offset = ReferenceValue - Sec.addr;
1496           uint64_t object_offset = Sec.offset + sect_offset;
1497           StringRef MachOContents = info->O->getData();
1498           uint64_t object_size = MachOContents.size();
1499           const char *object_addr = (const char *)MachOContents.data();
1500           if (object_offset < object_size) {
1501             uint64_t pointer_value;
1502             memcpy(&pointer_value, object_addr + object_offset,
1503                    sizeof(uint64_t));
1504             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1505               sys::swapByteOrder(pointer_value);
1506             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
1507               selref = true;
1508             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1509                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
1510               classref = true;
1511             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
1512                      ReferenceValue + 8 < Sec.addr + Sec.size) {
1513               msgref = true;
1514               memcpy(&pointer_value, object_addr + object_offset + 8,
1515                      sizeof(uint64_t));
1516               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1517                 sys::swapByteOrder(pointer_value);
1518             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
1519               cfstring = true;
1520             return pointer_value;
1521           } else {
1522             return 0;
1523           }
1524         }
1525       }
1526     }
1527     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
1528     if (I == LoadCommandCount - 1)
1529       break;
1530     else
1531       Load = info->O->getNextLoadCommandInfo(Load);
1532   }
1533   return 0;
1534 }
1535
1536 // get_pointer_64 returns a pointer to the bytes in the object file at the
1537 // Address from a section in the Mach-O file.  And indirectly returns the
1538 // offset into the section, number of bytes left in the section past the offset
1539 // and which section is was being referenced.  If the Address is not in a
1540 // section nullptr is returned.
1541 const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
1542                            SectionRef &S, DisassembleInfo *info) {
1543   offset = 0;
1544   left = 0;
1545   S = SectionRef();
1546   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
1547     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
1548     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
1549     if (Address >= SectAddress && Address < SectAddress + SectSize) {
1550       S = (*(info->Sections))[SectIdx];
1551       offset = Address - SectAddress;
1552       left = SectSize - offset;
1553       StringRef SectContents;
1554       ((*(info->Sections))[SectIdx]).getContents(SectContents);
1555       return SectContents.data() + offset;
1556     }
1557   }
1558   return nullptr;
1559 }
1560
1561 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
1562 // the symbol indirectly through n_value. Based on the relocation information
1563 // for the specified section offset in the specified section reference.
1564 const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
1565                           DisassembleInfo *info, uint64_t &n_value) {
1566   n_value = 0;
1567   if (info->verbose == false)
1568     return nullptr;
1569
1570   // See if there is an external relocation entry at the sect_offset.
1571   bool reloc_found = false;
1572   DataRefImpl Rel;
1573   MachO::any_relocation_info RE;
1574   bool isExtern = false;
1575   SymbolRef Symbol;
1576   for (const RelocationRef &Reloc : S.relocations()) {
1577     uint64_t RelocOffset;
1578     Reloc.getOffset(RelocOffset);
1579     if (RelocOffset == sect_offset) {
1580       Rel = Reloc.getRawDataRefImpl();
1581       RE = info->O->getRelocation(Rel);
1582       if (info->O->isRelocationScattered(RE))
1583         continue;
1584       isExtern = info->O->getPlainRelocationExternal(RE);
1585       if (isExtern) {
1586         symbol_iterator RelocSym = Reloc.getSymbol();
1587         Symbol = *RelocSym;
1588       }
1589       reloc_found = true;
1590       break;
1591     }
1592   }
1593   // If there is an external relocation entry for a symbol in this section
1594   // at this section_offset then use that symbol's value for the n_value
1595   // and return its name.
1596   const char *SymbolName = nullptr;
1597   if (reloc_found && isExtern) {
1598     Symbol.getAddress(n_value);
1599     StringRef name;
1600     Symbol.getName(name);
1601     if (!name.empty()) {
1602       SymbolName = name.data();
1603       return SymbolName;
1604     }
1605   }
1606
1607   // TODO: For fully linked images, look through the external relocation
1608   // entries off the dynamic symtab command. For these the r_offset is from the
1609   // start of the first writeable segment in the Mach-O file.  So the offset
1610   // to this section from that segment is passed to this routine by the caller,
1611   // as the database_offset. Which is the difference of the section's starting
1612   // address and the first writable segment.
1613   //
1614   // NOTE: need add passing the database_offset to this routine.
1615
1616   // TODO: We did not find an external relocation entry so look up the
1617   // ReferenceValue as an address of a symbol and if found return that symbol's
1618   // name.
1619   //
1620   // NOTE: need add passing the ReferenceValue to this routine.  Then that code
1621   // would simply be this:
1622   // SymbolName = GuessSymbolName(ReferenceValue, info);
1623
1624   return SymbolName;
1625 }
1626
1627 // These are structs in the Objective-C meta data and read to produce the
1628 // comments for disassembly.  While these are part of the ABI they are no
1629 // public defintions.  So the are here not in include/llvm/Support/MachO.h .
1630
1631 // The cfstring object in a 64-bit Mach-O file.
1632 struct cfstring64_t {
1633   uint64_t isa;        // class64_t * (64-bit pointer)
1634   uint64_t flags;      // flag bits
1635   uint64_t characters; // char * (64-bit pointer)
1636   uint64_t length;     // number of non-NULL characters in above
1637 };
1638
1639 // The class object in a 64-bit Mach-O file.
1640 struct class64_t {
1641   uint64_t isa;        // class64_t * (64-bit pointer)
1642   uint64_t superclass; // class64_t * (64-bit pointer)
1643   uint64_t cache;      // Cache (64-bit pointer)
1644   uint64_t vtable;     // IMP * (64-bit pointer)
1645   uint64_t data;       // class_ro64_t * (64-bit pointer)
1646 };
1647
1648 struct class_ro64_t {
1649   uint32_t flags;
1650   uint32_t instanceStart;
1651   uint32_t instanceSize;
1652   uint32_t reserved;
1653   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
1654   uint64_t name;           // const char * (64-bit pointer)
1655   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
1656   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
1657   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
1658   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
1659   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
1660 };
1661
1662 inline void swapStruct(struct cfstring64_t &cfs) {
1663   sys::swapByteOrder(cfs.isa);
1664   sys::swapByteOrder(cfs.flags);
1665   sys::swapByteOrder(cfs.characters);
1666   sys::swapByteOrder(cfs.length);
1667 }
1668
1669 inline void swapStruct(struct class64_t &c) {
1670   sys::swapByteOrder(c.isa);
1671   sys::swapByteOrder(c.superclass);
1672   sys::swapByteOrder(c.cache);
1673   sys::swapByteOrder(c.vtable);
1674   sys::swapByteOrder(c.data);
1675 }
1676
1677 inline void swapStruct(struct class_ro64_t &cro) {
1678   sys::swapByteOrder(cro.flags);
1679   sys::swapByteOrder(cro.instanceStart);
1680   sys::swapByteOrder(cro.instanceSize);
1681   sys::swapByteOrder(cro.reserved);
1682   sys::swapByteOrder(cro.ivarLayout);
1683   sys::swapByteOrder(cro.name);
1684   sys::swapByteOrder(cro.baseMethods);
1685   sys::swapByteOrder(cro.baseProtocols);
1686   sys::swapByteOrder(cro.ivars);
1687   sys::swapByteOrder(cro.weakIvarLayout);
1688   sys::swapByteOrder(cro.baseProperties);
1689 }
1690
1691 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
1692                                                  struct DisassembleInfo *info);
1693
1694 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
1695 // to an Objective-C class and returns the class name.  It is also passed the
1696 // address of the pointer, so when the pointer is zero as it can be in an .o
1697 // file, that is used to look for an external relocation entry with a symbol
1698 // name.
1699 const char *get_objc2_64bit_class_name(uint64_t pointer_value,
1700                                        uint64_t ReferenceValue,
1701                                        struct DisassembleInfo *info) {
1702   const char *r;
1703   uint32_t offset, left;
1704   SectionRef S;
1705
1706   // The pointer_value can be 0 in an object file and have a relocation
1707   // entry for the class symbol at the ReferenceValue (the address of the
1708   // pointer).
1709   if (pointer_value == 0) {
1710     r = get_pointer_64(ReferenceValue, offset, left, S, info);
1711     if (r == nullptr || left < sizeof(uint64_t))
1712       return nullptr;
1713     uint64_t n_value;
1714     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1715     if (symbol_name == nullptr)
1716       return nullptr;
1717     const char *class_name = strrchr(symbol_name, '$');
1718     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
1719       return class_name + 2;
1720     else
1721       return nullptr;
1722   }
1723
1724   // The case were the pointer_value is non-zero and points to a class defined
1725   // in this Mach-O file.
1726   r = get_pointer_64(pointer_value, offset, left, S, info);
1727   if (r == nullptr || left < sizeof(struct class64_t))
1728     return nullptr;
1729   struct class64_t c;
1730   memcpy(&c, r, sizeof(struct class64_t));
1731   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1732     swapStruct(c);
1733   if (c.data == 0)
1734     return nullptr;
1735   r = get_pointer_64(c.data, offset, left, S, info);
1736   if (r == nullptr || left < sizeof(struct class_ro64_t))
1737     return nullptr;
1738   struct class_ro64_t cro;
1739   memcpy(&cro, r, sizeof(struct class_ro64_t));
1740   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1741     swapStruct(cro);
1742   if (cro.name == 0)
1743     return nullptr;
1744   const char *name = get_pointer_64(cro.name, offset, left, S, info);
1745   return name;
1746 }
1747
1748 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
1749 // pointer to a cfstring and returns its name or nullptr.
1750 const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
1751                                           struct DisassembleInfo *info) {
1752   const char *r, *name;
1753   uint32_t offset, left;
1754   SectionRef S;
1755   struct cfstring64_t cfs;
1756   uint64_t cfs_characters;
1757
1758   r = get_pointer_64(ReferenceValue, offset, left, S, info);
1759   if (r == nullptr || left < sizeof(struct cfstring64_t))
1760     return nullptr;
1761   memcpy(&cfs, r, sizeof(struct cfstring64_t));
1762   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1763     swapStruct(cfs);
1764   if (cfs.characters == 0) {
1765     uint64_t n_value;
1766     const char *symbol_name = get_symbol_64(
1767         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
1768     if (symbol_name == nullptr)
1769       return nullptr;
1770     cfs_characters = n_value;
1771   } else
1772     cfs_characters = cfs.characters;
1773   name = get_pointer_64(cfs_characters, offset, left, S, info);
1774
1775   return name;
1776 }
1777
1778 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
1779 // of a pointer to an Objective-C selector reference when the pointer value is
1780 // zero as in a .o file and is likely to have a external relocation entry with
1781 // who's symbol's n_value is the real pointer to the selector name.  If that is
1782 // the case the real pointer to the selector name is returned else 0 is
1783 // returned
1784 uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
1785                                 struct DisassembleInfo *info) {
1786   uint32_t offset, left;
1787   SectionRef S;
1788
1789   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
1790   if (r == nullptr || left < sizeof(uint64_t))
1791     return 0;
1792   uint64_t n_value;
1793   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1794   if (symbol_name == nullptr)
1795     return 0;
1796   return n_value;
1797 }
1798
1799 // GuessLiteralPointer returns a string which for the item in the Mach-O file
1800 // for the address passed in as ReferenceValue for printing as a comment with
1801 // the instruction and also returns the corresponding type of that item
1802 // indirectly through ReferenceType.
1803 //
1804 // If ReferenceValue is an address of literal cstring then a pointer to the
1805 // cstring is returned and ReferenceType is set to
1806 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
1807 //
1808 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
1809 // Class ref that name is returned and the ReferenceType is set accordingly.
1810 //
1811 // Lastly, literals which are Symbol address in a literal pool are looked for
1812 // and if found the symbol name is returned and ReferenceType is set to
1813 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
1814 //
1815 // If there is no item in the Mach-O file for the address passed in as
1816 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
1817 const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
1818                                 uint64_t *ReferenceType,
1819                                 struct DisassembleInfo *info) {
1820   // First see if there is an external relocation entry at the ReferencePC.
1821   uint64_t sect_addr = info->S.getAddress();
1822   uint64_t sect_offset = ReferencePC - sect_addr;
1823   bool reloc_found = false;
1824   DataRefImpl Rel;
1825   MachO::any_relocation_info RE;
1826   bool isExtern = false;
1827   SymbolRef Symbol;
1828   for (const RelocationRef &Reloc : info->S.relocations()) {
1829     uint64_t RelocOffset;
1830     Reloc.getOffset(RelocOffset);
1831     if (RelocOffset == sect_offset) {
1832       Rel = Reloc.getRawDataRefImpl();
1833       RE = info->O->getRelocation(Rel);
1834       if (info->O->isRelocationScattered(RE))
1835         continue;
1836       isExtern = info->O->getPlainRelocationExternal(RE);
1837       if (isExtern) {
1838         symbol_iterator RelocSym = Reloc.getSymbol();
1839         Symbol = *RelocSym;
1840       }
1841       reloc_found = true;
1842       break;
1843     }
1844   }
1845   // If there is an external relocation entry for a symbol in a section
1846   // then used that symbol's value for the value of the reference.
1847   if (reloc_found && isExtern) {
1848     if (info->O->getAnyRelocationPCRel(RE)) {
1849       unsigned Type = info->O->getAnyRelocationType(RE);
1850       if (Type == MachO::X86_64_RELOC_SIGNED) {
1851         Symbol.getAddress(ReferenceValue);
1852       }
1853     }
1854   }
1855
1856   // Look for literals such as Objective-C CFStrings refs, Selector refs,
1857   // Message refs and Class refs.
1858   bool classref, selref, msgref, cfstring;
1859   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
1860                                                selref, msgref, cfstring);
1861   if (classref == true && pointer_value == 0) {
1862     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
1863     // And the pointer_value in that section is typically zero as it will be
1864     // set by dyld as part of the "bind information".
1865     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
1866     if (name != nullptr) {
1867       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1868       const char *class_name = strrchr(name, '$');
1869       if (class_name != nullptr && class_name[1] == '_' &&
1870           class_name[2] != '\0') {
1871         info->class_name = class_name + 2;
1872         return name;
1873       }
1874     }
1875   }
1876
1877   if (classref == true) {
1878     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1879     const char *name =
1880         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
1881     if (name != nullptr)
1882       info->class_name = name;
1883     else
1884       name = "bad class ref";
1885     return name;
1886   }
1887
1888   if (cfstring == true) {
1889     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
1890     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
1891     return name;
1892   }
1893
1894   if (selref == true && pointer_value == 0)
1895     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
1896
1897   if (pointer_value != 0)
1898     ReferenceValue = pointer_value;
1899
1900   const char *name = GuessCstringPointer(ReferenceValue, info);
1901   if (name) {
1902     if (pointer_value != 0 && selref == true) {
1903       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
1904       info->selector_name = name;
1905     } else if (pointer_value != 0 && msgref == true) {
1906       info->class_name = nullptr;
1907       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
1908       info->selector_name = name;
1909     } else
1910       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
1911     return name;
1912   }
1913
1914   // Lastly look for an indirect symbol with this ReferenceValue which is in
1915   // a literal pool.  If found return that symbol name.
1916   name = GuessIndirectSymbol(ReferenceValue, info);
1917   if (name) {
1918     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
1919     return name;
1920   }
1921
1922   return nullptr;
1923 }
1924
1925 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
1926 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
1927 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
1928 // is created and returns the symbol name that matches the ReferenceValue or
1929 // nullptr if none.  The ReferenceType is passed in for the IN type of
1930 // reference the instruction is making from the values in defined in the header
1931 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
1932 // Out type and the ReferenceName will also be set which is added as a comment
1933 // to the disassembled instruction.
1934 //
1935 #if HAVE_CXXABI_H
1936 // If the symbol name is a C++ mangled name then the demangled name is
1937 // returned through ReferenceName and ReferenceType is set to
1938 // LLVMDisassembler_ReferenceType_DeMangled_Name .
1939 #endif
1940 //
1941 // When this is called to get a symbol name for a branch target then the
1942 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
1943 // SymbolValue will be looked for in the indirect symbol table to determine if
1944 // it is an address for a symbol stub.  If so then the symbol name for that
1945 // stub is returned indirectly through ReferenceName and then ReferenceType is
1946 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
1947 //
1948 // When this is called with an value loaded via a PC relative load then
1949 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
1950 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
1951 // or an Objective-C meta data reference.  If so the output ReferenceType is
1952 // set to correspond to that as well as setting the ReferenceName.
1953 const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
1954                                    uint64_t *ReferenceType,
1955                                    uint64_t ReferencePC,
1956                                    const char **ReferenceName) {
1957   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1958   // If no verbose symbolic information is wanted then just return nullptr.
1959   if (info->verbose == false) {
1960     *ReferenceName = nullptr;
1961     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1962     return nullptr;
1963   }
1964
1965   const char *SymbolName = GuessSymbolName(ReferenceValue, info);
1966
1967   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
1968     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
1969     if (*ReferenceName != nullptr) {
1970       method_reference(info, ReferenceType, ReferenceName);
1971       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
1972         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
1973     } else
1974 #if HAVE_CXXABI_H
1975         if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1976       if (info->demangled_name != nullptr)
1977         free(info->demangled_name);
1978       int status;
1979       info->demangled_name =
1980           abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
1981       if (info->demangled_name != nullptr) {
1982         *ReferenceName = info->demangled_name;
1983         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1984       } else
1985         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1986     } else
1987 #endif
1988       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1989   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
1990     *ReferenceName =
1991         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1992     if (*ReferenceName)
1993       method_reference(info, ReferenceType, ReferenceName);
1994     else
1995       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1996     // If this is arm64 and the reference is an adrp instruction save the
1997     // instruction, passed in ReferenceValue and the address of the instruction
1998     // for use later if we see and add immediate instruction.
1999   } else if (info->O->getArch() == Triple::aarch64 &&
2000              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2001     info->adrp_inst = ReferenceValue;
2002     info->adrp_addr = ReferencePC;
2003     SymbolName = nullptr;
2004     *ReferenceName = nullptr;
2005     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2006     // If this is arm64 and reference is an add immediate instruction and we
2007     // have
2008     // seen an adrp instruction just before it and the adrp's Xd register
2009     // matches
2010     // this add's Xn register reconstruct the value being referenced and look to
2011     // see if it is a literal pointer.  Note the add immediate instruction is
2012     // passed in ReferenceValue.
2013   } else if (info->O->getArch() == Triple::aarch64 &&
2014              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2015              ReferencePC - 4 == info->adrp_addr &&
2016              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2017              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2018     uint32_t addxri_inst;
2019     uint64_t adrp_imm, addxri_imm;
2020
2021     adrp_imm =
2022         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2023     if (info->adrp_inst & 0x0200000)
2024       adrp_imm |= 0xfffffffffc000000LL;
2025
2026     addxri_inst = ReferenceValue;
2027     addxri_imm = (addxri_inst >> 10) & 0xfff;
2028     if (((addxri_inst >> 22) & 0x3) == 1)
2029       addxri_imm <<= 12;
2030
2031     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2032                      (adrp_imm << 12) + addxri_imm;
2033
2034     *ReferenceName =
2035         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2036     if (*ReferenceName == nullptr)
2037       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2038     // If this is arm64 and the reference is a load register instruction and we
2039     // have seen an adrp instruction just before it and the adrp's Xd register
2040     // matches this add's Xn register reconstruct the value being referenced and
2041     // look to see if it is a literal pointer.  Note the load register
2042     // instruction is passed in ReferenceValue.
2043   } else if (info->O->getArch() == Triple::aarch64 &&
2044              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2045              ReferencePC - 4 == info->adrp_addr &&
2046              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2047              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2048     uint32_t ldrxui_inst;
2049     uint64_t adrp_imm, ldrxui_imm;
2050
2051     adrp_imm =
2052         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2053     if (info->adrp_inst & 0x0200000)
2054       adrp_imm |= 0xfffffffffc000000LL;
2055
2056     ldrxui_inst = ReferenceValue;
2057     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2058
2059     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2060                      (adrp_imm << 12) + (ldrxui_imm << 3);
2061
2062     *ReferenceName =
2063         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2064     if (*ReferenceName == nullptr)
2065       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2066   }
2067   // If this arm64 and is an load register (PC-relative) instruction the
2068   // ReferenceValue is the PC plus the immediate value.
2069   else if (info->O->getArch() == Triple::aarch64 &&
2070            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2071             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2072     *ReferenceName =
2073         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2074     if (*ReferenceName == nullptr)
2075       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2076   }
2077 #if HAVE_CXXABI_H
2078   else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2079     if (info->demangled_name != nullptr)
2080       free(info->demangled_name);
2081     int status;
2082     info->demangled_name =
2083         abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2084     if (info->demangled_name != nullptr) {
2085       *ReferenceName = info->demangled_name;
2086       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2087     }
2088   }
2089 #endif
2090   else {
2091     *ReferenceName = nullptr;
2092     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2093   }
2094
2095   return SymbolName;
2096 }
2097
2098 /// \brief Emits the comments that are stored in the CommentStream.
2099 /// Each comment in the CommentStream must end with a newline.
2100 static void emitComments(raw_svector_ostream &CommentStream,
2101                          SmallString<128> &CommentsToEmit,
2102                          formatted_raw_ostream &FormattedOS,
2103                          const MCAsmInfo &MAI) {
2104   // Flush the stream before taking its content.
2105   CommentStream.flush();
2106   StringRef Comments = CommentsToEmit.str();
2107   // Get the default information for printing a comment.
2108   const char *CommentBegin = MAI.getCommentString();
2109   unsigned CommentColumn = MAI.getCommentColumn();
2110   bool IsFirst = true;
2111   while (!Comments.empty()) {
2112     if (!IsFirst)
2113       FormattedOS << '\n';
2114     // Emit a line of comments.
2115     FormattedOS.PadToColumn(CommentColumn);
2116     size_t Position = Comments.find('\n');
2117     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2118     // Move after the newline character.
2119     Comments = Comments.substr(Position + 1);
2120     IsFirst = false;
2121   }
2122   FormattedOS.flush();
2123
2124   // Tell the comment stream that the vector changed underneath it.
2125   CommentsToEmit.clear();
2126   CommentStream.resync();
2127 }
2128
2129 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF) {
2130   const char *McpuDefault = nullptr;
2131   const Target *ThumbTarget = nullptr;
2132   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
2133   if (!TheTarget) {
2134     // GetTarget prints out stuff.
2135     return;
2136   }
2137   if (MCPU.empty() && McpuDefault)
2138     MCPU = McpuDefault;
2139
2140   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
2141   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
2142   if (ThumbTarget)
2143     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
2144
2145   // Package up features to be passed to target/subtarget
2146   std::string FeaturesStr;
2147   if (MAttrs.size()) {
2148     SubtargetFeatures Features;
2149     for (unsigned i = 0; i != MAttrs.size(); ++i)
2150       Features.AddFeature(MAttrs[i]);
2151     FeaturesStr = Features.getString();
2152   }
2153
2154   // Set up disassembler.
2155   std::unique_ptr<const MCRegisterInfo> MRI(
2156       TheTarget->createMCRegInfo(TripleName));
2157   std::unique_ptr<const MCAsmInfo> AsmInfo(
2158       TheTarget->createMCAsmInfo(*MRI, TripleName));
2159   std::unique_ptr<const MCSubtargetInfo> STI(
2160       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
2161   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
2162   std::unique_ptr<MCDisassembler> DisAsm(
2163       TheTarget->createMCDisassembler(*STI, Ctx));
2164   std::unique_ptr<MCSymbolizer> Symbolizer;
2165   struct DisassembleInfo SymbolizerInfo;
2166   std::unique_ptr<MCRelocationInfo> RelInfo(
2167       TheTarget->createMCRelocationInfo(TripleName, Ctx));
2168   if (RelInfo) {
2169     Symbolizer.reset(TheTarget->createMCSymbolizer(
2170         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2171         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
2172     DisAsm->setSymbolizer(std::move(Symbolizer));
2173   }
2174   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
2175   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
2176       AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
2177   // Set the display preference for hex vs. decimal immediates.
2178   IP->setPrintImmHex(PrintImmHex);
2179   // Comment stream and backing vector.
2180   SmallString<128> CommentsToEmit;
2181   raw_svector_ostream CommentStream(CommentsToEmit);
2182   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
2183   // if it is done then arm64 comments for string literals don't get printed
2184   // and some constant get printed instead and not setting it causes intel
2185   // (32-bit and 64-bit) comments printed with different spacing before the
2186   // comment causing different diffs with the 'C' disassembler library API.
2187   // IP->setCommentStream(CommentStream);
2188
2189   if (!AsmInfo || !STI || !DisAsm || !IP) {
2190     errs() << "error: couldn't initialize disassembler for target "
2191            << TripleName << '\n';
2192     return;
2193   }
2194
2195   // Set up thumb disassembler.
2196   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
2197   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
2198   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
2199   std::unique_ptr<MCDisassembler> ThumbDisAsm;
2200   std::unique_ptr<MCInstPrinter> ThumbIP;
2201   std::unique_ptr<MCContext> ThumbCtx;
2202   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
2203   struct DisassembleInfo ThumbSymbolizerInfo;
2204   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
2205   if (ThumbTarget) {
2206     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
2207     ThumbAsmInfo.reset(
2208         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
2209     ThumbSTI.reset(
2210         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
2211     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
2212     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
2213     MCContext *PtrThumbCtx = ThumbCtx.get();
2214     ThumbRelInfo.reset(
2215         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
2216     if (ThumbRelInfo) {
2217       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
2218           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2219           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
2220       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
2221     }
2222     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
2223     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
2224         ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
2225         *ThumbSTI));
2226     // Set the display preference for hex vs. decimal immediates.
2227     ThumbIP->setPrintImmHex(PrintImmHex);
2228   }
2229
2230   if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
2231     errs() << "error: couldn't initialize disassembler for target "
2232            << ThumbTripleName << '\n';
2233     return;
2234   }
2235
2236   MachO::mach_header Header = MachOOF->getHeader();
2237
2238   // FIXME: Using the -cfg command line option, this code used to be able to
2239   // annotate relocations with the referenced symbol's name, and if this was
2240   // inside a __[cf]string section, the data it points to. This is now replaced
2241   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
2242   std::vector<SectionRef> Sections;
2243   std::vector<SymbolRef> Symbols;
2244   SmallVector<uint64_t, 8> FoundFns;
2245   uint64_t BaseSegmentAddress;
2246
2247   getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
2248                         BaseSegmentAddress);
2249
2250   // Sort the symbols by address, just in case they didn't come in that way.
2251   std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
2252
2253   // Build a data in code table that is sorted on by the address of each entry.
2254   uint64_t BaseAddress = 0;
2255   if (Header.filetype == MachO::MH_OBJECT)
2256     BaseAddress = Sections[0].getAddress();
2257   else
2258     BaseAddress = BaseSegmentAddress;
2259   DiceTable Dices;
2260   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
2261        DI != DE; ++DI) {
2262     uint32_t Offset;
2263     DI->getOffset(Offset);
2264     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
2265   }
2266   array_pod_sort(Dices.begin(), Dices.end());
2267
2268 #ifndef NDEBUG
2269   raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
2270 #else
2271   raw_ostream &DebugOut = nulls();
2272 #endif
2273
2274   std::unique_ptr<DIContext> diContext;
2275   ObjectFile *DbgObj = MachOOF;
2276   // Try to find debug info and set up the DIContext for it.
2277   if (UseDbg) {
2278     // A separate DSym file path was specified, parse it as a macho file,
2279     // get the sections and supply it to the section name parsing machinery.
2280     if (!DSYMFile.empty()) {
2281       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
2282           MemoryBuffer::getFileOrSTDIN(DSYMFile);
2283       if (std::error_code EC = BufOrErr.getError()) {
2284         errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
2285         return;
2286       }
2287       DbgObj =
2288           ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
2289               .get()
2290               .release();
2291     }
2292
2293     // Setup the DIContext
2294     diContext.reset(DIContext::getDWARFContext(*DbgObj));
2295   }
2296
2297   // TODO: For now this only disassembles the (__TEXT,__text) section (see the
2298   // checks in the code below at the top of this loop).  It should allow a
2299   // darwin otool(1) like -s option to disassemble any named segment & section
2300   // that is marked as containing instructions with the attributes
2301   // S_ATTR_PURE_INSTRUCTIONS or S_ATTR_SOME_INSTRUCTIONS in the flags field of
2302   // the section structure.
2303   outs() << "(__TEXT,__text) section\n";
2304
2305   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
2306
2307     bool SectIsText = Sections[SectIdx].isText();
2308     if (SectIsText == false)
2309       continue;
2310
2311     StringRef SectName;
2312     if (Sections[SectIdx].getName(SectName) || SectName != "__text")
2313       continue; // Skip non-text sections
2314
2315     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
2316
2317     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
2318     if (SegmentName != "__TEXT")
2319       continue;
2320
2321     StringRef BytesStr;
2322     Sections[SectIdx].getContents(BytesStr);
2323     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
2324                             BytesStr.size());
2325     uint64_t SectAddress = Sections[SectIdx].getAddress();
2326
2327     bool symbolTableWorked = false;
2328
2329     // Parse relocations.
2330     std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
2331     for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
2332       uint64_t RelocOffset;
2333       Reloc.getOffset(RelocOffset);
2334       uint64_t SectionAddress = Sections[SectIdx].getAddress();
2335       RelocOffset -= SectionAddress;
2336
2337       symbol_iterator RelocSym = Reloc.getSymbol();
2338
2339       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
2340     }
2341     array_pod_sort(Relocs.begin(), Relocs.end());
2342
2343     // Create a map of symbol addresses to symbol names for use by
2344     // the SymbolizerSymbolLookUp() routine.
2345     SymbolAddressMap AddrMap;
2346     for (const SymbolRef &Symbol : MachOOF->symbols()) {
2347       SymbolRef::Type ST;
2348       Symbol.getType(ST);
2349       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
2350           ST == SymbolRef::ST_Other) {
2351         uint64_t Address;
2352         Symbol.getAddress(Address);
2353         StringRef SymName;
2354         Symbol.getName(SymName);
2355         AddrMap[Address] = SymName;
2356       }
2357     }
2358     // Set up the block of info used by the Symbolizer call backs.
2359     SymbolizerInfo.verbose = true;
2360     SymbolizerInfo.O = MachOOF;
2361     SymbolizerInfo.S = Sections[SectIdx];
2362     SymbolizerInfo.AddrMap = &AddrMap;
2363     SymbolizerInfo.Sections = &Sections;
2364     SymbolizerInfo.class_name = nullptr;
2365     SymbolizerInfo.selector_name = nullptr;
2366     SymbolizerInfo.method = nullptr;
2367     SymbolizerInfo.demangled_name = nullptr;
2368     SymbolizerInfo.bindtable = nullptr;
2369     SymbolizerInfo.adrp_addr = 0;
2370     SymbolizerInfo.adrp_inst = 0;
2371     // Same for the ThumbSymbolizer
2372     ThumbSymbolizerInfo.verbose = true;
2373     ThumbSymbolizerInfo.O = MachOOF;
2374     ThumbSymbolizerInfo.S = Sections[SectIdx];
2375     ThumbSymbolizerInfo.AddrMap = &AddrMap;
2376     ThumbSymbolizerInfo.Sections = &Sections;
2377     ThumbSymbolizerInfo.class_name = nullptr;
2378     ThumbSymbolizerInfo.selector_name = nullptr;
2379     ThumbSymbolizerInfo.method = nullptr;
2380     ThumbSymbolizerInfo.demangled_name = nullptr;
2381     ThumbSymbolizerInfo.bindtable = nullptr;
2382     ThumbSymbolizerInfo.adrp_addr = 0;
2383     ThumbSymbolizerInfo.adrp_inst = 0;
2384
2385     // Disassemble symbol by symbol.
2386     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
2387       StringRef SymName;
2388       Symbols[SymIdx].getName(SymName);
2389
2390       SymbolRef::Type ST;
2391       Symbols[SymIdx].getType(ST);
2392       if (ST != SymbolRef::ST_Function)
2393         continue;
2394
2395       // Make sure the symbol is defined in this section.
2396       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
2397       if (!containsSym)
2398         continue;
2399
2400       // Start at the address of the symbol relative to the section's address.
2401       uint64_t Start = 0;
2402       uint64_t SectionAddress = Sections[SectIdx].getAddress();
2403       Symbols[SymIdx].getAddress(Start);
2404       Start -= SectionAddress;
2405
2406       // Stop disassembling either at the beginning of the next symbol or at
2407       // the end of the section.
2408       bool containsNextSym = false;
2409       uint64_t NextSym = 0;
2410       uint64_t NextSymIdx = SymIdx + 1;
2411       while (Symbols.size() > NextSymIdx) {
2412         SymbolRef::Type NextSymType;
2413         Symbols[NextSymIdx].getType(NextSymType);
2414         if (NextSymType == SymbolRef::ST_Function) {
2415           containsNextSym =
2416               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
2417           Symbols[NextSymIdx].getAddress(NextSym);
2418           NextSym -= SectionAddress;
2419           break;
2420         }
2421         ++NextSymIdx;
2422       }
2423
2424       uint64_t SectSize = Sections[SectIdx].getSize();
2425       uint64_t End = containsNextSym ? NextSym : SectSize;
2426       uint64_t Size;
2427
2428       symbolTableWorked = true;
2429
2430       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
2431       bool isThumb =
2432           (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
2433
2434       outs() << SymName << ":\n";
2435       DILineInfo lastLine;
2436       for (uint64_t Index = Start; Index < End; Index += Size) {
2437         MCInst Inst;
2438
2439         uint64_t PC = SectAddress + Index;
2440         if (FullLeadingAddr) {
2441           if (MachOOF->is64Bit())
2442             outs() << format("%016" PRIx64, PC);
2443           else
2444             outs() << format("%08" PRIx64, PC);
2445         } else {
2446           outs() << format("%8" PRIx64 ":", PC);
2447         }
2448         if (!NoShowRawInsn)
2449           outs() << "\t";
2450
2451         // Check the data in code table here to see if this is data not an
2452         // instruction to be disassembled.
2453         DiceTable Dice;
2454         Dice.push_back(std::make_pair(PC, DiceRef()));
2455         dice_table_iterator DTI =
2456             std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
2457                         compareDiceTableEntries);
2458         if (DTI != Dices.end()) {
2459           uint16_t Length;
2460           DTI->second.getLength(Length);
2461           uint16_t Kind;
2462           DTI->second.getKind(Kind);
2463           Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
2464                                     Index,
2465                                 Length, Kind);
2466           if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
2467               (PC == (DTI->first + Length - 1)) && (Length & 1))
2468             Size++;
2469           continue;
2470         }
2471
2472         SmallVector<char, 64> AnnotationsBytes;
2473         raw_svector_ostream Annotations(AnnotationsBytes);
2474
2475         bool gotInst;
2476         if (isThumb)
2477           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
2478                                                 PC, DebugOut, Annotations);
2479         else
2480           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
2481                                            DebugOut, Annotations);
2482         if (gotInst) {
2483           if (!NoShowRawInsn) {
2484             DumpBytes(StringRef(
2485                 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
2486           }
2487           formatted_raw_ostream FormattedOS(outs());
2488           Annotations.flush();
2489           StringRef AnnotationsStr = Annotations.str();
2490           if (isThumb)
2491             ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
2492           else
2493             IP->printInst(&Inst, FormattedOS, AnnotationsStr);
2494           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
2495
2496           // Print debug info.
2497           if (diContext) {
2498             DILineInfo dli = diContext->getLineInfoForAddress(PC);
2499             // Print valid line info if it changed.
2500             if (dli != lastLine && dli.Line != 0)
2501               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
2502                      << dli.Column;
2503             lastLine = dli;
2504           }
2505           outs() << "\n";
2506         } else {
2507           unsigned int Arch = MachOOF->getArch();
2508           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
2509             outs() << format("\t.byte 0x%02x #bad opcode\n",
2510                              *(Bytes.data() + Index) & 0xff);
2511             Size = 1; // skip exactly one illegible byte and move on.
2512           } else if (Arch == Triple::aarch64) {
2513             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
2514                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
2515                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
2516                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
2517             outs() << format("\t.long\t0x%08x\n", opcode);
2518             Size = 4;
2519           } else {
2520             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2521             if (Size == 0)
2522               Size = 1; // skip illegible bytes
2523           }
2524         }
2525       }
2526     }
2527     if (!symbolTableWorked) {
2528       // Reading the symbol table didn't work, disassemble the whole section.
2529       uint64_t SectAddress = Sections[SectIdx].getAddress();
2530       uint64_t SectSize = Sections[SectIdx].getSize();
2531       uint64_t InstSize;
2532       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
2533         MCInst Inst;
2534
2535         uint64_t PC = SectAddress + Index;
2536         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
2537                                    DebugOut, nulls())) {
2538           if (FullLeadingAddr) {
2539             if (MachOOF->is64Bit())
2540               outs() << format("%016" PRIx64, PC);
2541             else
2542               outs() << format("%08" PRIx64, PC);
2543           } else {
2544             outs() << format("%8" PRIx64 ":", PC);
2545           }
2546           if (!NoShowRawInsn) {
2547             outs() << "\t";
2548             DumpBytes(
2549                 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
2550                           InstSize));
2551           }
2552           IP->printInst(&Inst, outs(), "");
2553           outs() << "\n";
2554         } else {
2555           unsigned int Arch = MachOOF->getArch();
2556           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
2557             outs() << format("\t.byte 0x%02x #bad opcode\n",
2558                              *(Bytes.data() + Index) & 0xff);
2559             InstSize = 1; // skip exactly one illegible byte and move on.
2560           } else {
2561             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2562             if (InstSize == 0)
2563               InstSize = 1; // skip illegible bytes
2564           }
2565         }
2566       }
2567     }
2568     // The TripleName's need to be reset if we are called again for a different
2569     // archtecture.
2570     TripleName = "";
2571     ThumbTripleName = "";
2572
2573     if (SymbolizerInfo.method != nullptr)
2574       free(SymbolizerInfo.method);
2575     if (SymbolizerInfo.demangled_name != nullptr)
2576       free(SymbolizerInfo.demangled_name);
2577     if (SymbolizerInfo.bindtable != nullptr)
2578       delete SymbolizerInfo.bindtable;
2579     if (ThumbSymbolizerInfo.method != nullptr)
2580       free(ThumbSymbolizerInfo.method);
2581     if (ThumbSymbolizerInfo.demangled_name != nullptr)
2582       free(ThumbSymbolizerInfo.demangled_name);
2583     if (ThumbSymbolizerInfo.bindtable != nullptr)
2584       delete ThumbSymbolizerInfo.bindtable;
2585   }
2586 }
2587
2588 //===----------------------------------------------------------------------===//
2589 // __compact_unwind section dumping
2590 //===----------------------------------------------------------------------===//
2591
2592 namespace {
2593
2594 template <typename T> static uint64_t readNext(const char *&Buf) {
2595   using llvm::support::little;
2596   using llvm::support::unaligned;
2597
2598   uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
2599   Buf += sizeof(T);
2600   return Val;
2601 }
2602
2603 struct CompactUnwindEntry {
2604   uint32_t OffsetInSection;
2605
2606   uint64_t FunctionAddr;
2607   uint32_t Length;
2608   uint32_t CompactEncoding;
2609   uint64_t PersonalityAddr;
2610   uint64_t LSDAAddr;
2611
2612   RelocationRef FunctionReloc;
2613   RelocationRef PersonalityReloc;
2614   RelocationRef LSDAReloc;
2615
2616   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
2617       : OffsetInSection(Offset) {
2618     if (Is64)
2619       read<uint64_t>(Contents.data() + Offset);
2620     else
2621       read<uint32_t>(Contents.data() + Offset);
2622   }
2623
2624 private:
2625   template <typename UIntPtr> void read(const char *Buf) {
2626     FunctionAddr = readNext<UIntPtr>(Buf);
2627     Length = readNext<uint32_t>(Buf);
2628     CompactEncoding = readNext<uint32_t>(Buf);
2629     PersonalityAddr = readNext<UIntPtr>(Buf);
2630     LSDAAddr = readNext<UIntPtr>(Buf);
2631   }
2632 };
2633 }
2634
2635 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
2636 /// and data being relocated, determine the best base Name and Addend to use for
2637 /// display purposes.
2638 ///
2639 /// 1. An Extern relocation will directly reference a symbol (and the data is
2640 ///    then already an addend), so use that.
2641 /// 2. Otherwise the data is an offset in the object file's layout; try to find
2642 //     a symbol before it in the same section, and use the offset from there.
2643 /// 3. Finally, if all that fails, fall back to an offset from the start of the
2644 ///    referenced section.
2645 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
2646                                       std::map<uint64_t, SymbolRef> &Symbols,
2647                                       const RelocationRef &Reloc, uint64_t Addr,
2648                                       StringRef &Name, uint64_t &Addend) {
2649   if (Reloc.getSymbol() != Obj->symbol_end()) {
2650     Reloc.getSymbol()->getName(Name);
2651     Addend = Addr;
2652     return;
2653   }
2654
2655   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
2656   SectionRef RelocSection = Obj->getRelocationSection(RE);
2657
2658   uint64_t SectionAddr = RelocSection.getAddress();
2659
2660   auto Sym = Symbols.upper_bound(Addr);
2661   if (Sym == Symbols.begin()) {
2662     // The first symbol in the object is after this reference, the best we can
2663     // do is section-relative notation.
2664     RelocSection.getName(Name);
2665     Addend = Addr - SectionAddr;
2666     return;
2667   }
2668
2669   // Go back one so that SymbolAddress <= Addr.
2670   --Sym;
2671
2672   section_iterator SymSection = Obj->section_end();
2673   Sym->second.getSection(SymSection);
2674   if (RelocSection == *SymSection) {
2675     // There's a valid symbol in the same section before this reference.
2676     Sym->second.getName(Name);
2677     Addend = Addr - Sym->first;
2678     return;
2679   }
2680
2681   // There is a symbol before this reference, but it's in a different
2682   // section. Probably not helpful to mention it, so use the section name.
2683   RelocSection.getName(Name);
2684   Addend = Addr - SectionAddr;
2685 }
2686
2687 static void printUnwindRelocDest(const MachOObjectFile *Obj,
2688                                  std::map<uint64_t, SymbolRef> &Symbols,
2689                                  const RelocationRef &Reloc, uint64_t Addr) {
2690   StringRef Name;
2691   uint64_t Addend;
2692
2693   if (!Reloc.getObjectFile())
2694     return;
2695
2696   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
2697
2698   outs() << Name;
2699   if (Addend)
2700     outs() << " + " << format("0x%" PRIx64, Addend);
2701 }
2702
2703 static void
2704 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
2705                                std::map<uint64_t, SymbolRef> &Symbols,
2706                                const SectionRef &CompactUnwind) {
2707
2708   assert(Obj->isLittleEndian() &&
2709          "There should not be a big-endian .o with __compact_unwind");
2710
2711   bool Is64 = Obj->is64Bit();
2712   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
2713   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
2714
2715   StringRef Contents;
2716   CompactUnwind.getContents(Contents);
2717
2718   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
2719
2720   // First populate the initial raw offsets, encodings and so on from the entry.
2721   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
2722     CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
2723     CompactUnwinds.push_back(Entry);
2724   }
2725
2726   // Next we need to look at the relocations to find out what objects are
2727   // actually being referred to.
2728   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
2729     uint64_t RelocAddress;
2730     Reloc.getOffset(RelocAddress);
2731
2732     uint32_t EntryIdx = RelocAddress / EntrySize;
2733     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
2734     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
2735
2736     if (OffsetInEntry == 0)
2737       Entry.FunctionReloc = Reloc;
2738     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
2739       Entry.PersonalityReloc = Reloc;
2740     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
2741       Entry.LSDAReloc = Reloc;
2742     else
2743       llvm_unreachable("Unexpected relocation in __compact_unwind section");
2744   }
2745
2746   // Finally, we're ready to print the data we've gathered.
2747   outs() << "Contents of __compact_unwind section:\n";
2748   for (auto &Entry : CompactUnwinds) {
2749     outs() << "  Entry at offset "
2750            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
2751
2752     // 1. Start of the region this entry applies to.
2753     outs() << "    start:                " << format("0x%" PRIx64,
2754                                                      Entry.FunctionAddr) << ' ';
2755     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
2756     outs() << '\n';
2757
2758     // 2. Length of the region this entry applies to.
2759     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
2760            << '\n';
2761     // 3. The 32-bit compact encoding.
2762     outs() << "    compact encoding:     "
2763            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
2764
2765     // 4. The personality function, if present.
2766     if (Entry.PersonalityReloc.getObjectFile()) {
2767       outs() << "    personality function: "
2768              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
2769       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
2770                            Entry.PersonalityAddr);
2771       outs() << '\n';
2772     }
2773
2774     // 5. This entry's language-specific data area.
2775     if (Entry.LSDAReloc.getObjectFile()) {
2776       outs() << "    LSDA:                 " << format("0x%" PRIx64,
2777                                                        Entry.LSDAAddr) << ' ';
2778       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
2779       outs() << '\n';
2780     }
2781   }
2782 }
2783
2784 //===----------------------------------------------------------------------===//
2785 // __unwind_info section dumping
2786 //===----------------------------------------------------------------------===//
2787
2788 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
2789   const char *Pos = PageStart;
2790   uint32_t Kind = readNext<uint32_t>(Pos);
2791   (void)Kind;
2792   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
2793
2794   uint16_t EntriesStart = readNext<uint16_t>(Pos);
2795   uint16_t NumEntries = readNext<uint16_t>(Pos);
2796
2797   Pos = PageStart + EntriesStart;
2798   for (unsigned i = 0; i < NumEntries; ++i) {
2799     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2800     uint32_t Encoding = readNext<uint32_t>(Pos);
2801
2802     outs() << "      [" << i << "]: "
2803            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2804            << ", "
2805            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
2806   }
2807 }
2808
2809 static void printCompressedSecondLevelUnwindPage(
2810     const char *PageStart, uint32_t FunctionBase,
2811     const SmallVectorImpl<uint32_t> &CommonEncodings) {
2812   const char *Pos = PageStart;
2813   uint32_t Kind = readNext<uint32_t>(Pos);
2814   (void)Kind;
2815   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
2816
2817   uint16_t EntriesStart = readNext<uint16_t>(Pos);
2818   uint16_t NumEntries = readNext<uint16_t>(Pos);
2819
2820   uint16_t EncodingsStart = readNext<uint16_t>(Pos);
2821   readNext<uint16_t>(Pos);
2822   const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
2823       PageStart + EncodingsStart);
2824
2825   Pos = PageStart + EntriesStart;
2826   for (unsigned i = 0; i < NumEntries; ++i) {
2827     uint32_t Entry = readNext<uint32_t>(Pos);
2828     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
2829     uint32_t EncodingIdx = Entry >> 24;
2830
2831     uint32_t Encoding;
2832     if (EncodingIdx < CommonEncodings.size())
2833       Encoding = CommonEncodings[EncodingIdx];
2834     else
2835       Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
2836
2837     outs() << "      [" << i << "]: "
2838            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2839            << ", "
2840            << "encoding[" << EncodingIdx
2841            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
2842   }
2843 }
2844
2845 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
2846                                         std::map<uint64_t, SymbolRef> &Symbols,
2847                                         const SectionRef &UnwindInfo) {
2848
2849   assert(Obj->isLittleEndian() &&
2850          "There should not be a big-endian .o with __unwind_info");
2851
2852   outs() << "Contents of __unwind_info section:\n";
2853
2854   StringRef Contents;
2855   UnwindInfo.getContents(Contents);
2856   const char *Pos = Contents.data();
2857
2858   //===----------------------------------
2859   // Section header
2860   //===----------------------------------
2861
2862   uint32_t Version = readNext<uint32_t>(Pos);
2863   outs() << "  Version:                                   "
2864          << format("0x%" PRIx32, Version) << '\n';
2865   assert(Version == 1 && "only understand version 1");
2866
2867   uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
2868   outs() << "  Common encodings array section offset:     "
2869          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
2870   uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
2871   outs() << "  Number of common encodings in array:       "
2872          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
2873
2874   uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
2875   outs() << "  Personality function array section offset: "
2876          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
2877   uint32_t NumPersonalities = readNext<uint32_t>(Pos);
2878   outs() << "  Number of personality functions in array:  "
2879          << format("0x%" PRIx32, NumPersonalities) << '\n';
2880
2881   uint32_t IndicesStart = readNext<uint32_t>(Pos);
2882   outs() << "  Index array section offset:                "
2883          << format("0x%" PRIx32, IndicesStart) << '\n';
2884   uint32_t NumIndices = readNext<uint32_t>(Pos);
2885   outs() << "  Number of indices in array:                "
2886          << format("0x%" PRIx32, NumIndices) << '\n';
2887
2888   //===----------------------------------
2889   // A shared list of common encodings
2890   //===----------------------------------
2891
2892   // These occupy indices in the range [0, N] whenever an encoding is referenced
2893   // from a compressed 2nd level index table. In practice the linker only
2894   // creates ~128 of these, so that indices are available to embed encodings in
2895   // the 2nd level index.
2896
2897   SmallVector<uint32_t, 64> CommonEncodings;
2898   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
2899   Pos = Contents.data() + CommonEncodingsStart;
2900   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
2901     uint32_t Encoding = readNext<uint32_t>(Pos);
2902     CommonEncodings.push_back(Encoding);
2903
2904     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
2905            << '\n';
2906   }
2907
2908   //===----------------------------------
2909   // Personality functions used in this executable
2910   //===----------------------------------
2911
2912   // There should be only a handful of these (one per source language,
2913   // roughly). Particularly since they only get 2 bits in the compact encoding.
2914
2915   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
2916   Pos = Contents.data() + PersonalitiesStart;
2917   for (unsigned i = 0; i < NumPersonalities; ++i) {
2918     uint32_t PersonalityFn = readNext<uint32_t>(Pos);
2919     outs() << "    personality[" << i + 1
2920            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
2921   }
2922
2923   //===----------------------------------
2924   // The level 1 index entries
2925   //===----------------------------------
2926
2927   // These specify an approximate place to start searching for the more detailed
2928   // information, sorted by PC.
2929
2930   struct IndexEntry {
2931     uint32_t FunctionOffset;
2932     uint32_t SecondLevelPageStart;
2933     uint32_t LSDAStart;
2934   };
2935
2936   SmallVector<IndexEntry, 4> IndexEntries;
2937
2938   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
2939   Pos = Contents.data() + IndicesStart;
2940   for (unsigned i = 0; i < NumIndices; ++i) {
2941     IndexEntry Entry;
2942
2943     Entry.FunctionOffset = readNext<uint32_t>(Pos);
2944     Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
2945     Entry.LSDAStart = readNext<uint32_t>(Pos);
2946     IndexEntries.push_back(Entry);
2947
2948     outs() << "    [" << i << "]: "
2949            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
2950            << ", "
2951            << "2nd level page offset="
2952            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
2953            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
2954   }
2955
2956   //===----------------------------------
2957   // Next come the LSDA tables
2958   //===----------------------------------
2959
2960   // The LSDA layout is rather implicit: it's a contiguous array of entries from
2961   // the first top-level index's LSDAOffset to the last (sentinel).
2962
2963   outs() << "  LSDA descriptors:\n";
2964   Pos = Contents.data() + IndexEntries[0].LSDAStart;
2965   int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
2966                  (2 * sizeof(uint32_t));
2967   for (int i = 0; i < NumLSDAs; ++i) {
2968     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2969     uint32_t LSDAOffset = readNext<uint32_t>(Pos);
2970     outs() << "    [" << i << "]: "
2971            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2972            << ", "
2973            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
2974   }
2975
2976   //===----------------------------------
2977   // Finally, the 2nd level indices
2978   //===----------------------------------
2979
2980   // Generally these are 4K in size, and have 2 possible forms:
2981   //   + Regular stores up to 511 entries with disparate encodings
2982   //   + Compressed stores up to 1021 entries if few enough compact encoding
2983   //     values are used.
2984   outs() << "  Second level indices:\n";
2985   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
2986     // The final sentinel top-level index has no associated 2nd level page
2987     if (IndexEntries[i].SecondLevelPageStart == 0)
2988       break;
2989
2990     outs() << "    Second level index[" << i << "]: "
2991            << "offset in section="
2992            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
2993            << ", "
2994            << "base function offset="
2995            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
2996
2997     Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
2998     uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
2999     if (Kind == 2)
3000       printRegularSecondLevelUnwindPage(Pos);
3001     else if (Kind == 3)
3002       printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3003                                            CommonEncodings);
3004     else
3005       llvm_unreachable("Do not know how to print this kind of 2nd level page");
3006   }
3007 }
3008
3009 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3010   std::map<uint64_t, SymbolRef> Symbols;
3011   for (const SymbolRef &SymRef : Obj->symbols()) {
3012     // Discard any undefined or absolute symbols. They're not going to take part
3013     // in the convenience lookup for unwind info and just take up resources.
3014     section_iterator Section = Obj->section_end();
3015     SymRef.getSection(Section);
3016     if (Section == Obj->section_end())
3017       continue;
3018
3019     uint64_t Addr;
3020     SymRef.getAddress(Addr);
3021     Symbols.insert(std::make_pair(Addr, SymRef));
3022   }
3023
3024   for (const SectionRef &Section : Obj->sections()) {
3025     StringRef SectName;
3026     Section.getName(SectName);
3027     if (SectName == "__compact_unwind")
3028       printMachOCompactUnwindSection(Obj, Symbols, Section);
3029     else if (SectName == "__unwind_info")
3030       printMachOUnwindInfoSection(Obj, Symbols, Section);
3031     else if (SectName == "__eh_frame")
3032       outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3033   }
3034 }
3035
3036 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3037                             uint32_t cpusubtype, uint32_t filetype,
3038                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3039                             bool verbose) {
3040   outs() << "Mach header\n";
3041   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
3042             "sizeofcmds      flags\n";
3043   if (verbose) {
3044     if (magic == MachO::MH_MAGIC)
3045       outs() << "   MH_MAGIC";
3046     else if (magic == MachO::MH_MAGIC_64)
3047       outs() << "MH_MAGIC_64";
3048     else
3049       outs() << format(" 0x%08" PRIx32, magic);
3050     switch (cputype) {
3051     case MachO::CPU_TYPE_I386:
3052       outs() << "    I386";
3053       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3054       case MachO::CPU_SUBTYPE_I386_ALL:
3055         outs() << "        ALL";
3056         break;
3057       default:
3058         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3059         break;
3060       }
3061       break;
3062     case MachO::CPU_TYPE_X86_64:
3063       outs() << "  X86_64";
3064       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3065       case MachO::CPU_SUBTYPE_X86_64_ALL:
3066         outs() << "        ALL";
3067         break;
3068       case MachO::CPU_SUBTYPE_X86_64_H:
3069         outs() << "    Haswell";
3070         break;
3071       default:
3072         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3073         break;
3074       }
3075       break;
3076     case MachO::CPU_TYPE_ARM:
3077       outs() << "     ARM";
3078       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3079       case MachO::CPU_SUBTYPE_ARM_ALL:
3080         outs() << "        ALL";
3081         break;
3082       case MachO::CPU_SUBTYPE_ARM_V4T:
3083         outs() << "        V4T";
3084         break;
3085       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3086         outs() << "      V5TEJ";
3087         break;
3088       case MachO::CPU_SUBTYPE_ARM_XSCALE:
3089         outs() << "     XSCALE";
3090         break;
3091       case MachO::CPU_SUBTYPE_ARM_V6:
3092         outs() << "         V6";
3093         break;
3094       case MachO::CPU_SUBTYPE_ARM_V6M:
3095         outs() << "        V6M";
3096         break;
3097       case MachO::CPU_SUBTYPE_ARM_V7:
3098         outs() << "         V7";
3099         break;
3100       case MachO::CPU_SUBTYPE_ARM_V7EM:
3101         outs() << "       V7EM";
3102         break;
3103       case MachO::CPU_SUBTYPE_ARM_V7K:
3104         outs() << "        V7K";
3105         break;
3106       case MachO::CPU_SUBTYPE_ARM_V7M:
3107         outs() << "        V7M";
3108         break;
3109       case MachO::CPU_SUBTYPE_ARM_V7S:
3110         outs() << "        V7S";
3111         break;
3112       default:
3113         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3114         break;
3115       }
3116       break;
3117     case MachO::CPU_TYPE_ARM64:
3118       outs() << "   ARM64";
3119       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3120       case MachO::CPU_SUBTYPE_ARM64_ALL:
3121         outs() << "        ALL";
3122         break;
3123       default:
3124         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3125         break;
3126       }
3127       break;
3128     case MachO::CPU_TYPE_POWERPC:
3129       outs() << "     PPC";
3130       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3131       case MachO::CPU_SUBTYPE_POWERPC_ALL:
3132         outs() << "        ALL";
3133         break;
3134       default:
3135         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3136         break;
3137       }
3138       break;
3139     case MachO::CPU_TYPE_POWERPC64:
3140       outs() << "   PPC64";
3141       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3142       case MachO::CPU_SUBTYPE_POWERPC_ALL:
3143         outs() << "        ALL";
3144         break;
3145       default:
3146         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3147         break;
3148       }
3149       break;
3150     }
3151     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
3152       outs() << " LIB64";
3153     } else {
3154       outs() << format("  0x%02" PRIx32,
3155                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3156     }
3157     switch (filetype) {
3158     case MachO::MH_OBJECT:
3159       outs() << "      OBJECT";
3160       break;
3161     case MachO::MH_EXECUTE:
3162       outs() << "     EXECUTE";
3163       break;
3164     case MachO::MH_FVMLIB:
3165       outs() << "      FVMLIB";
3166       break;
3167     case MachO::MH_CORE:
3168       outs() << "        CORE";
3169       break;
3170     case MachO::MH_PRELOAD:
3171       outs() << "     PRELOAD";
3172       break;
3173     case MachO::MH_DYLIB:
3174       outs() << "       DYLIB";
3175       break;
3176     case MachO::MH_DYLIB_STUB:
3177       outs() << "  DYLIB_STUB";
3178       break;
3179     case MachO::MH_DYLINKER:
3180       outs() << "    DYLINKER";
3181       break;
3182     case MachO::MH_BUNDLE:
3183       outs() << "      BUNDLE";
3184       break;
3185     case MachO::MH_DSYM:
3186       outs() << "        DSYM";
3187       break;
3188     case MachO::MH_KEXT_BUNDLE:
3189       outs() << "  KEXTBUNDLE";
3190       break;
3191     default:
3192       outs() << format("  %10u", filetype);
3193       break;
3194     }
3195     outs() << format(" %5u", ncmds);
3196     outs() << format(" %10u", sizeofcmds);
3197     uint32_t f = flags;
3198     if (f & MachO::MH_NOUNDEFS) {
3199       outs() << "   NOUNDEFS";
3200       f &= ~MachO::MH_NOUNDEFS;
3201     }
3202     if (f & MachO::MH_INCRLINK) {
3203       outs() << " INCRLINK";
3204       f &= ~MachO::MH_INCRLINK;
3205     }
3206     if (f & MachO::MH_DYLDLINK) {
3207       outs() << " DYLDLINK";
3208       f &= ~MachO::MH_DYLDLINK;
3209     }
3210     if (f & MachO::MH_BINDATLOAD) {
3211       outs() << " BINDATLOAD";
3212       f &= ~MachO::MH_BINDATLOAD;
3213     }
3214     if (f & MachO::MH_PREBOUND) {
3215       outs() << " PREBOUND";
3216       f &= ~MachO::MH_PREBOUND;
3217     }
3218     if (f & MachO::MH_SPLIT_SEGS) {
3219       outs() << " SPLIT_SEGS";
3220       f &= ~MachO::MH_SPLIT_SEGS;
3221     }
3222     if (f & MachO::MH_LAZY_INIT) {
3223       outs() << " LAZY_INIT";
3224       f &= ~MachO::MH_LAZY_INIT;
3225     }
3226     if (f & MachO::MH_TWOLEVEL) {
3227       outs() << " TWOLEVEL";
3228       f &= ~MachO::MH_TWOLEVEL;
3229     }
3230     if (f & MachO::MH_FORCE_FLAT) {
3231       outs() << " FORCE_FLAT";
3232       f &= ~MachO::MH_FORCE_FLAT;
3233     }
3234     if (f & MachO::MH_NOMULTIDEFS) {
3235       outs() << " NOMULTIDEFS";
3236       f &= ~MachO::MH_NOMULTIDEFS;
3237     }
3238     if (f & MachO::MH_NOFIXPREBINDING) {
3239       outs() << " NOFIXPREBINDING";
3240       f &= ~MachO::MH_NOFIXPREBINDING;
3241     }
3242     if (f & MachO::MH_PREBINDABLE) {
3243       outs() << " PREBINDABLE";
3244       f &= ~MachO::MH_PREBINDABLE;
3245     }
3246     if (f & MachO::MH_ALLMODSBOUND) {
3247       outs() << " ALLMODSBOUND";
3248       f &= ~MachO::MH_ALLMODSBOUND;
3249     }
3250     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
3251       outs() << " SUBSECTIONS_VIA_SYMBOLS";
3252       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
3253     }
3254     if (f & MachO::MH_CANONICAL) {
3255       outs() << " CANONICAL";
3256       f &= ~MachO::MH_CANONICAL;
3257     }
3258     if (f & MachO::MH_WEAK_DEFINES) {
3259       outs() << " WEAK_DEFINES";
3260       f &= ~MachO::MH_WEAK_DEFINES;
3261     }
3262     if (f & MachO::MH_BINDS_TO_WEAK) {
3263       outs() << " BINDS_TO_WEAK";
3264       f &= ~MachO::MH_BINDS_TO_WEAK;
3265     }
3266     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
3267       outs() << " ALLOW_STACK_EXECUTION";
3268       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
3269     }
3270     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
3271       outs() << " DEAD_STRIPPABLE_DYLIB";
3272       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
3273     }
3274     if (f & MachO::MH_PIE) {
3275       outs() << " PIE";
3276       f &= ~MachO::MH_PIE;
3277     }
3278     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
3279       outs() << " NO_REEXPORTED_DYLIBS";
3280       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
3281     }
3282     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
3283       outs() << " MH_HAS_TLV_DESCRIPTORS";
3284       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
3285     }
3286     if (f & MachO::MH_NO_HEAP_EXECUTION) {
3287       outs() << " MH_NO_HEAP_EXECUTION";
3288       f &= ~MachO::MH_NO_HEAP_EXECUTION;
3289     }
3290     if (f & MachO::MH_APP_EXTENSION_SAFE) {
3291       outs() << " APP_EXTENSION_SAFE";
3292       f &= ~MachO::MH_APP_EXTENSION_SAFE;
3293     }
3294     if (f != 0 || flags == 0)
3295       outs() << format(" 0x%08" PRIx32, f);
3296   } else {
3297     outs() << format(" 0x%08" PRIx32, magic);
3298     outs() << format(" %7d", cputype);
3299     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3300     outs() << format("  0x%02" PRIx32,
3301                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3302     outs() << format("  %10u", filetype);
3303     outs() << format(" %5u", ncmds);
3304     outs() << format(" %10u", sizeofcmds);
3305     outs() << format(" 0x%08" PRIx32, flags);
3306   }
3307   outs() << "\n";
3308 }
3309
3310 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
3311                                 StringRef SegName, uint64_t vmaddr,
3312                                 uint64_t vmsize, uint64_t fileoff,
3313                                 uint64_t filesize, uint32_t maxprot,
3314                                 uint32_t initprot, uint32_t nsects,
3315                                 uint32_t flags, uint32_t object_size,
3316                                 bool verbose) {
3317   uint64_t expected_cmdsize;
3318   if (cmd == MachO::LC_SEGMENT) {
3319     outs() << "      cmd LC_SEGMENT\n";
3320     expected_cmdsize = nsects;
3321     expected_cmdsize *= sizeof(struct MachO::section);
3322     expected_cmdsize += sizeof(struct MachO::segment_command);
3323   } else {
3324     outs() << "      cmd LC_SEGMENT_64\n";
3325     expected_cmdsize = nsects;
3326     expected_cmdsize *= sizeof(struct MachO::section_64);
3327     expected_cmdsize += sizeof(struct MachO::segment_command_64);
3328   }
3329   outs() << "  cmdsize " << cmdsize;
3330   if (cmdsize != expected_cmdsize)
3331     outs() << " Inconsistent size\n";
3332   else
3333     outs() << "\n";
3334   outs() << "  segname " << SegName << "\n";
3335   if (cmd == MachO::LC_SEGMENT_64) {
3336     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
3337     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
3338   } else {
3339     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
3340     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
3341   }
3342   outs() << "  fileoff " << fileoff;
3343   if (fileoff > object_size)
3344     outs() << " (past end of file)\n";
3345   else
3346     outs() << "\n";
3347   outs() << " filesize " << filesize;
3348   if (fileoff + filesize > object_size)
3349     outs() << " (past end of file)\n";
3350   else
3351     outs() << "\n";
3352   if (verbose) {
3353     if ((maxprot &
3354          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3355            MachO::VM_PROT_EXECUTE)) != 0)
3356       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
3357     else {
3358       if (maxprot & MachO::VM_PROT_READ)
3359         outs() << "  maxprot r";
3360       else
3361         outs() << "  maxprot -";
3362       if (maxprot & MachO::VM_PROT_WRITE)
3363         outs() << "w";
3364       else
3365         outs() << "-";
3366       if (maxprot & MachO::VM_PROT_EXECUTE)
3367         outs() << "x\n";
3368       else
3369         outs() << "-\n";
3370     }
3371     if ((initprot &
3372          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3373            MachO::VM_PROT_EXECUTE)) != 0)
3374       outs() << "  initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
3375     else {
3376       if (initprot & MachO::VM_PROT_READ)
3377         outs() << " initprot r";
3378       else
3379         outs() << " initprot -";
3380       if (initprot & MachO::VM_PROT_WRITE)
3381         outs() << "w";
3382       else
3383         outs() << "-";
3384       if (initprot & MachO::VM_PROT_EXECUTE)
3385         outs() << "x\n";
3386       else
3387         outs() << "-\n";
3388     }
3389   } else {
3390     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
3391     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
3392   }
3393   outs() << "   nsects " << nsects << "\n";
3394   if (verbose) {
3395     outs() << "    flags";
3396     if (flags == 0)
3397       outs() << " (none)\n";
3398     else {
3399       if (flags & MachO::SG_HIGHVM) {
3400         outs() << " HIGHVM";
3401         flags &= ~MachO::SG_HIGHVM;
3402       }
3403       if (flags & MachO::SG_FVMLIB) {
3404         outs() << " FVMLIB";
3405         flags &= ~MachO::SG_FVMLIB;
3406       }
3407       if (flags & MachO::SG_NORELOC) {
3408         outs() << " NORELOC";
3409         flags &= ~MachO::SG_NORELOC;
3410       }
3411       if (flags & MachO::SG_PROTECTED_VERSION_1) {
3412         outs() << " PROTECTED_VERSION_1";
3413         flags &= ~MachO::SG_PROTECTED_VERSION_1;
3414       }
3415       if (flags)
3416         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
3417       else
3418         outs() << "\n";
3419     }
3420   } else {
3421     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
3422   }
3423 }
3424
3425 static void PrintSection(const char *sectname, const char *segname,
3426                          uint64_t addr, uint64_t size, uint32_t offset,
3427                          uint32_t align, uint32_t reloff, uint32_t nreloc,
3428                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
3429                          uint32_t cmd, const char *sg_segname,
3430                          uint32_t filetype, uint32_t object_size,
3431                          bool verbose) {
3432   outs() << "Section\n";
3433   outs() << "  sectname " << format("%.16s\n", sectname);
3434   outs() << "   segname " << format("%.16s", segname);
3435   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
3436     outs() << " (does not match segment)\n";
3437   else
3438     outs() << "\n";
3439   if (cmd == MachO::LC_SEGMENT_64) {
3440     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
3441     outs() << "      size " << format("0x%016" PRIx64, size);
3442   } else {
3443     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
3444     outs() << "      size " << format("0x%08" PRIx64, size);
3445   }
3446   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
3447     outs() << " (past end of file)\n";
3448   else
3449     outs() << "\n";
3450   outs() << "    offset " << offset;
3451   if (offset > object_size)
3452     outs() << " (past end of file)\n";
3453   else
3454     outs() << "\n";
3455   uint32_t align_shifted = 1 << align;
3456   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
3457   outs() << "    reloff " << reloff;
3458   if (reloff > object_size)
3459     outs() << " (past end of file)\n";
3460   else
3461     outs() << "\n";
3462   outs() << "    nreloc " << nreloc;
3463   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
3464     outs() << " (past end of file)\n";
3465   else
3466     outs() << "\n";
3467   uint32_t section_type = flags & MachO::SECTION_TYPE;
3468   if (verbose) {
3469     outs() << "      type";
3470     if (section_type == MachO::S_REGULAR)
3471       outs() << " S_REGULAR\n";
3472     else if (section_type == MachO::S_ZEROFILL)
3473       outs() << " S_ZEROFILL\n";
3474     else if (section_type == MachO::S_CSTRING_LITERALS)
3475       outs() << " S_CSTRING_LITERALS\n";
3476     else if (section_type == MachO::S_4BYTE_LITERALS)
3477       outs() << " S_4BYTE_LITERALS\n";
3478     else if (section_type == MachO::S_8BYTE_LITERALS)
3479       outs() << " S_8BYTE_LITERALS\n";
3480     else if (section_type == MachO::S_16BYTE_LITERALS)
3481       outs() << " S_16BYTE_LITERALS\n";
3482     else if (section_type == MachO::S_LITERAL_POINTERS)
3483       outs() << " S_LITERAL_POINTERS\n";
3484     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
3485       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
3486     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
3487       outs() << " S_LAZY_SYMBOL_POINTERS\n";
3488     else if (section_type == MachO::S_SYMBOL_STUBS)
3489       outs() << " S_SYMBOL_STUBS\n";
3490     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
3491       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
3492     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
3493       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
3494     else if (section_type == MachO::S_COALESCED)
3495       outs() << " S_COALESCED\n";
3496     else if (section_type == MachO::S_INTERPOSING)
3497       outs() << " S_INTERPOSING\n";
3498     else if (section_type == MachO::S_DTRACE_DOF)
3499       outs() << " S_DTRACE_DOF\n";
3500     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
3501       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
3502     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
3503       outs() << " S_THREAD_LOCAL_REGULAR\n";
3504     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
3505       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
3506     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
3507       outs() << " S_THREAD_LOCAL_VARIABLES\n";
3508     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3509       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
3510     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
3511       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
3512     else
3513       outs() << format("0x%08" PRIx32, section_type) << "\n";
3514     outs() << "attributes";
3515     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
3516     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
3517       outs() << " PURE_INSTRUCTIONS";
3518     if (section_attributes & MachO::S_ATTR_NO_TOC)
3519       outs() << " NO_TOC";
3520     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
3521       outs() << " STRIP_STATIC_SYMS";
3522     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
3523       outs() << " NO_DEAD_STRIP";
3524     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
3525       outs() << " LIVE_SUPPORT";
3526     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
3527       outs() << " SELF_MODIFYING_CODE";
3528     if (section_attributes & MachO::S_ATTR_DEBUG)
3529       outs() << " DEBUG";
3530     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
3531       outs() << " SOME_INSTRUCTIONS";
3532     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
3533       outs() << " EXT_RELOC";
3534     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
3535       outs() << " LOC_RELOC";
3536     if (section_attributes == 0)
3537       outs() << " (none)";
3538     outs() << "\n";
3539   } else
3540     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
3541   outs() << " reserved1 " << reserved1;
3542   if (section_type == MachO::S_SYMBOL_STUBS ||
3543       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3544       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3545       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3546       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3547     outs() << " (index into indirect symbol table)\n";
3548   else
3549     outs() << "\n";
3550   outs() << " reserved2 " << reserved2;
3551   if (section_type == MachO::S_SYMBOL_STUBS)
3552     outs() << " (size of stubs)\n";
3553   else
3554     outs() << "\n";
3555 }
3556
3557 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
3558                                    uint32_t object_size) {
3559   outs() << "     cmd LC_SYMTAB\n";
3560   outs() << " cmdsize " << st.cmdsize;
3561   if (st.cmdsize != sizeof(struct MachO::symtab_command))
3562     outs() << " Incorrect size\n";
3563   else
3564     outs() << "\n";
3565   outs() << "  symoff " << st.symoff;
3566   if (st.symoff > object_size)
3567     outs() << " (past end of file)\n";
3568   else
3569     outs() << "\n";
3570   outs() << "   nsyms " << st.nsyms;
3571   uint64_t big_size;
3572   if (Is64Bit) {
3573     big_size = st.nsyms;
3574     big_size *= sizeof(struct MachO::nlist_64);
3575     big_size += st.symoff;
3576     if (big_size > object_size)
3577       outs() << " (past end of file)\n";
3578     else
3579       outs() << "\n";
3580   } else {
3581     big_size = st.nsyms;
3582     big_size *= sizeof(struct MachO::nlist);
3583     big_size += st.symoff;
3584     if (big_size > object_size)
3585       outs() << " (past end of file)\n";
3586     else
3587       outs() << "\n";
3588   }
3589   outs() << "  stroff " << st.stroff;
3590   if (st.stroff > object_size)
3591     outs() << " (past end of file)\n";
3592   else
3593     outs() << "\n";
3594   outs() << " strsize " << st.strsize;
3595   big_size = st.stroff;
3596   big_size += st.strsize;
3597   if (big_size > object_size)
3598     outs() << " (past end of file)\n";
3599   else
3600     outs() << "\n";
3601 }
3602
3603 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
3604                                      uint32_t nsyms, uint32_t object_size,
3605                                      bool Is64Bit) {
3606   outs() << "            cmd LC_DYSYMTAB\n";
3607   outs() << "        cmdsize " << dyst.cmdsize;
3608   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
3609     outs() << " Incorrect size\n";
3610   else
3611     outs() << "\n";
3612   outs() << "      ilocalsym " << dyst.ilocalsym;
3613   if (dyst.ilocalsym > nsyms)
3614     outs() << " (greater than the number of symbols)\n";
3615   else
3616     outs() << "\n";
3617   outs() << "      nlocalsym " << dyst.nlocalsym;
3618   uint64_t big_size;
3619   big_size = dyst.ilocalsym;
3620   big_size += dyst.nlocalsym;
3621   if (big_size > nsyms)
3622     outs() << " (past the end of the symbol table)\n";
3623   else
3624     outs() << "\n";
3625   outs() << "     iextdefsym " << dyst.iextdefsym;
3626   if (dyst.iextdefsym > nsyms)
3627     outs() << " (greater than the number of symbols)\n";
3628   else
3629     outs() << "\n";
3630   outs() << "     nextdefsym " << dyst.nextdefsym;
3631   big_size = dyst.iextdefsym;
3632   big_size += dyst.nextdefsym;
3633   if (big_size > nsyms)
3634     outs() << " (past the end of the symbol table)\n";
3635   else
3636     outs() << "\n";
3637   outs() << "      iundefsym " << dyst.iundefsym;
3638   if (dyst.iundefsym > nsyms)
3639     outs() << " (greater than the number of symbols)\n";
3640   else
3641     outs() << "\n";
3642   outs() << "      nundefsym " << dyst.nundefsym;
3643   big_size = dyst.iundefsym;
3644   big_size += dyst.nundefsym;
3645   if (big_size > nsyms)
3646     outs() << " (past the end of the symbol table)\n";
3647   else
3648     outs() << "\n";
3649   outs() << "         tocoff " << dyst.tocoff;
3650   if (dyst.tocoff > object_size)
3651     outs() << " (past end of file)\n";
3652   else
3653     outs() << "\n";
3654   outs() << "           ntoc " << dyst.ntoc;
3655   big_size = dyst.ntoc;
3656   big_size *= sizeof(struct MachO::dylib_table_of_contents);
3657   big_size += dyst.tocoff;
3658   if (big_size > object_size)
3659     outs() << " (past end of file)\n";
3660   else
3661     outs() << "\n";
3662   outs() << "      modtaboff " << dyst.modtaboff;
3663   if (dyst.modtaboff > object_size)
3664     outs() << " (past end of file)\n";
3665   else
3666     outs() << "\n";
3667   outs() << "        nmodtab " << dyst.nmodtab;
3668   uint64_t modtabend;
3669   if (Is64Bit) {
3670     modtabend = dyst.nmodtab;
3671     modtabend *= sizeof(struct MachO::dylib_module_64);
3672     modtabend += dyst.modtaboff;
3673   } else {
3674     modtabend = dyst.nmodtab;
3675     modtabend *= sizeof(struct MachO::dylib_module);
3676     modtabend += dyst.modtaboff;
3677   }
3678   if (modtabend > object_size)
3679     outs() << " (past end of file)\n";
3680   else
3681     outs() << "\n";
3682   outs() << "   extrefsymoff " << dyst.extrefsymoff;
3683   if (dyst.extrefsymoff > object_size)
3684     outs() << " (past end of file)\n";
3685   else
3686     outs() << "\n";
3687   outs() << "    nextrefsyms " << dyst.nextrefsyms;
3688   big_size = dyst.nextrefsyms;
3689   big_size *= sizeof(struct MachO::dylib_reference);
3690   big_size += dyst.extrefsymoff;
3691   if (big_size > object_size)
3692     outs() << " (past end of file)\n";
3693   else
3694     outs() << "\n";
3695   outs() << " indirectsymoff " << dyst.indirectsymoff;
3696   if (dyst.indirectsymoff > object_size)
3697     outs() << " (past end of file)\n";
3698   else
3699     outs() << "\n";
3700   outs() << "  nindirectsyms " << dyst.nindirectsyms;
3701   big_size = dyst.nindirectsyms;
3702   big_size *= sizeof(uint32_t);
3703   big_size += dyst.indirectsymoff;
3704   if (big_size > object_size)
3705     outs() << " (past end of file)\n";
3706   else
3707     outs() << "\n";
3708   outs() << "      extreloff " << dyst.extreloff;
3709   if (dyst.extreloff > object_size)
3710     outs() << " (past end of file)\n";
3711   else
3712     outs() << "\n";
3713   outs() << "        nextrel " << dyst.nextrel;
3714   big_size = dyst.nextrel;
3715   big_size *= sizeof(struct MachO::relocation_info);
3716   big_size += dyst.extreloff;
3717   if (big_size > object_size)
3718     outs() << " (past end of file)\n";
3719   else
3720     outs() << "\n";
3721   outs() << "      locreloff " << dyst.locreloff;
3722   if (dyst.locreloff > object_size)
3723     outs() << " (past end of file)\n";
3724   else
3725     outs() << "\n";
3726   outs() << "        nlocrel " << dyst.nlocrel;
3727   big_size = dyst.nlocrel;
3728   big_size *= sizeof(struct MachO::relocation_info);
3729   big_size += dyst.locreloff;
3730   if (big_size > object_size)
3731     outs() << " (past end of file)\n";
3732   else
3733     outs() << "\n";
3734 }
3735
3736 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
3737                                      uint32_t object_size) {
3738   if (dc.cmd == MachO::LC_DYLD_INFO)
3739     outs() << "            cmd LC_DYLD_INFO\n";
3740   else
3741     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
3742   outs() << "        cmdsize " << dc.cmdsize;
3743   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
3744     outs() << " Incorrect size\n";
3745   else
3746     outs() << "\n";
3747   outs() << "     rebase_off " << dc.rebase_off;
3748   if (dc.rebase_off > object_size)
3749     outs() << " (past end of file)\n";
3750   else
3751     outs() << "\n";
3752   outs() << "    rebase_size " << dc.rebase_size;
3753   uint64_t big_size;
3754   big_size = dc.rebase_off;
3755   big_size += dc.rebase_size;
3756   if (big_size > object_size)
3757     outs() << " (past end of file)\n";
3758   else
3759     outs() << "\n";
3760   outs() << "       bind_off " << dc.bind_off;
3761   if (dc.bind_off > object_size)
3762     outs() << " (past end of file)\n";
3763   else
3764     outs() << "\n";
3765   outs() << "      bind_size " << dc.bind_size;
3766   big_size = dc.bind_off;
3767   big_size += dc.bind_size;
3768   if (big_size > object_size)
3769     outs() << " (past end of file)\n";
3770   else
3771     outs() << "\n";
3772   outs() << "  weak_bind_off " << dc.weak_bind_off;
3773   if (dc.weak_bind_off > object_size)
3774     outs() << " (past end of file)\n";
3775   else
3776     outs() << "\n";
3777   outs() << " weak_bind_size " << dc.weak_bind_size;
3778   big_size = dc.weak_bind_off;
3779   big_size += dc.weak_bind_size;
3780   if (big_size > object_size)
3781     outs() << " (past end of file)\n";
3782   else
3783     outs() << "\n";
3784   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
3785   if (dc.lazy_bind_off > object_size)
3786     outs() << " (past end of file)\n";
3787   else
3788     outs() << "\n";
3789   outs() << " lazy_bind_size " << dc.lazy_bind_size;
3790   big_size = dc.lazy_bind_off;
3791   big_size += dc.lazy_bind_size;
3792   if (big_size > object_size)
3793     outs() << " (past end of file)\n";
3794   else
3795     outs() << "\n";
3796   outs() << "     export_off " << dc.export_off;
3797   if (dc.export_off > object_size)
3798     outs() << " (past end of file)\n";
3799   else
3800     outs() << "\n";
3801   outs() << "    export_size " << dc.export_size;
3802   big_size = dc.export_off;
3803   big_size += dc.export_size;
3804   if (big_size > object_size)
3805     outs() << " (past end of file)\n";
3806   else
3807     outs() << "\n";
3808 }
3809
3810 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
3811                                  const char *Ptr) {
3812   if (dyld.cmd == MachO::LC_ID_DYLINKER)
3813     outs() << "          cmd LC_ID_DYLINKER\n";
3814   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
3815     outs() << "          cmd LC_LOAD_DYLINKER\n";
3816   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
3817     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
3818   else
3819     outs() << "          cmd ?(" << dyld.cmd << ")\n";
3820   outs() << "      cmdsize " << dyld.cmdsize;
3821   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
3822     outs() << " Incorrect size\n";
3823   else
3824     outs() << "\n";
3825   if (dyld.name >= dyld.cmdsize)
3826     outs() << "         name ?(bad offset " << dyld.name << ")\n";
3827   else {
3828     const char *P = (const char *)(Ptr) + dyld.name;
3829     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
3830   }
3831 }
3832
3833 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
3834   outs() << "     cmd LC_UUID\n";
3835   outs() << " cmdsize " << uuid.cmdsize;
3836   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
3837     outs() << " Incorrect size\n";
3838   else
3839     outs() << "\n";
3840   outs() << "    uuid ";
3841   outs() << format("%02" PRIX32, uuid.uuid[0]);
3842   outs() << format("%02" PRIX32, uuid.uuid[1]);
3843   outs() << format("%02" PRIX32, uuid.uuid[2]);
3844   outs() << format("%02" PRIX32, uuid.uuid[3]);
3845   outs() << "-";
3846   outs() << format("%02" PRIX32, uuid.uuid[4]);
3847   outs() << format("%02" PRIX32, uuid.uuid[5]);
3848   outs() << "-";
3849   outs() << format("%02" PRIX32, uuid.uuid[6]);
3850   outs() << format("%02" PRIX32, uuid.uuid[7]);
3851   outs() << "-";
3852   outs() << format("%02" PRIX32, uuid.uuid[8]);
3853   outs() << format("%02" PRIX32, uuid.uuid[9]);
3854   outs() << "-";
3855   outs() << format("%02" PRIX32, uuid.uuid[10]);
3856   outs() << format("%02" PRIX32, uuid.uuid[11]);
3857   outs() << format("%02" PRIX32, uuid.uuid[12]);
3858   outs() << format("%02" PRIX32, uuid.uuid[13]);
3859   outs() << format("%02" PRIX32, uuid.uuid[14]);
3860   outs() << format("%02" PRIX32, uuid.uuid[15]);
3861   outs() << "\n";
3862 }
3863
3864 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
3865   outs() << "          cmd LC_RPATH\n";
3866   outs() << "      cmdsize " << rpath.cmdsize;
3867   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
3868     outs() << " Incorrect size\n";
3869   else
3870     outs() << "\n";
3871   if (rpath.path >= rpath.cmdsize)
3872     outs() << "         path ?(bad offset " << rpath.path << ")\n";
3873   else {
3874     const char *P = (const char *)(Ptr) + rpath.path;
3875     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
3876   }
3877 }
3878
3879 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
3880   if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
3881     outs() << "      cmd LC_VERSION_MIN_MACOSX\n";
3882   else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
3883     outs() << "      cmd LC_VERSION_MIN_IPHONEOS\n";
3884   else
3885     outs() << "      cmd " << vd.cmd << " (?)\n";
3886   outs() << "  cmdsize " << vd.cmdsize;
3887   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
3888     outs() << " Incorrect size\n";
3889   else
3890     outs() << "\n";
3891   outs() << "  version " << ((vd.version >> 16) & 0xffff) << "."
3892          << ((vd.version >> 8) & 0xff);
3893   if ((vd.version & 0xff) != 0)
3894     outs() << "." << (vd.version & 0xff);
3895   outs() << "\n";
3896   if (vd.sdk == 0)
3897     outs() << "      sdk n/a";
3898   else {
3899     outs() << "      sdk " << ((vd.sdk >> 16) & 0xffff) << "."
3900            << ((vd.sdk >> 8) & 0xff);
3901   }
3902   if ((vd.sdk & 0xff) != 0)
3903     outs() << "." << (vd.sdk & 0xff);
3904   outs() << "\n";
3905 }
3906
3907 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
3908   outs() << "      cmd LC_SOURCE_VERSION\n";
3909   outs() << "  cmdsize " << sd.cmdsize;
3910   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
3911     outs() << " Incorrect size\n";
3912   else
3913     outs() << "\n";
3914   uint64_t a = (sd.version >> 40) & 0xffffff;
3915   uint64_t b = (sd.version >> 30) & 0x3ff;
3916   uint64_t c = (sd.version >> 20) & 0x3ff;
3917   uint64_t d = (sd.version >> 10) & 0x3ff;
3918   uint64_t e = sd.version & 0x3ff;
3919   outs() << "  version " << a << "." << b;
3920   if (e != 0)
3921     outs() << "." << c << "." << d << "." << e;
3922   else if (d != 0)
3923     outs() << "." << c << "." << d;
3924   else if (c != 0)
3925     outs() << "." << c;
3926   outs() << "\n";
3927 }
3928
3929 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
3930   outs() << "       cmd LC_MAIN\n";
3931   outs() << "   cmdsize " << ep.cmdsize;
3932   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
3933     outs() << " Incorrect size\n";
3934   else
3935     outs() << "\n";
3936   outs() << "  entryoff " << ep.entryoff << "\n";
3937   outs() << " stacksize " << ep.stacksize << "\n";
3938 }
3939
3940 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
3941                                        uint32_t object_size) {
3942   outs() << "          cmd LC_ENCRYPTION_INFO\n";
3943   outs() << "      cmdsize " << ec.cmdsize;
3944   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
3945     outs() << " Incorrect size\n";
3946   else
3947     outs() << "\n";
3948   outs() << "     cryptoff " << ec.cryptoff;
3949   if (ec.cryptoff > object_size)
3950     outs() << " (past end of file)\n";
3951   else
3952     outs() << "\n";
3953   outs() << "    cryptsize " << ec.cryptsize;
3954   if (ec.cryptsize > object_size)
3955     outs() << " (past end of file)\n";
3956   else
3957     outs() << "\n";
3958   outs() << "      cryptid " << ec.cryptid << "\n";
3959 }
3960
3961 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
3962                                          uint32_t object_size) {
3963   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
3964   outs() << "      cmdsize " << ec.cmdsize;
3965   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
3966     outs() << " Incorrect size\n";
3967   else
3968     outs() << "\n";
3969   outs() << "     cryptoff " << ec.cryptoff;
3970   if (ec.cryptoff > object_size)
3971     outs() << " (past end of file)\n";
3972   else
3973     outs() << "\n";
3974   outs() << "    cryptsize " << ec.cryptsize;
3975   if (ec.cryptsize > object_size)
3976     outs() << " (past end of file)\n";
3977   else
3978     outs() << "\n";
3979   outs() << "      cryptid " << ec.cryptid << "\n";
3980   outs() << "          pad " << ec.pad << "\n";
3981 }
3982
3983 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
3984                                      const char *Ptr) {
3985   outs() << "     cmd LC_LINKER_OPTION\n";
3986   outs() << " cmdsize " << lo.cmdsize;
3987   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
3988     outs() << " Incorrect size\n";
3989   else
3990     outs() << "\n";
3991   outs() << "   count " << lo.count << "\n";
3992   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
3993   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
3994   uint32_t i = 0;
3995   while (left > 0) {
3996     while (*string == '\0' && left > 0) {
3997       string++;
3998       left--;
3999     }
4000     if (left > 0) {
4001       i++;
4002       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
4003       uint32_t NullPos = StringRef(string, left).find('\0');
4004       uint32_t len = std::min(NullPos, left) + 1;
4005       string += len;
4006       left -= len;
4007     }
4008   }
4009   if (lo.count != i)
4010     outs() << "   count " << lo.count << " does not match number of strings "
4011            << i << "\n";
4012 }
4013
4014 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4015                                      const char *Ptr) {
4016   outs() << "          cmd LC_SUB_FRAMEWORK\n";
4017   outs() << "      cmdsize " << sub.cmdsize;
4018   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4019     outs() << " Incorrect size\n";
4020   else
4021     outs() << "\n";
4022   if (sub.umbrella < sub.cmdsize) {
4023     const char *P = Ptr + sub.umbrella;
4024     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
4025   } else {
4026     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
4027   }
4028 }
4029
4030 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4031                                     const char *Ptr) {
4032   outs() << "          cmd LC_SUB_UMBRELLA\n";
4033   outs() << "      cmdsize " << sub.cmdsize;
4034   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4035     outs() << " Incorrect size\n";
4036   else
4037     outs() << "\n";
4038   if (sub.sub_umbrella < sub.cmdsize) {
4039     const char *P = Ptr + sub.sub_umbrella;
4040     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4041   } else {
4042     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4043   }
4044 }
4045
4046 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4047                                    const char *Ptr) {
4048   outs() << "          cmd LC_SUB_LIBRARY\n";
4049   outs() << "      cmdsize " << sub.cmdsize;
4050   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4051     outs() << " Incorrect size\n";
4052   else
4053     outs() << "\n";
4054   if (sub.sub_library < sub.cmdsize) {
4055     const char *P = Ptr + sub.sub_library;
4056     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
4057   } else {
4058     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
4059   }
4060 }
4061
4062 static void PrintSubClientCommand(MachO::sub_client_command sub,
4063                                   const char *Ptr) {
4064   outs() << "          cmd LC_SUB_CLIENT\n";
4065   outs() << "      cmdsize " << sub.cmdsize;
4066   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4067     outs() << " Incorrect size\n";
4068   else
4069     outs() << "\n";
4070   if (sub.client < sub.cmdsize) {
4071     const char *P = Ptr + sub.client;
4072     outs() << "       client " << P << " (offset " << sub.client << ")\n";
4073   } else {
4074     outs() << "       client ?(bad offset " << sub.client << ")\n";
4075   }
4076 }
4077
4078 static void PrintRoutinesCommand(MachO::routines_command r) {
4079   outs() << "          cmd LC_ROUTINES\n";
4080   outs() << "      cmdsize " << r.cmdsize;
4081   if (r.cmdsize != sizeof(struct MachO::routines_command))
4082     outs() << " Incorrect size\n";
4083   else
4084     outs() << "\n";
4085   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4086   outs() << "  init_module " << r.init_module << "\n";
4087   outs() << "    reserved1 " << r.reserved1 << "\n";
4088   outs() << "    reserved2 " << r.reserved2 << "\n";
4089   outs() << "    reserved3 " << r.reserved3 << "\n";
4090   outs() << "    reserved4 " << r.reserved4 << "\n";
4091   outs() << "    reserved5 " << r.reserved5 << "\n";
4092   outs() << "    reserved6 " << r.reserved6 << "\n";
4093 }
4094
4095 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4096   outs() << "          cmd LC_ROUTINES_64\n";
4097   outs() << "      cmdsize " << r.cmdsize;
4098   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4099     outs() << " Incorrect size\n";
4100   else
4101     outs() << "\n";
4102   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4103   outs() << "  init_module " << r.init_module << "\n";
4104   outs() << "    reserved1 " << r.reserved1 << "\n";
4105   outs() << "    reserved2 " << r.reserved2 << "\n";
4106   outs() << "    reserved3 " << r.reserved3 << "\n";
4107   outs() << "    reserved4 " << r.reserved4 << "\n";
4108   outs() << "    reserved5 " << r.reserved5 << "\n";
4109   outs() << "    reserved6 " << r.reserved6 << "\n";
4110 }
4111
4112 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4113   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
4114   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4115   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4116   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
4117   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4118   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4119   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
4120   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4121   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4122   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
4123   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4124   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4125   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
4126   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4127   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4128   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
4129   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4130   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
4131   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
4132   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4133   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4134 }
4135
4136 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
4137   uint32_t f;
4138   outs() << "\t      mmst_reg  ";
4139   for (f = 0; f < 10; f++)
4140     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4141   outs() << "\n";
4142   outs() << "\t      mmst_rsrv ";
4143   for (f = 0; f < 6; f++)
4144     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4145   outs() << "\n";
4146 }
4147
4148 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
4149   uint32_t f;
4150   outs() << "\t      xmm_reg ";
4151   for (f = 0; f < 16; f++)
4152     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
4153   outs() << "\n";
4154 }
4155
4156 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
4157   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
4158   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
4159   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
4160   outs() << " denorm " << fpu.fpu_fcw.denorm;
4161   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
4162   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
4163   outs() << " undfl " << fpu.fpu_fcw.undfl;
4164   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
4165   outs() << "\t\t     pc ";
4166   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
4167     outs() << "FP_PREC_24B ";
4168   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
4169     outs() << "FP_PREC_53B ";
4170   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
4171     outs() << "FP_PREC_64B ";
4172   else
4173     outs() << fpu.fpu_fcw.pc << " ";
4174   outs() << "rc ";
4175   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
4176     outs() << "FP_RND_NEAR ";
4177   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
4178     outs() << "FP_RND_DOWN ";
4179   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
4180     outs() << "FP_RND_UP ";
4181   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
4182     outs() << "FP_CHOP ";
4183   outs() << "\n";
4184   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
4185   outs() << " denorm " << fpu.fpu_fsw.denorm;
4186   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
4187   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
4188   outs() << " undfl " << fpu.fpu_fsw.undfl;
4189   outs() << " precis " << fpu.fpu_fsw.precis;
4190   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
4191   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
4192   outs() << " c0 " << fpu.fpu_fsw.c0;
4193   outs() << " c1 " << fpu.fpu_fsw.c1;
4194   outs() << " c2 " << fpu.fpu_fsw.c2;
4195   outs() << " tos " << fpu.fpu_fsw.tos;
4196   outs() << " c3 " << fpu.fpu_fsw.c3;
4197   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
4198   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
4199   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
4200   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
4201   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
4202   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
4203   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
4204   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
4205   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
4206   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
4207   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
4208   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
4209   outs() << "\n";
4210   outs() << "\t    fpu_stmm0:\n";
4211   Print_mmst_reg(fpu.fpu_stmm0);
4212   outs() << "\t    fpu_stmm1:\n";
4213   Print_mmst_reg(fpu.fpu_stmm1);
4214   outs() << "\t    fpu_stmm2:\n";
4215   Print_mmst_reg(fpu.fpu_stmm2);
4216   outs() << "\t    fpu_stmm3:\n";
4217   Print_mmst_reg(fpu.fpu_stmm3);
4218   outs() << "\t    fpu_stmm4:\n";
4219   Print_mmst_reg(fpu.fpu_stmm4);
4220   outs() << "\t    fpu_stmm5:\n";
4221   Print_mmst_reg(fpu.fpu_stmm5);
4222   outs() << "\t    fpu_stmm6:\n";
4223   Print_mmst_reg(fpu.fpu_stmm6);
4224   outs() << "\t    fpu_stmm7:\n";
4225   Print_mmst_reg(fpu.fpu_stmm7);
4226   outs() << "\t    fpu_xmm0:\n";
4227   Print_xmm_reg(fpu.fpu_xmm0);
4228   outs() << "\t    fpu_xmm1:\n";
4229   Print_xmm_reg(fpu.fpu_xmm1);
4230   outs() << "\t    fpu_xmm2:\n";
4231   Print_xmm_reg(fpu.fpu_xmm2);
4232   outs() << "\t    fpu_xmm3:\n";
4233   Print_xmm_reg(fpu.fpu_xmm3);
4234   outs() << "\t    fpu_xmm4:\n";
4235   Print_xmm_reg(fpu.fpu_xmm4);
4236   outs() << "\t    fpu_xmm5:\n";
4237   Print_xmm_reg(fpu.fpu_xmm5);
4238   outs() << "\t    fpu_xmm6:\n";
4239   Print_xmm_reg(fpu.fpu_xmm6);
4240   outs() << "\t    fpu_xmm7:\n";
4241   Print_xmm_reg(fpu.fpu_xmm7);
4242   outs() << "\t    fpu_xmm8:\n";
4243   Print_xmm_reg(fpu.fpu_xmm8);
4244   outs() << "\t    fpu_xmm9:\n";
4245   Print_xmm_reg(fpu.fpu_xmm9);
4246   outs() << "\t    fpu_xmm10:\n";
4247   Print_xmm_reg(fpu.fpu_xmm10);
4248   outs() << "\t    fpu_xmm11:\n";
4249   Print_xmm_reg(fpu.fpu_xmm11);
4250   outs() << "\t    fpu_xmm12:\n";
4251   Print_xmm_reg(fpu.fpu_xmm12);
4252   outs() << "\t    fpu_xmm13:\n";
4253   Print_xmm_reg(fpu.fpu_xmm13);
4254   outs() << "\t    fpu_xmm14:\n";
4255   Print_xmm_reg(fpu.fpu_xmm14);
4256   outs() << "\t    fpu_xmm15:\n";
4257   Print_xmm_reg(fpu.fpu_xmm15);
4258   outs() << "\t    fpu_rsrv4:\n";
4259   for (uint32_t f = 0; f < 6; f++) {
4260     outs() << "\t            ";
4261     for (uint32_t g = 0; g < 16; g++)
4262       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
4263     outs() << "\n";
4264   }
4265   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
4266   outs() << "\n";
4267 }
4268
4269 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
4270   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
4271   outs() << " err " << format("0x%08" PRIx32, exc64.err);
4272   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
4273 }
4274
4275 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
4276                                bool isLittleEndian, uint32_t cputype) {
4277   if (t.cmd == MachO::LC_THREAD)
4278     outs() << "        cmd LC_THREAD\n";
4279   else if (t.cmd == MachO::LC_UNIXTHREAD)
4280     outs() << "        cmd LC_UNIXTHREAD\n";
4281   else
4282     outs() << "        cmd " << t.cmd << " (unknown)\n";
4283   outs() << "    cmdsize " << t.cmdsize;
4284   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
4285     outs() << " Incorrect size\n";
4286   else
4287     outs() << "\n";
4288
4289   const char *begin = Ptr + sizeof(struct MachO::thread_command);
4290   const char *end = Ptr + t.cmdsize;
4291   uint32_t flavor, count, left;
4292   if (cputype == MachO::CPU_TYPE_X86_64) {
4293     while (begin < end) {
4294       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4295         memcpy((char *)&flavor, begin, sizeof(uint32_t));
4296         begin += sizeof(uint32_t);
4297       } else {
4298         flavor = 0;
4299         begin = end;
4300       }
4301       if (isLittleEndian != sys::IsLittleEndianHost)
4302         sys::swapByteOrder(flavor);
4303       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4304         memcpy((char *)&count, begin, sizeof(uint32_t));
4305         begin += sizeof(uint32_t);
4306       } else {
4307         count = 0;
4308         begin = end;
4309       }
4310       if (isLittleEndian != sys::IsLittleEndianHost)
4311         sys::swapByteOrder(count);
4312       if (flavor == MachO::x86_THREAD_STATE64) {
4313         outs() << "     flavor x86_THREAD_STATE64\n";
4314         if (count == MachO::x86_THREAD_STATE64_COUNT)
4315           outs() << "      count x86_THREAD_STATE64_COUNT\n";
4316         else
4317           outs() << "      count " << count
4318                  << " (not x86_THREAD_STATE64_COUNT)\n";
4319         MachO::x86_thread_state64_t cpu64;
4320         left = end - begin;
4321         if (left >= sizeof(MachO::x86_thread_state64_t)) {
4322           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
4323           begin += sizeof(MachO::x86_thread_state64_t);
4324         } else {
4325           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
4326           memcpy(&cpu64, begin, left);
4327           begin += left;
4328         }
4329         if (isLittleEndian != sys::IsLittleEndianHost)
4330           swapStruct(cpu64);
4331         Print_x86_thread_state64_t(cpu64);
4332       } else if (flavor == MachO::x86_THREAD_STATE) {
4333         outs() << "     flavor x86_THREAD_STATE\n";
4334         if (count == MachO::x86_THREAD_STATE_COUNT)
4335           outs() << "      count x86_THREAD_STATE_COUNT\n";
4336         else
4337           outs() << "      count " << count
4338                  << " (not x86_THREAD_STATE_COUNT)\n";
4339         struct MachO::x86_thread_state_t ts;
4340         left = end - begin;
4341         if (left >= sizeof(MachO::x86_thread_state_t)) {
4342           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
4343           begin += sizeof(MachO::x86_thread_state_t);
4344         } else {
4345           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
4346           memcpy(&ts, begin, left);
4347           begin += left;
4348         }
4349         if (isLittleEndian != sys::IsLittleEndianHost)
4350           swapStruct(ts);
4351         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
4352           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
4353           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
4354             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
4355           else
4356             outs() << "tsh.count " << ts.tsh.count
4357                    << " (not x86_THREAD_STATE64_COUNT\n";
4358           Print_x86_thread_state64_t(ts.uts.ts64);
4359         } else {
4360           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
4361                  << ts.tsh.count << "\n";
4362         }
4363       } else if (flavor == MachO::x86_FLOAT_STATE) {
4364         outs() << "     flavor x86_FLOAT_STATE\n";
4365         if (count == MachO::x86_FLOAT_STATE_COUNT)
4366           outs() << "      count x86_FLOAT_STATE_COUNT\n";
4367         else
4368           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
4369         struct MachO::x86_float_state_t fs;
4370         left = end - begin;
4371         if (left >= sizeof(MachO::x86_float_state_t)) {
4372           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
4373           begin += sizeof(MachO::x86_float_state_t);
4374         } else {
4375           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
4376           memcpy(&fs, begin, left);
4377           begin += left;
4378         }
4379         if (isLittleEndian != sys::IsLittleEndianHost)
4380           swapStruct(fs);
4381         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
4382           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
4383           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
4384             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
4385           else
4386             outs() << "fsh.count " << fs.fsh.count
4387                    << " (not x86_FLOAT_STATE64_COUNT\n";
4388           Print_x86_float_state_t(fs.ufs.fs64);
4389         } else {
4390           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
4391                  << fs.fsh.count << "\n";
4392         }
4393       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
4394         outs() << "     flavor x86_EXCEPTION_STATE\n";
4395         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
4396           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
4397         else
4398           outs() << "      count " << count
4399                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
4400         struct MachO::x86_exception_state_t es;
4401         left = end - begin;
4402         if (left >= sizeof(MachO::x86_exception_state_t)) {
4403           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
4404           begin += sizeof(MachO::x86_exception_state_t);
4405         } else {
4406           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
4407           memcpy(&es, begin, left);
4408           begin += left;
4409         }
4410         if (isLittleEndian != sys::IsLittleEndianHost)
4411           swapStruct(es);
4412         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
4413           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
4414           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
4415             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
4416           else
4417             outs() << "\t    esh.count " << es.esh.count
4418                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
4419           Print_x86_exception_state_t(es.ues.es64);
4420         } else {
4421           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
4422                  << es.esh.count << "\n";
4423         }
4424       } else {
4425         outs() << "     flavor " << flavor << " (unknown)\n";
4426         outs() << "      count " << count << "\n";
4427         outs() << "      state (unknown)\n";
4428         begin += count * sizeof(uint32_t);
4429       }
4430     }
4431   } else {
4432     while (begin < end) {
4433       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4434         memcpy((char *)&flavor, begin, sizeof(uint32_t));
4435         begin += sizeof(uint32_t);
4436       } else {
4437         flavor = 0;
4438         begin = end;
4439       }
4440       if (isLittleEndian != sys::IsLittleEndianHost)
4441         sys::swapByteOrder(flavor);
4442       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4443         memcpy((char *)&count, begin, sizeof(uint32_t));
4444         begin += sizeof(uint32_t);
4445       } else {
4446         count = 0;
4447         begin = end;
4448       }
4449       if (isLittleEndian != sys::IsLittleEndianHost)
4450         sys::swapByteOrder(count);
4451       outs() << "     flavor " << flavor << "\n";
4452       outs() << "      count " << count << "\n";
4453       outs() << "      state (Unknown cputype/cpusubtype)\n";
4454       begin += count * sizeof(uint32_t);
4455     }
4456   }
4457 }
4458
4459 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
4460   if (dl.cmd == MachO::LC_ID_DYLIB)
4461     outs() << "          cmd LC_ID_DYLIB\n";
4462   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
4463     outs() << "          cmd LC_LOAD_DYLIB\n";
4464   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
4465     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
4466   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
4467     outs() << "          cmd LC_REEXPORT_DYLIB\n";
4468   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
4469     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
4470   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
4471     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
4472   else
4473     outs() << "          cmd " << dl.cmd << " (unknown)\n";
4474   outs() << "      cmdsize " << dl.cmdsize;
4475   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
4476     outs() << " Incorrect size\n";
4477   else
4478     outs() << "\n";
4479   if (dl.dylib.name < dl.cmdsize) {
4480     const char *P = (const char *)(Ptr) + dl.dylib.name;
4481     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
4482   } else {
4483     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
4484   }
4485   outs() << "   time stamp " << dl.dylib.timestamp << " ";
4486   time_t t = dl.dylib.timestamp;
4487   outs() << ctime(&t);
4488   outs() << "      current version ";
4489   if (dl.dylib.current_version == 0xffffffff)
4490     outs() << "n/a\n";
4491   else
4492     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
4493            << ((dl.dylib.current_version >> 8) & 0xff) << "."
4494            << (dl.dylib.current_version & 0xff) << "\n";
4495   outs() << "compatibility version ";
4496   if (dl.dylib.compatibility_version == 0xffffffff)
4497     outs() << "n/a\n";
4498   else
4499     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
4500            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
4501            << (dl.dylib.compatibility_version & 0xff) << "\n";
4502 }
4503
4504 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
4505                                      uint32_t object_size) {
4506   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
4507     outs() << "      cmd LC_FUNCTION_STARTS\n";
4508   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
4509     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
4510   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
4511     outs() << "      cmd LC_FUNCTION_STARTS\n";
4512   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
4513     outs() << "      cmd LC_DATA_IN_CODE\n";
4514   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
4515     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
4516   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
4517     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
4518   else
4519     outs() << "      cmd " << ld.cmd << " (?)\n";
4520   outs() << "  cmdsize " << ld.cmdsize;
4521   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
4522     outs() << " Incorrect size\n";
4523   else
4524     outs() << "\n";
4525   outs() << "  dataoff " << ld.dataoff;
4526   if (ld.dataoff > object_size)
4527     outs() << " (past end of file)\n";
4528   else
4529     outs() << "\n";
4530   outs() << " datasize " << ld.datasize;
4531   uint64_t big_size = ld.dataoff;
4532   big_size += ld.datasize;
4533   if (big_size > object_size)
4534     outs() << " (past end of file)\n";
4535   else
4536     outs() << "\n";
4537 }
4538
4539 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
4540                               uint32_t filetype, uint32_t cputype,
4541                               bool verbose) {
4542   if (ncmds == 0)
4543     return;
4544   StringRef Buf = Obj->getData();
4545   MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
4546   for (unsigned i = 0;; ++i) {
4547     outs() << "Load command " << i << "\n";
4548     if (Command.C.cmd == MachO::LC_SEGMENT) {
4549       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
4550       const char *sg_segname = SLC.segname;
4551       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
4552                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
4553                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
4554                           verbose);
4555       for (unsigned j = 0; j < SLC.nsects; j++) {
4556         MachO::section S = Obj->getSection(Command, j);
4557         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
4558                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
4559                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
4560       }
4561     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
4562       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
4563       const char *sg_segname = SLC_64.segname;
4564       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
4565                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
4566                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
4567                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
4568       for (unsigned j = 0; j < SLC_64.nsects; j++) {
4569         MachO::section_64 S_64 = Obj->getSection64(Command, j);
4570         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
4571                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
4572                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
4573                      sg_segname, filetype, Buf.size(), verbose);
4574       }
4575     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
4576       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
4577       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
4578     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
4579       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
4580       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
4581       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
4582                                Obj->is64Bit());
4583     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
4584                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
4585       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
4586       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
4587     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
4588                Command.C.cmd == MachO::LC_ID_DYLINKER ||
4589                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
4590       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
4591       PrintDyldLoadCommand(Dyld, Command.Ptr);
4592     } else if (Command.C.cmd == MachO::LC_UUID) {
4593       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
4594       PrintUuidLoadCommand(Uuid);
4595     } else if (Command.C.cmd == MachO::LC_RPATH) {
4596       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
4597       PrintRpathLoadCommand(Rpath, Command.Ptr);
4598     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
4599                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
4600       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
4601       PrintVersionMinLoadCommand(Vd);
4602     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
4603       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
4604       PrintSourceVersionCommand(Sd);
4605     } else if (Command.C.cmd == MachO::LC_MAIN) {
4606       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
4607       PrintEntryPointCommand(Ep);
4608     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
4609       MachO::encryption_info_command Ei =
4610           Obj->getEncryptionInfoCommand(Command);
4611       PrintEncryptionInfoCommand(Ei, Buf.size());
4612     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
4613       MachO::encryption_info_command_64 Ei =
4614           Obj->getEncryptionInfoCommand64(Command);
4615       PrintEncryptionInfoCommand64(Ei, Buf.size());
4616     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
4617       MachO::linker_option_command Lo =
4618           Obj->getLinkerOptionLoadCommand(Command);
4619       PrintLinkerOptionCommand(Lo, Command.Ptr);
4620     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
4621       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
4622       PrintSubFrameworkCommand(Sf, Command.Ptr);
4623     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
4624       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
4625       PrintSubUmbrellaCommand(Sf, Command.Ptr);
4626     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
4627       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
4628       PrintSubLibraryCommand(Sl, Command.Ptr);
4629     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
4630       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
4631       PrintSubClientCommand(Sc, Command.Ptr);
4632     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
4633       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
4634       PrintRoutinesCommand(Rc);
4635     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
4636       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
4637       PrintRoutinesCommand64(Rc);
4638     } else if (Command.C.cmd == MachO::LC_THREAD ||
4639                Command.C.cmd == MachO::LC_UNIXTHREAD) {
4640       MachO::thread_command Tc = Obj->getThreadCommand(Command);
4641       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
4642     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
4643                Command.C.cmd == MachO::LC_ID_DYLIB ||
4644                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
4645                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
4646                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
4647                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
4648       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
4649       PrintDylibCommand(Dl, Command.Ptr);
4650     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
4651                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
4652                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
4653                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
4654                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
4655                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
4656       MachO::linkedit_data_command Ld =
4657           Obj->getLinkeditDataLoadCommand(Command);
4658       PrintLinkEditDataCommand(Ld, Buf.size());
4659     } else {
4660       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
4661              << ")\n";
4662       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
4663       // TODO: get and print the raw bytes of the load command.
4664     }
4665     // TODO: print all the other kinds of load commands.
4666     if (i == ncmds - 1)
4667       break;
4668     else
4669       Command = Obj->getNextLoadCommandInfo(Command);
4670   }
4671 }
4672
4673 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
4674                                   uint32_t &filetype, uint32_t &cputype,
4675                                   bool verbose) {
4676   if (Obj->is64Bit()) {
4677     MachO::mach_header_64 H_64;
4678     H_64 = Obj->getHeader64();
4679     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
4680                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
4681     ncmds = H_64.ncmds;
4682     filetype = H_64.filetype;
4683     cputype = H_64.cputype;
4684   } else {
4685     MachO::mach_header H;
4686     H = Obj->getHeader();
4687     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
4688                     H.sizeofcmds, H.flags, verbose);
4689     ncmds = H.ncmds;
4690     filetype = H.filetype;
4691     cputype = H.cputype;
4692   }
4693 }
4694
4695 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
4696   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
4697   uint32_t ncmds = 0;
4698   uint32_t filetype = 0;
4699   uint32_t cputype = 0;
4700   getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
4701   PrintLoadCommands(file, ncmds, filetype, cputype, true);
4702 }
4703
4704 //===----------------------------------------------------------------------===//
4705 // export trie dumping
4706 //===----------------------------------------------------------------------===//
4707
4708 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
4709   for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
4710     uint64_t Flags = Entry.flags();
4711     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
4712     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
4713     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4714                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
4715     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4716                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
4717     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
4718     if (ReExport)
4719       outs() << "[re-export] ";
4720     else
4721       outs() << format("0x%08llX  ",
4722                        Entry.address()); // FIXME:add in base address
4723     outs() << Entry.name();
4724     if (WeakDef || ThreadLocal || Resolver || Abs) {
4725       bool NeedsComma = false;
4726       outs() << " [";
4727       if (WeakDef) {
4728         outs() << "weak_def";
4729         NeedsComma = true;
4730       }
4731       if (ThreadLocal) {
4732         if (NeedsComma)
4733           outs() << ", ";
4734         outs() << "per-thread";
4735         NeedsComma = true;
4736       }
4737       if (Abs) {
4738         if (NeedsComma)
4739           outs() << ", ";
4740         outs() << "absolute";
4741         NeedsComma = true;
4742       }
4743       if (Resolver) {
4744         if (NeedsComma)
4745           outs() << ", ";
4746         outs() << format("resolver=0x%08llX", Entry.other());
4747         NeedsComma = true;
4748       }
4749       outs() << "]";
4750     }
4751     if (ReExport) {
4752       StringRef DylibName = "unknown";
4753       int Ordinal = Entry.other() - 1;
4754       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
4755       if (Entry.otherName().empty())
4756         outs() << " (from " << DylibName << ")";
4757       else
4758         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
4759     }
4760     outs() << "\n";
4761   }
4762 }
4763
4764 //===----------------------------------------------------------------------===//
4765 // rebase table dumping
4766 //===----------------------------------------------------------------------===//
4767
4768 namespace {
4769 class SegInfo {
4770 public:
4771   SegInfo(const object::MachOObjectFile *Obj);
4772
4773   StringRef segmentName(uint32_t SegIndex);
4774   StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
4775   uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
4776
4777 private:
4778   struct SectionInfo {
4779     uint64_t Address;
4780     uint64_t Size;
4781     StringRef SectionName;
4782     StringRef SegmentName;
4783     uint64_t OffsetInSegment;
4784     uint64_t SegmentStartAddress;
4785     uint32_t SegmentIndex;
4786   };
4787   const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
4788   SmallVector<SectionInfo, 32> Sections;
4789 };
4790 }
4791
4792 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
4793   // Build table of sections so segIndex/offset pairs can be translated.
4794   uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
4795   StringRef CurSegName;
4796   uint64_t CurSegAddress;
4797   for (const SectionRef &Section : Obj->sections()) {
4798     SectionInfo Info;
4799     if (error(Section.getName(Info.SectionName)))
4800       return;
4801     Info.Address = Section.getAddress();
4802     Info.Size = Section.getSize();
4803     Info.SegmentName =
4804         Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4805     if (!Info.SegmentName.equals(CurSegName)) {
4806       ++CurSegIndex;
4807       CurSegName = Info.SegmentName;
4808       CurSegAddress = Info.Address;
4809     }
4810     Info.SegmentIndex = CurSegIndex - 1;
4811     Info.OffsetInSegment = Info.Address - CurSegAddress;
4812     Info.SegmentStartAddress = CurSegAddress;
4813     Sections.push_back(Info);
4814   }
4815 }
4816
4817 StringRef SegInfo::segmentName(uint32_t SegIndex) {
4818   for (const SectionInfo &SI : Sections) {
4819     if (SI.SegmentIndex == SegIndex)
4820       return SI.SegmentName;
4821   }
4822   llvm_unreachable("invalid segIndex");
4823 }
4824
4825 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
4826                                                  uint64_t OffsetInSeg) {
4827   for (const SectionInfo &SI : Sections) {
4828     if (SI.SegmentIndex != SegIndex)
4829       continue;
4830     if (SI.OffsetInSegment > OffsetInSeg)
4831       continue;
4832     if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
4833       continue;
4834     return SI;
4835   }
4836   llvm_unreachable("segIndex and offset not in any section");
4837 }
4838
4839 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
4840   return findSection(SegIndex, OffsetInSeg).SectionName;
4841 }
4842
4843 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4844   const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
4845   return SI.SegmentStartAddress + OffsetInSeg;
4846 }
4847
4848 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
4849   // Build table of sections so names can used in final output.
4850   SegInfo sectionTable(Obj);
4851
4852   outs() << "segment  section            address     type\n";
4853   for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
4854     uint32_t SegIndex = Entry.segmentIndex();
4855     uint64_t OffsetInSeg = Entry.segmentOffset();
4856     StringRef SegmentName = sectionTable.segmentName(SegIndex);
4857     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4858     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4859
4860     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
4861     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
4862                      SegmentName.str().c_str(), SectionName.str().c_str(),
4863                      Address, Entry.typeName().str().c_str());
4864   }
4865 }
4866
4867 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
4868   StringRef DylibName;
4869   switch (Ordinal) {
4870   case MachO::BIND_SPECIAL_DYLIB_SELF:
4871     return "this-image";
4872   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
4873     return "main-executable";
4874   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
4875     return "flat-namespace";
4876   default:
4877     if (Ordinal > 0) {
4878       std::error_code EC =
4879           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
4880       if (EC)
4881         return "<<bad library ordinal>>";
4882       return DylibName;
4883     }
4884   }
4885   return "<<unknown special ordinal>>";
4886 }
4887
4888 //===----------------------------------------------------------------------===//
4889 // bind table dumping
4890 //===----------------------------------------------------------------------===//
4891
4892 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
4893   // Build table of sections so names can used in final output.
4894   SegInfo sectionTable(Obj);
4895
4896   outs() << "segment  section            address    type       "
4897             "addend dylib            symbol\n";
4898   for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
4899     uint32_t SegIndex = Entry.segmentIndex();
4900     uint64_t OffsetInSeg = Entry.segmentOffset();
4901     StringRef SegmentName = sectionTable.segmentName(SegIndex);
4902     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4903     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4904
4905     // Table lines look like:
4906     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
4907     StringRef Attr;
4908     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
4909       Attr = " (weak_import)";
4910     outs() << left_justify(SegmentName, 8) << " "
4911            << left_justify(SectionName, 18) << " "
4912            << format_hex(Address, 10, true) << " "
4913            << left_justify(Entry.typeName(), 8) << " "
4914            << format_decimal(Entry.addend(), 8) << " "
4915            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
4916            << Entry.symbolName() << Attr << "\n";
4917   }
4918 }
4919
4920 //===----------------------------------------------------------------------===//
4921 // lazy bind table dumping
4922 //===----------------------------------------------------------------------===//
4923
4924 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
4925   // Build table of sections so names can used in final output.
4926   SegInfo sectionTable(Obj);
4927
4928   outs() << "segment  section            address     "
4929             "dylib            symbol\n";
4930   for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
4931     uint32_t SegIndex = Entry.segmentIndex();
4932     uint64_t OffsetInSeg = Entry.segmentOffset();
4933     StringRef SegmentName = sectionTable.segmentName(SegIndex);
4934     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4935     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4936
4937     // Table lines look like:
4938     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
4939     outs() << left_justify(SegmentName, 8) << " "
4940            << left_justify(SectionName, 18) << " "
4941            << format_hex(Address, 10, true) << " "
4942            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
4943            << Entry.symbolName() << "\n";
4944   }
4945 }
4946
4947 //===----------------------------------------------------------------------===//
4948 // weak bind table dumping
4949 //===----------------------------------------------------------------------===//
4950
4951 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
4952   // Build table of sections so names can used in final output.
4953   SegInfo sectionTable(Obj);
4954
4955   outs() << "segment  section            address     "
4956             "type       addend   symbol\n";
4957   for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
4958     // Strong symbols don't have a location to update.
4959     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
4960       outs() << "                                        strong              "
4961              << Entry.symbolName() << "\n";
4962       continue;
4963     }
4964     uint32_t SegIndex = Entry.segmentIndex();
4965     uint64_t OffsetInSeg = Entry.segmentOffset();
4966     StringRef SegmentName = sectionTable.segmentName(SegIndex);
4967     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4968     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4969
4970     // Table lines look like:
4971     // __DATA  __data  0x00001000  pointer    0   _foo
4972     outs() << left_justify(SegmentName, 8) << " "
4973            << left_justify(SectionName, 18) << " "
4974            << format_hex(Address, 10, true) << " "
4975            << left_justify(Entry.typeName(), 8) << " "
4976            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
4977            << "\n";
4978   }
4979 }
4980
4981 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
4982 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
4983 // information for that address. If the address is found its binding symbol
4984 // name is returned.  If not nullptr is returned.
4985 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
4986                                                  struct DisassembleInfo *info) {
4987   if (info->bindtable == nullptr) {
4988     info->bindtable = new (BindTable);
4989     SegInfo sectionTable(info->O);
4990     for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
4991       uint32_t SegIndex = Entry.segmentIndex();
4992       uint64_t OffsetInSeg = Entry.segmentOffset();
4993       uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4994       const char *SymbolName = nullptr;
4995       StringRef name = Entry.symbolName();
4996       if (!name.empty())
4997         SymbolName = name.data();
4998       info->bindtable->push_back(std::make_pair(Address, SymbolName));
4999     }
5000   }
5001   for (bind_table_iterator BI = info->bindtable->begin(),
5002                            BE = info->bindtable->end();
5003        BI != BE; ++BI) {
5004     uint64_t Address = BI->first;
5005     if (ReferenceValue == Address) {
5006       const char *SymbolName = BI->second;
5007       return SymbolName;
5008     }
5009   }
5010   return nullptr;
5011 }