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