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