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