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