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