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