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