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