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