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