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