[Objdump] DumpBytes of uint8_t from ArrayRef<uint8_t> instead of char from StringRef...
[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 uint8_t *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(ArrayRef<uint8_t>(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(ArrayRef<uint8_t>(bytes, 2));
224       Value = bytes[1] << 8 | bytes[0];
225       outs() << "\t.short " << Value;
226       Size = 2;
227     } else {
228       if (!NoShowRawInsn)
229         DumpBytes(ArrayRef<uint8_t>(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(ArrayRef<uint8_t>(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(ArrayRef<uint8_t>(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(ArrayRef<uint8_t>(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(Bytes.data() + Index, Length, Kind);
3327           if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
3328               (PC == (DTI->first + Length - 1)) && (Length & 1))
3329             Size++;
3330           continue;
3331         }
3332
3333         SmallVector<char, 64> AnnotationsBytes;
3334         raw_svector_ostream Annotations(AnnotationsBytes);
3335
3336         bool gotInst;
3337         if (isThumb)
3338           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
3339                                                 PC, DebugOut, Annotations);
3340         else
3341           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
3342                                            DebugOut, Annotations);
3343         if (gotInst) {
3344           if (!NoShowRawInsn) {
3345             DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size));
3346           }
3347           formatted_raw_ostream FormattedOS(outs());
3348           Annotations.flush();
3349           StringRef AnnotationsStr = Annotations.str();
3350           if (isThumb)
3351             ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
3352           else
3353             IP->printInst(&Inst, FormattedOS, AnnotationsStr);
3354           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
3355
3356           // Print debug info.
3357           if (diContext) {
3358             DILineInfo dli = diContext->getLineInfoForAddress(PC);
3359             // Print valid line info if it changed.
3360             if (dli != lastLine && dli.Line != 0)
3361               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
3362                      << dli.Column;
3363             lastLine = dli;
3364           }
3365           outs() << "\n";
3366         } else {
3367           unsigned int Arch = MachOOF->getArch();
3368           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3369             outs() << format("\t.byte 0x%02x #bad opcode\n",
3370                              *(Bytes.data() + Index) & 0xff);
3371             Size = 1; // skip exactly one illegible byte and move on.
3372           } else if (Arch == Triple::aarch64) {
3373             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
3374                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
3375                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
3376                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
3377             outs() << format("\t.long\t0x%08x\n", opcode);
3378             Size = 4;
3379           } else {
3380             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3381             if (Size == 0)
3382               Size = 1; // skip illegible bytes
3383           }
3384         }
3385       }
3386     }
3387     if (!symbolTableWorked) {
3388       // Reading the symbol table didn't work, disassemble the whole section.
3389       uint64_t SectAddress = Sections[SectIdx].getAddress();
3390       uint64_t SectSize = Sections[SectIdx].getSize();
3391       uint64_t InstSize;
3392       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
3393         MCInst Inst;
3394
3395         uint64_t PC = SectAddress + Index;
3396         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
3397                                    DebugOut, nulls())) {
3398           if (!NoLeadingAddr) {
3399             if (FullLeadingAddr) {
3400               if (MachOOF->is64Bit())
3401                 outs() << format("%016" PRIx64, PC);
3402               else
3403                 outs() << format("%08" PRIx64, PC);
3404             } else {
3405               outs() << format("%8" PRIx64 ":", PC);
3406             }
3407           }
3408           if (!NoShowRawInsn) {
3409             outs() << "\t";
3410             DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, InstSize));
3411           }
3412           IP->printInst(&Inst, outs(), "");
3413           outs() << "\n";
3414         } else {
3415           unsigned int Arch = MachOOF->getArch();
3416           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3417             outs() << format("\t.byte 0x%02x #bad opcode\n",
3418                              *(Bytes.data() + Index) & 0xff);
3419             InstSize = 1; // skip exactly one illegible byte and move on.
3420           } else {
3421             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3422             if (InstSize == 0)
3423               InstSize = 1; // skip illegible bytes
3424           }
3425         }
3426       }
3427     }
3428     // The TripleName's need to be reset if we are called again for a different
3429     // archtecture.
3430     TripleName = "";
3431     ThumbTripleName = "";
3432
3433     if (SymbolizerInfo.method != nullptr)
3434       free(SymbolizerInfo.method);
3435     if (SymbolizerInfo.demangled_name != nullptr)
3436       free(SymbolizerInfo.demangled_name);
3437     if (SymbolizerInfo.bindtable != nullptr)
3438       delete SymbolizerInfo.bindtable;
3439     if (ThumbSymbolizerInfo.method != nullptr)
3440       free(ThumbSymbolizerInfo.method);
3441     if (ThumbSymbolizerInfo.demangled_name != nullptr)
3442       free(ThumbSymbolizerInfo.demangled_name);
3443     if (ThumbSymbolizerInfo.bindtable != nullptr)
3444       delete ThumbSymbolizerInfo.bindtable;
3445   }
3446 }
3447
3448 //===----------------------------------------------------------------------===//
3449 // __compact_unwind section dumping
3450 //===----------------------------------------------------------------------===//
3451
3452 namespace {
3453
3454 template <typename T> static uint64_t readNext(const char *&Buf) {
3455   using llvm::support::little;
3456   using llvm::support::unaligned;
3457
3458   uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
3459   Buf += sizeof(T);
3460   return Val;
3461 }
3462
3463 struct CompactUnwindEntry {
3464   uint32_t OffsetInSection;
3465
3466   uint64_t FunctionAddr;
3467   uint32_t Length;
3468   uint32_t CompactEncoding;
3469   uint64_t PersonalityAddr;
3470   uint64_t LSDAAddr;
3471
3472   RelocationRef FunctionReloc;
3473   RelocationRef PersonalityReloc;
3474   RelocationRef LSDAReloc;
3475
3476   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
3477       : OffsetInSection(Offset) {
3478     if (Is64)
3479       read<uint64_t>(Contents.data() + Offset);
3480     else
3481       read<uint32_t>(Contents.data() + Offset);
3482   }
3483
3484 private:
3485   template <typename UIntPtr> void read(const char *Buf) {
3486     FunctionAddr = readNext<UIntPtr>(Buf);
3487     Length = readNext<uint32_t>(Buf);
3488     CompactEncoding = readNext<uint32_t>(Buf);
3489     PersonalityAddr = readNext<UIntPtr>(Buf);
3490     LSDAAddr = readNext<UIntPtr>(Buf);
3491   }
3492 };
3493 }
3494
3495 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
3496 /// and data being relocated, determine the best base Name and Addend to use for
3497 /// display purposes.
3498 ///
3499 /// 1. An Extern relocation will directly reference a symbol (and the data is
3500 ///    then already an addend), so use that.
3501 /// 2. Otherwise the data is an offset in the object file's layout; try to find
3502 //     a symbol before it in the same section, and use the offset from there.
3503 /// 3. Finally, if all that fails, fall back to an offset from the start of the
3504 ///    referenced section.
3505 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
3506                                       std::map<uint64_t, SymbolRef> &Symbols,
3507                                       const RelocationRef &Reloc, uint64_t Addr,
3508                                       StringRef &Name, uint64_t &Addend) {
3509   if (Reloc.getSymbol() != Obj->symbol_end()) {
3510     Reloc.getSymbol()->getName(Name);
3511     Addend = Addr;
3512     return;
3513   }
3514
3515   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
3516   SectionRef RelocSection = Obj->getRelocationSection(RE);
3517
3518   uint64_t SectionAddr = RelocSection.getAddress();
3519
3520   auto Sym = Symbols.upper_bound(Addr);
3521   if (Sym == Symbols.begin()) {
3522     // The first symbol in the object is after this reference, the best we can
3523     // do is section-relative notation.
3524     RelocSection.getName(Name);
3525     Addend = Addr - SectionAddr;
3526     return;
3527   }
3528
3529   // Go back one so that SymbolAddress <= Addr.
3530   --Sym;
3531
3532   section_iterator SymSection = Obj->section_end();
3533   Sym->second.getSection(SymSection);
3534   if (RelocSection == *SymSection) {
3535     // There's a valid symbol in the same section before this reference.
3536     Sym->second.getName(Name);
3537     Addend = Addr - Sym->first;
3538     return;
3539   }
3540
3541   // There is a symbol before this reference, but it's in a different
3542   // section. Probably not helpful to mention it, so use the section name.
3543   RelocSection.getName(Name);
3544   Addend = Addr - SectionAddr;
3545 }
3546
3547 static void printUnwindRelocDest(const MachOObjectFile *Obj,
3548                                  std::map<uint64_t, SymbolRef> &Symbols,
3549                                  const RelocationRef &Reloc, uint64_t Addr) {
3550   StringRef Name;
3551   uint64_t Addend;
3552
3553   if (!Reloc.getObjectFile())
3554     return;
3555
3556   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
3557
3558   outs() << Name;
3559   if (Addend)
3560     outs() << " + " << format("0x%" PRIx64, Addend);
3561 }
3562
3563 static void
3564 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
3565                                std::map<uint64_t, SymbolRef> &Symbols,
3566                                const SectionRef &CompactUnwind) {
3567
3568   assert(Obj->isLittleEndian() &&
3569          "There should not be a big-endian .o with __compact_unwind");
3570
3571   bool Is64 = Obj->is64Bit();
3572   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
3573   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
3574
3575   StringRef Contents;
3576   CompactUnwind.getContents(Contents);
3577
3578   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
3579
3580   // First populate the initial raw offsets, encodings and so on from the entry.
3581   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
3582     CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
3583     CompactUnwinds.push_back(Entry);
3584   }
3585
3586   // Next we need to look at the relocations to find out what objects are
3587   // actually being referred to.
3588   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
3589     uint64_t RelocAddress;
3590     Reloc.getOffset(RelocAddress);
3591
3592     uint32_t EntryIdx = RelocAddress / EntrySize;
3593     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
3594     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
3595
3596     if (OffsetInEntry == 0)
3597       Entry.FunctionReloc = Reloc;
3598     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
3599       Entry.PersonalityReloc = Reloc;
3600     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
3601       Entry.LSDAReloc = Reloc;
3602     else
3603       llvm_unreachable("Unexpected relocation in __compact_unwind section");
3604   }
3605
3606   // Finally, we're ready to print the data we've gathered.
3607   outs() << "Contents of __compact_unwind section:\n";
3608   for (auto &Entry : CompactUnwinds) {
3609     outs() << "  Entry at offset "
3610            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
3611
3612     // 1. Start of the region this entry applies to.
3613     outs() << "    start:                " << format("0x%" PRIx64,
3614                                                      Entry.FunctionAddr) << ' ';
3615     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
3616     outs() << '\n';
3617
3618     // 2. Length of the region this entry applies to.
3619     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
3620            << '\n';
3621     // 3. The 32-bit compact encoding.
3622     outs() << "    compact encoding:     "
3623            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
3624
3625     // 4. The personality function, if present.
3626     if (Entry.PersonalityReloc.getObjectFile()) {
3627       outs() << "    personality function: "
3628              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
3629       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
3630                            Entry.PersonalityAddr);
3631       outs() << '\n';
3632     }
3633
3634     // 5. This entry's language-specific data area.
3635     if (Entry.LSDAReloc.getObjectFile()) {
3636       outs() << "    LSDA:                 " << format("0x%" PRIx64,
3637                                                        Entry.LSDAAddr) << ' ';
3638       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
3639       outs() << '\n';
3640     }
3641   }
3642 }
3643
3644 //===----------------------------------------------------------------------===//
3645 // __unwind_info section dumping
3646 //===----------------------------------------------------------------------===//
3647
3648 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
3649   const char *Pos = PageStart;
3650   uint32_t Kind = readNext<uint32_t>(Pos);
3651   (void)Kind;
3652   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
3653
3654   uint16_t EntriesStart = readNext<uint16_t>(Pos);
3655   uint16_t NumEntries = readNext<uint16_t>(Pos);
3656
3657   Pos = PageStart + EntriesStart;
3658   for (unsigned i = 0; i < NumEntries; ++i) {
3659     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3660     uint32_t Encoding = readNext<uint32_t>(Pos);
3661
3662     outs() << "      [" << i << "]: "
3663            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3664            << ", "
3665            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
3666   }
3667 }
3668
3669 static void printCompressedSecondLevelUnwindPage(
3670     const char *PageStart, uint32_t FunctionBase,
3671     const SmallVectorImpl<uint32_t> &CommonEncodings) {
3672   const char *Pos = PageStart;
3673   uint32_t Kind = readNext<uint32_t>(Pos);
3674   (void)Kind;
3675   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
3676
3677   uint16_t EntriesStart = readNext<uint16_t>(Pos);
3678   uint16_t NumEntries = readNext<uint16_t>(Pos);
3679
3680   uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3681   readNext<uint16_t>(Pos);
3682   const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3683       PageStart + EncodingsStart);
3684
3685   Pos = PageStart + EntriesStart;
3686   for (unsigned i = 0; i < NumEntries; ++i) {
3687     uint32_t Entry = readNext<uint32_t>(Pos);
3688     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3689     uint32_t EncodingIdx = Entry >> 24;
3690
3691     uint32_t Encoding;
3692     if (EncodingIdx < CommonEncodings.size())
3693       Encoding = CommonEncodings[EncodingIdx];
3694     else
3695       Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3696
3697     outs() << "      [" << i << "]: "
3698            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3699            << ", "
3700            << "encoding[" << EncodingIdx
3701            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
3702   }
3703 }
3704
3705 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3706                                         std::map<uint64_t, SymbolRef> &Symbols,
3707                                         const SectionRef &UnwindInfo) {
3708
3709   assert(Obj->isLittleEndian() &&
3710          "There should not be a big-endian .o with __unwind_info");
3711
3712   outs() << "Contents of __unwind_info section:\n";
3713
3714   StringRef Contents;
3715   UnwindInfo.getContents(Contents);
3716   const char *Pos = Contents.data();
3717
3718   //===----------------------------------
3719   // Section header
3720   //===----------------------------------
3721
3722   uint32_t Version = readNext<uint32_t>(Pos);
3723   outs() << "  Version:                                   "
3724          << format("0x%" PRIx32, Version) << '\n';
3725   assert(Version == 1 && "only understand version 1");
3726
3727   uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3728   outs() << "  Common encodings array section offset:     "
3729          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3730   uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3731   outs() << "  Number of common encodings in array:       "
3732          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3733
3734   uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3735   outs() << "  Personality function array section offset: "
3736          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3737   uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3738   outs() << "  Number of personality functions in array:  "
3739          << format("0x%" PRIx32, NumPersonalities) << '\n';
3740
3741   uint32_t IndicesStart = readNext<uint32_t>(Pos);
3742   outs() << "  Index array section offset:                "
3743          << format("0x%" PRIx32, IndicesStart) << '\n';
3744   uint32_t NumIndices = readNext<uint32_t>(Pos);
3745   outs() << "  Number of indices in array:                "
3746          << format("0x%" PRIx32, NumIndices) << '\n';
3747
3748   //===----------------------------------
3749   // A shared list of common encodings
3750   //===----------------------------------
3751
3752   // These occupy indices in the range [0, N] whenever an encoding is referenced
3753   // from a compressed 2nd level index table. In practice the linker only
3754   // creates ~128 of these, so that indices are available to embed encodings in
3755   // the 2nd level index.
3756
3757   SmallVector<uint32_t, 64> CommonEncodings;
3758   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
3759   Pos = Contents.data() + CommonEncodingsStart;
3760   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3761     uint32_t Encoding = readNext<uint32_t>(Pos);
3762     CommonEncodings.push_back(Encoding);
3763
3764     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3765            << '\n';
3766   }
3767
3768   //===----------------------------------
3769   // Personality functions used in this executable
3770   //===----------------------------------
3771
3772   // There should be only a handful of these (one per source language,
3773   // roughly). Particularly since they only get 2 bits in the compact encoding.
3774
3775   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
3776   Pos = Contents.data() + PersonalitiesStart;
3777   for (unsigned i = 0; i < NumPersonalities; ++i) {
3778     uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3779     outs() << "    personality[" << i + 1
3780            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3781   }
3782
3783   //===----------------------------------
3784   // The level 1 index entries
3785   //===----------------------------------
3786
3787   // These specify an approximate place to start searching for the more detailed
3788   // information, sorted by PC.
3789
3790   struct IndexEntry {
3791     uint32_t FunctionOffset;
3792     uint32_t SecondLevelPageStart;
3793     uint32_t LSDAStart;
3794   };
3795
3796   SmallVector<IndexEntry, 4> IndexEntries;
3797
3798   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
3799   Pos = Contents.data() + IndicesStart;
3800   for (unsigned i = 0; i < NumIndices; ++i) {
3801     IndexEntry Entry;
3802
3803     Entry.FunctionOffset = readNext<uint32_t>(Pos);
3804     Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3805     Entry.LSDAStart = readNext<uint32_t>(Pos);
3806     IndexEntries.push_back(Entry);
3807
3808     outs() << "    [" << i << "]: "
3809            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3810            << ", "
3811            << "2nd level page offset="
3812            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
3813            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
3814   }
3815
3816   //===----------------------------------
3817   // Next come the LSDA tables
3818   //===----------------------------------
3819
3820   // The LSDA layout is rather implicit: it's a contiguous array of entries from
3821   // the first top-level index's LSDAOffset to the last (sentinel).
3822
3823   outs() << "  LSDA descriptors:\n";
3824   Pos = Contents.data() + IndexEntries[0].LSDAStart;
3825   int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3826                  (2 * sizeof(uint32_t));
3827   for (int i = 0; i < NumLSDAs; ++i) {
3828     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3829     uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3830     outs() << "    [" << i << "]: "
3831            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3832            << ", "
3833            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
3834   }
3835
3836   //===----------------------------------
3837   // Finally, the 2nd level indices
3838   //===----------------------------------
3839
3840   // Generally these are 4K in size, and have 2 possible forms:
3841   //   + Regular stores up to 511 entries with disparate encodings
3842   //   + Compressed stores up to 1021 entries if few enough compact encoding
3843   //     values are used.
3844   outs() << "  Second level indices:\n";
3845   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3846     // The final sentinel top-level index has no associated 2nd level page
3847     if (IndexEntries[i].SecondLevelPageStart == 0)
3848       break;
3849
3850     outs() << "    Second level index[" << i << "]: "
3851            << "offset in section="
3852            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3853            << ", "
3854            << "base function offset="
3855            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3856
3857     Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
3858     uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
3859     if (Kind == 2)
3860       printRegularSecondLevelUnwindPage(Pos);
3861     else if (Kind == 3)
3862       printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3863                                            CommonEncodings);
3864     else
3865       llvm_unreachable("Do not know how to print this kind of 2nd level page");
3866   }
3867 }
3868
3869 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3870   std::map<uint64_t, SymbolRef> Symbols;
3871   for (const SymbolRef &SymRef : Obj->symbols()) {
3872     // Discard any undefined or absolute symbols. They're not going to take part
3873     // in the convenience lookup for unwind info and just take up resources.
3874     section_iterator Section = Obj->section_end();
3875     SymRef.getSection(Section);
3876     if (Section == Obj->section_end())
3877       continue;
3878
3879     uint64_t Addr;
3880     SymRef.getAddress(Addr);
3881     Symbols.insert(std::make_pair(Addr, SymRef));
3882   }
3883
3884   for (const SectionRef &Section : Obj->sections()) {
3885     StringRef SectName;
3886     Section.getName(SectName);
3887     if (SectName == "__compact_unwind")
3888       printMachOCompactUnwindSection(Obj, Symbols, Section);
3889     else if (SectName == "__unwind_info")
3890       printMachOUnwindInfoSection(Obj, Symbols, Section);
3891     else if (SectName == "__eh_frame")
3892       outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3893   }
3894 }
3895
3896 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3897                             uint32_t cpusubtype, uint32_t filetype,
3898                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3899                             bool verbose) {
3900   outs() << "Mach header\n";
3901   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
3902             "sizeofcmds      flags\n";
3903   if (verbose) {
3904     if (magic == MachO::MH_MAGIC)
3905       outs() << "   MH_MAGIC";
3906     else if (magic == MachO::MH_MAGIC_64)
3907       outs() << "MH_MAGIC_64";
3908     else
3909       outs() << format(" 0x%08" PRIx32, magic);
3910     switch (cputype) {
3911     case MachO::CPU_TYPE_I386:
3912       outs() << "    I386";
3913       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3914       case MachO::CPU_SUBTYPE_I386_ALL:
3915         outs() << "        ALL";
3916         break;
3917       default:
3918         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3919         break;
3920       }
3921       break;
3922     case MachO::CPU_TYPE_X86_64:
3923       outs() << "  X86_64";
3924       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3925       case MachO::CPU_SUBTYPE_X86_64_ALL:
3926         outs() << "        ALL";
3927         break;
3928       case MachO::CPU_SUBTYPE_X86_64_H:
3929         outs() << "    Haswell";
3930         break;
3931       default:
3932         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3933         break;
3934       }
3935       break;
3936     case MachO::CPU_TYPE_ARM:
3937       outs() << "     ARM";
3938       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3939       case MachO::CPU_SUBTYPE_ARM_ALL:
3940         outs() << "        ALL";
3941         break;
3942       case MachO::CPU_SUBTYPE_ARM_V4T:
3943         outs() << "        V4T";
3944         break;
3945       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3946         outs() << "      V5TEJ";
3947         break;
3948       case MachO::CPU_SUBTYPE_ARM_XSCALE:
3949         outs() << "     XSCALE";
3950         break;
3951       case MachO::CPU_SUBTYPE_ARM_V6:
3952         outs() << "         V6";
3953         break;
3954       case MachO::CPU_SUBTYPE_ARM_V6M:
3955         outs() << "        V6M";
3956         break;
3957       case MachO::CPU_SUBTYPE_ARM_V7:
3958         outs() << "         V7";
3959         break;
3960       case MachO::CPU_SUBTYPE_ARM_V7EM:
3961         outs() << "       V7EM";
3962         break;
3963       case MachO::CPU_SUBTYPE_ARM_V7K:
3964         outs() << "        V7K";
3965         break;
3966       case MachO::CPU_SUBTYPE_ARM_V7M:
3967         outs() << "        V7M";
3968         break;
3969       case MachO::CPU_SUBTYPE_ARM_V7S:
3970         outs() << "        V7S";
3971         break;
3972       default:
3973         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3974         break;
3975       }
3976       break;
3977     case MachO::CPU_TYPE_ARM64:
3978       outs() << "   ARM64";
3979       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3980       case MachO::CPU_SUBTYPE_ARM64_ALL:
3981         outs() << "        ALL";
3982         break;
3983       default:
3984         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3985         break;
3986       }
3987       break;
3988     case MachO::CPU_TYPE_POWERPC:
3989       outs() << "     PPC";
3990       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3991       case MachO::CPU_SUBTYPE_POWERPC_ALL:
3992         outs() << "        ALL";
3993         break;
3994       default:
3995         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3996         break;
3997       }
3998       break;
3999     case MachO::CPU_TYPE_POWERPC64:
4000       outs() << "   PPC64";
4001       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
4002       case MachO::CPU_SUBTYPE_POWERPC_ALL:
4003         outs() << "        ALL";
4004         break;
4005       default:
4006         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4007         break;
4008       }
4009       break;
4010     }
4011     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
4012       outs() << " LIB64";
4013     } else {
4014       outs() << format("  0x%02" PRIx32,
4015                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4016     }
4017     switch (filetype) {
4018     case MachO::MH_OBJECT:
4019       outs() << "      OBJECT";
4020       break;
4021     case MachO::MH_EXECUTE:
4022       outs() << "     EXECUTE";
4023       break;
4024     case MachO::MH_FVMLIB:
4025       outs() << "      FVMLIB";
4026       break;
4027     case MachO::MH_CORE:
4028       outs() << "        CORE";
4029       break;
4030     case MachO::MH_PRELOAD:
4031       outs() << "     PRELOAD";
4032       break;
4033     case MachO::MH_DYLIB:
4034       outs() << "       DYLIB";
4035       break;
4036     case MachO::MH_DYLIB_STUB:
4037       outs() << "  DYLIB_STUB";
4038       break;
4039     case MachO::MH_DYLINKER:
4040       outs() << "    DYLINKER";
4041       break;
4042     case MachO::MH_BUNDLE:
4043       outs() << "      BUNDLE";
4044       break;
4045     case MachO::MH_DSYM:
4046       outs() << "        DSYM";
4047       break;
4048     case MachO::MH_KEXT_BUNDLE:
4049       outs() << "  KEXTBUNDLE";
4050       break;
4051     default:
4052       outs() << format("  %10u", filetype);
4053       break;
4054     }
4055     outs() << format(" %5u", ncmds);
4056     outs() << format(" %10u", sizeofcmds);
4057     uint32_t f = flags;
4058     if (f & MachO::MH_NOUNDEFS) {
4059       outs() << "   NOUNDEFS";
4060       f &= ~MachO::MH_NOUNDEFS;
4061     }
4062     if (f & MachO::MH_INCRLINK) {
4063       outs() << " INCRLINK";
4064       f &= ~MachO::MH_INCRLINK;
4065     }
4066     if (f & MachO::MH_DYLDLINK) {
4067       outs() << " DYLDLINK";
4068       f &= ~MachO::MH_DYLDLINK;
4069     }
4070     if (f & MachO::MH_BINDATLOAD) {
4071       outs() << " BINDATLOAD";
4072       f &= ~MachO::MH_BINDATLOAD;
4073     }
4074     if (f & MachO::MH_PREBOUND) {
4075       outs() << " PREBOUND";
4076       f &= ~MachO::MH_PREBOUND;
4077     }
4078     if (f & MachO::MH_SPLIT_SEGS) {
4079       outs() << " SPLIT_SEGS";
4080       f &= ~MachO::MH_SPLIT_SEGS;
4081     }
4082     if (f & MachO::MH_LAZY_INIT) {
4083       outs() << " LAZY_INIT";
4084       f &= ~MachO::MH_LAZY_INIT;
4085     }
4086     if (f & MachO::MH_TWOLEVEL) {
4087       outs() << " TWOLEVEL";
4088       f &= ~MachO::MH_TWOLEVEL;
4089     }
4090     if (f & MachO::MH_FORCE_FLAT) {
4091       outs() << " FORCE_FLAT";
4092       f &= ~MachO::MH_FORCE_FLAT;
4093     }
4094     if (f & MachO::MH_NOMULTIDEFS) {
4095       outs() << " NOMULTIDEFS";
4096       f &= ~MachO::MH_NOMULTIDEFS;
4097     }
4098     if (f & MachO::MH_NOFIXPREBINDING) {
4099       outs() << " NOFIXPREBINDING";
4100       f &= ~MachO::MH_NOFIXPREBINDING;
4101     }
4102     if (f & MachO::MH_PREBINDABLE) {
4103       outs() << " PREBINDABLE";
4104       f &= ~MachO::MH_PREBINDABLE;
4105     }
4106     if (f & MachO::MH_ALLMODSBOUND) {
4107       outs() << " ALLMODSBOUND";
4108       f &= ~MachO::MH_ALLMODSBOUND;
4109     }
4110     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
4111       outs() << " SUBSECTIONS_VIA_SYMBOLS";
4112       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
4113     }
4114     if (f & MachO::MH_CANONICAL) {
4115       outs() << " CANONICAL";
4116       f &= ~MachO::MH_CANONICAL;
4117     }
4118     if (f & MachO::MH_WEAK_DEFINES) {
4119       outs() << " WEAK_DEFINES";
4120       f &= ~MachO::MH_WEAK_DEFINES;
4121     }
4122     if (f & MachO::MH_BINDS_TO_WEAK) {
4123       outs() << " BINDS_TO_WEAK";
4124       f &= ~MachO::MH_BINDS_TO_WEAK;
4125     }
4126     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
4127       outs() << " ALLOW_STACK_EXECUTION";
4128       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
4129     }
4130     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
4131       outs() << " DEAD_STRIPPABLE_DYLIB";
4132       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
4133     }
4134     if (f & MachO::MH_PIE) {
4135       outs() << " PIE";
4136       f &= ~MachO::MH_PIE;
4137     }
4138     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
4139       outs() << " NO_REEXPORTED_DYLIBS";
4140       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
4141     }
4142     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
4143       outs() << " MH_HAS_TLV_DESCRIPTORS";
4144       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
4145     }
4146     if (f & MachO::MH_NO_HEAP_EXECUTION) {
4147       outs() << " MH_NO_HEAP_EXECUTION";
4148       f &= ~MachO::MH_NO_HEAP_EXECUTION;
4149     }
4150     if (f & MachO::MH_APP_EXTENSION_SAFE) {
4151       outs() << " APP_EXTENSION_SAFE";
4152       f &= ~MachO::MH_APP_EXTENSION_SAFE;
4153     }
4154     if (f != 0 || flags == 0)
4155       outs() << format(" 0x%08" PRIx32, f);
4156   } else {
4157     outs() << format(" 0x%08" PRIx32, magic);
4158     outs() << format(" %7d", cputype);
4159     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4160     outs() << format("  0x%02" PRIx32,
4161                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4162     outs() << format("  %10u", filetype);
4163     outs() << format(" %5u", ncmds);
4164     outs() << format(" %10u", sizeofcmds);
4165     outs() << format(" 0x%08" PRIx32, flags);
4166   }
4167   outs() << "\n";
4168 }
4169
4170 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
4171                                 StringRef SegName, uint64_t vmaddr,
4172                                 uint64_t vmsize, uint64_t fileoff,
4173                                 uint64_t filesize, uint32_t maxprot,
4174                                 uint32_t initprot, uint32_t nsects,
4175                                 uint32_t flags, uint32_t object_size,
4176                                 bool verbose) {
4177   uint64_t expected_cmdsize;
4178   if (cmd == MachO::LC_SEGMENT) {
4179     outs() << "      cmd LC_SEGMENT\n";
4180     expected_cmdsize = nsects;
4181     expected_cmdsize *= sizeof(struct MachO::section);
4182     expected_cmdsize += sizeof(struct MachO::segment_command);
4183   } else {
4184     outs() << "      cmd LC_SEGMENT_64\n";
4185     expected_cmdsize = nsects;
4186     expected_cmdsize *= sizeof(struct MachO::section_64);
4187     expected_cmdsize += sizeof(struct MachO::segment_command_64);
4188   }
4189   outs() << "  cmdsize " << cmdsize;
4190   if (cmdsize != expected_cmdsize)
4191     outs() << " Inconsistent size\n";
4192   else
4193     outs() << "\n";
4194   outs() << "  segname " << SegName << "\n";
4195   if (cmd == MachO::LC_SEGMENT_64) {
4196     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
4197     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
4198   } else {
4199     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
4200     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
4201   }
4202   outs() << "  fileoff " << fileoff;
4203   if (fileoff > object_size)
4204     outs() << " (past end of file)\n";
4205   else
4206     outs() << "\n";
4207   outs() << " filesize " << filesize;
4208   if (fileoff + filesize > object_size)
4209     outs() << " (past end of file)\n";
4210   else
4211     outs() << "\n";
4212   if (verbose) {
4213     if ((maxprot &
4214          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4215            MachO::VM_PROT_EXECUTE)) != 0)
4216       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
4217     else {
4218       if (maxprot & MachO::VM_PROT_READ)
4219         outs() << "  maxprot r";
4220       else
4221         outs() << "  maxprot -";
4222       if (maxprot & MachO::VM_PROT_WRITE)
4223         outs() << "w";
4224       else
4225         outs() << "-";
4226       if (maxprot & MachO::VM_PROT_EXECUTE)
4227         outs() << "x\n";
4228       else
4229         outs() << "-\n";
4230     }
4231     if ((initprot &
4232          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4233            MachO::VM_PROT_EXECUTE)) != 0)
4234       outs() << "  initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
4235     else {
4236       if (initprot & MachO::VM_PROT_READ)
4237         outs() << " initprot r";
4238       else
4239         outs() << " initprot -";
4240       if (initprot & MachO::VM_PROT_WRITE)
4241         outs() << "w";
4242       else
4243         outs() << "-";
4244       if (initprot & MachO::VM_PROT_EXECUTE)
4245         outs() << "x\n";
4246       else
4247         outs() << "-\n";
4248     }
4249   } else {
4250     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
4251     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
4252   }
4253   outs() << "   nsects " << nsects << "\n";
4254   if (verbose) {
4255     outs() << "    flags";
4256     if (flags == 0)
4257       outs() << " (none)\n";
4258     else {
4259       if (flags & MachO::SG_HIGHVM) {
4260         outs() << " HIGHVM";
4261         flags &= ~MachO::SG_HIGHVM;
4262       }
4263       if (flags & MachO::SG_FVMLIB) {
4264         outs() << " FVMLIB";
4265         flags &= ~MachO::SG_FVMLIB;
4266       }
4267       if (flags & MachO::SG_NORELOC) {
4268         outs() << " NORELOC";
4269         flags &= ~MachO::SG_NORELOC;
4270       }
4271       if (flags & MachO::SG_PROTECTED_VERSION_1) {
4272         outs() << " PROTECTED_VERSION_1";
4273         flags &= ~MachO::SG_PROTECTED_VERSION_1;
4274       }
4275       if (flags)
4276         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
4277       else
4278         outs() << "\n";
4279     }
4280   } else {
4281     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
4282   }
4283 }
4284
4285 static void PrintSection(const char *sectname, const char *segname,
4286                          uint64_t addr, uint64_t size, uint32_t offset,
4287                          uint32_t align, uint32_t reloff, uint32_t nreloc,
4288                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
4289                          uint32_t cmd, const char *sg_segname,
4290                          uint32_t filetype, uint32_t object_size,
4291                          bool verbose) {
4292   outs() << "Section\n";
4293   outs() << "  sectname " << format("%.16s\n", sectname);
4294   outs() << "   segname " << format("%.16s", segname);
4295   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
4296     outs() << " (does not match segment)\n";
4297   else
4298     outs() << "\n";
4299   if (cmd == MachO::LC_SEGMENT_64) {
4300     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
4301     outs() << "      size " << format("0x%016" PRIx64, size);
4302   } else {
4303     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
4304     outs() << "      size " << format("0x%08" PRIx64, size);
4305   }
4306   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
4307     outs() << " (past end of file)\n";
4308   else
4309     outs() << "\n";
4310   outs() << "    offset " << offset;
4311   if (offset > object_size)
4312     outs() << " (past end of file)\n";
4313   else
4314     outs() << "\n";
4315   uint32_t align_shifted = 1 << align;
4316   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
4317   outs() << "    reloff " << reloff;
4318   if (reloff > object_size)
4319     outs() << " (past end of file)\n";
4320   else
4321     outs() << "\n";
4322   outs() << "    nreloc " << nreloc;
4323   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
4324     outs() << " (past end of file)\n";
4325   else
4326     outs() << "\n";
4327   uint32_t section_type = flags & MachO::SECTION_TYPE;
4328   if (verbose) {
4329     outs() << "      type";
4330     if (section_type == MachO::S_REGULAR)
4331       outs() << " S_REGULAR\n";
4332     else if (section_type == MachO::S_ZEROFILL)
4333       outs() << " S_ZEROFILL\n";
4334     else if (section_type == MachO::S_CSTRING_LITERALS)
4335       outs() << " S_CSTRING_LITERALS\n";
4336     else if (section_type == MachO::S_4BYTE_LITERALS)
4337       outs() << " S_4BYTE_LITERALS\n";
4338     else if (section_type == MachO::S_8BYTE_LITERALS)
4339       outs() << " S_8BYTE_LITERALS\n";
4340     else if (section_type == MachO::S_16BYTE_LITERALS)
4341       outs() << " S_16BYTE_LITERALS\n";
4342     else if (section_type == MachO::S_LITERAL_POINTERS)
4343       outs() << " S_LITERAL_POINTERS\n";
4344     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
4345       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
4346     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
4347       outs() << " S_LAZY_SYMBOL_POINTERS\n";
4348     else if (section_type == MachO::S_SYMBOL_STUBS)
4349       outs() << " S_SYMBOL_STUBS\n";
4350     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
4351       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
4352     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
4353       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
4354     else if (section_type == MachO::S_COALESCED)
4355       outs() << " S_COALESCED\n";
4356     else if (section_type == MachO::S_INTERPOSING)
4357       outs() << " S_INTERPOSING\n";
4358     else if (section_type == MachO::S_DTRACE_DOF)
4359       outs() << " S_DTRACE_DOF\n";
4360     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
4361       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
4362     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
4363       outs() << " S_THREAD_LOCAL_REGULAR\n";
4364     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
4365       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
4366     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
4367       outs() << " S_THREAD_LOCAL_VARIABLES\n";
4368     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4369       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
4370     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
4371       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
4372     else
4373       outs() << format("0x%08" PRIx32, section_type) << "\n";
4374     outs() << "attributes";
4375     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
4376     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
4377       outs() << " PURE_INSTRUCTIONS";
4378     if (section_attributes & MachO::S_ATTR_NO_TOC)
4379       outs() << " NO_TOC";
4380     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
4381       outs() << " STRIP_STATIC_SYMS";
4382     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
4383       outs() << " NO_DEAD_STRIP";
4384     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
4385       outs() << " LIVE_SUPPORT";
4386     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
4387       outs() << " SELF_MODIFYING_CODE";
4388     if (section_attributes & MachO::S_ATTR_DEBUG)
4389       outs() << " DEBUG";
4390     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
4391       outs() << " SOME_INSTRUCTIONS";
4392     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
4393       outs() << " EXT_RELOC";
4394     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
4395       outs() << " LOC_RELOC";
4396     if (section_attributes == 0)
4397       outs() << " (none)";
4398     outs() << "\n";
4399   } else
4400     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
4401   outs() << " reserved1 " << reserved1;
4402   if (section_type == MachO::S_SYMBOL_STUBS ||
4403       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
4404       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
4405       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
4406       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4407     outs() << " (index into indirect symbol table)\n";
4408   else
4409     outs() << "\n";
4410   outs() << " reserved2 " << reserved2;
4411   if (section_type == MachO::S_SYMBOL_STUBS)
4412     outs() << " (size of stubs)\n";
4413   else
4414     outs() << "\n";
4415 }
4416
4417 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
4418                                    uint32_t object_size) {
4419   outs() << "     cmd LC_SYMTAB\n";
4420   outs() << " cmdsize " << st.cmdsize;
4421   if (st.cmdsize != sizeof(struct MachO::symtab_command))
4422     outs() << " Incorrect size\n";
4423   else
4424     outs() << "\n";
4425   outs() << "  symoff " << st.symoff;
4426   if (st.symoff > object_size)
4427     outs() << " (past end of file)\n";
4428   else
4429     outs() << "\n";
4430   outs() << "   nsyms " << st.nsyms;
4431   uint64_t big_size;
4432   if (Is64Bit) {
4433     big_size = st.nsyms;
4434     big_size *= sizeof(struct MachO::nlist_64);
4435     big_size += st.symoff;
4436     if (big_size > object_size)
4437       outs() << " (past end of file)\n";
4438     else
4439       outs() << "\n";
4440   } else {
4441     big_size = st.nsyms;
4442     big_size *= sizeof(struct MachO::nlist);
4443     big_size += st.symoff;
4444     if (big_size > object_size)
4445       outs() << " (past end of file)\n";
4446     else
4447       outs() << "\n";
4448   }
4449   outs() << "  stroff " << st.stroff;
4450   if (st.stroff > object_size)
4451     outs() << " (past end of file)\n";
4452   else
4453     outs() << "\n";
4454   outs() << " strsize " << st.strsize;
4455   big_size = st.stroff;
4456   big_size += st.strsize;
4457   if (big_size > object_size)
4458     outs() << " (past end of file)\n";
4459   else
4460     outs() << "\n";
4461 }
4462
4463 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
4464                                      uint32_t nsyms, uint32_t object_size,
4465                                      bool Is64Bit) {
4466   outs() << "            cmd LC_DYSYMTAB\n";
4467   outs() << "        cmdsize " << dyst.cmdsize;
4468   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
4469     outs() << " Incorrect size\n";
4470   else
4471     outs() << "\n";
4472   outs() << "      ilocalsym " << dyst.ilocalsym;
4473   if (dyst.ilocalsym > nsyms)
4474     outs() << " (greater than the number of symbols)\n";
4475   else
4476     outs() << "\n";
4477   outs() << "      nlocalsym " << dyst.nlocalsym;
4478   uint64_t big_size;
4479   big_size = dyst.ilocalsym;
4480   big_size += dyst.nlocalsym;
4481   if (big_size > nsyms)
4482     outs() << " (past the end of the symbol table)\n";
4483   else
4484     outs() << "\n";
4485   outs() << "     iextdefsym " << dyst.iextdefsym;
4486   if (dyst.iextdefsym > nsyms)
4487     outs() << " (greater than the number of symbols)\n";
4488   else
4489     outs() << "\n";
4490   outs() << "     nextdefsym " << dyst.nextdefsym;
4491   big_size = dyst.iextdefsym;
4492   big_size += dyst.nextdefsym;
4493   if (big_size > nsyms)
4494     outs() << " (past the end of the symbol table)\n";
4495   else
4496     outs() << "\n";
4497   outs() << "      iundefsym " << dyst.iundefsym;
4498   if (dyst.iundefsym > nsyms)
4499     outs() << " (greater than the number of symbols)\n";
4500   else
4501     outs() << "\n";
4502   outs() << "      nundefsym " << dyst.nundefsym;
4503   big_size = dyst.iundefsym;
4504   big_size += dyst.nundefsym;
4505   if (big_size > nsyms)
4506     outs() << " (past the end of the symbol table)\n";
4507   else
4508     outs() << "\n";
4509   outs() << "         tocoff " << dyst.tocoff;
4510   if (dyst.tocoff > object_size)
4511     outs() << " (past end of file)\n";
4512   else
4513     outs() << "\n";
4514   outs() << "           ntoc " << dyst.ntoc;
4515   big_size = dyst.ntoc;
4516   big_size *= sizeof(struct MachO::dylib_table_of_contents);
4517   big_size += dyst.tocoff;
4518   if (big_size > object_size)
4519     outs() << " (past end of file)\n";
4520   else
4521     outs() << "\n";
4522   outs() << "      modtaboff " << dyst.modtaboff;
4523   if (dyst.modtaboff > object_size)
4524     outs() << " (past end of file)\n";
4525   else
4526     outs() << "\n";
4527   outs() << "        nmodtab " << dyst.nmodtab;
4528   uint64_t modtabend;
4529   if (Is64Bit) {
4530     modtabend = dyst.nmodtab;
4531     modtabend *= sizeof(struct MachO::dylib_module_64);
4532     modtabend += dyst.modtaboff;
4533   } else {
4534     modtabend = dyst.nmodtab;
4535     modtabend *= sizeof(struct MachO::dylib_module);
4536     modtabend += dyst.modtaboff;
4537   }
4538   if (modtabend > object_size)
4539     outs() << " (past end of file)\n";
4540   else
4541     outs() << "\n";
4542   outs() << "   extrefsymoff " << dyst.extrefsymoff;
4543   if (dyst.extrefsymoff > object_size)
4544     outs() << " (past end of file)\n";
4545   else
4546     outs() << "\n";
4547   outs() << "    nextrefsyms " << dyst.nextrefsyms;
4548   big_size = dyst.nextrefsyms;
4549   big_size *= sizeof(struct MachO::dylib_reference);
4550   big_size += dyst.extrefsymoff;
4551   if (big_size > object_size)
4552     outs() << " (past end of file)\n";
4553   else
4554     outs() << "\n";
4555   outs() << " indirectsymoff " << dyst.indirectsymoff;
4556   if (dyst.indirectsymoff > object_size)
4557     outs() << " (past end of file)\n";
4558   else
4559     outs() << "\n";
4560   outs() << "  nindirectsyms " << dyst.nindirectsyms;
4561   big_size = dyst.nindirectsyms;
4562   big_size *= sizeof(uint32_t);
4563   big_size += dyst.indirectsymoff;
4564   if (big_size > object_size)
4565     outs() << " (past end of file)\n";
4566   else
4567     outs() << "\n";
4568   outs() << "      extreloff " << dyst.extreloff;
4569   if (dyst.extreloff > object_size)
4570     outs() << " (past end of file)\n";
4571   else
4572     outs() << "\n";
4573   outs() << "        nextrel " << dyst.nextrel;
4574   big_size = dyst.nextrel;
4575   big_size *= sizeof(struct MachO::relocation_info);
4576   big_size += dyst.extreloff;
4577   if (big_size > object_size)
4578     outs() << " (past end of file)\n";
4579   else
4580     outs() << "\n";
4581   outs() << "      locreloff " << dyst.locreloff;
4582   if (dyst.locreloff > object_size)
4583     outs() << " (past end of file)\n";
4584   else
4585     outs() << "\n";
4586   outs() << "        nlocrel " << dyst.nlocrel;
4587   big_size = dyst.nlocrel;
4588   big_size *= sizeof(struct MachO::relocation_info);
4589   big_size += dyst.locreloff;
4590   if (big_size > object_size)
4591     outs() << " (past end of file)\n";
4592   else
4593     outs() << "\n";
4594 }
4595
4596 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
4597                                      uint32_t object_size) {
4598   if (dc.cmd == MachO::LC_DYLD_INFO)
4599     outs() << "            cmd LC_DYLD_INFO\n";
4600   else
4601     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
4602   outs() << "        cmdsize " << dc.cmdsize;
4603   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
4604     outs() << " Incorrect size\n";
4605   else
4606     outs() << "\n";
4607   outs() << "     rebase_off " << dc.rebase_off;
4608   if (dc.rebase_off > object_size)
4609     outs() << " (past end of file)\n";
4610   else
4611     outs() << "\n";
4612   outs() << "    rebase_size " << dc.rebase_size;
4613   uint64_t big_size;
4614   big_size = dc.rebase_off;
4615   big_size += dc.rebase_size;
4616   if (big_size > object_size)
4617     outs() << " (past end of file)\n";
4618   else
4619     outs() << "\n";
4620   outs() << "       bind_off " << dc.bind_off;
4621   if (dc.bind_off > object_size)
4622     outs() << " (past end of file)\n";
4623   else
4624     outs() << "\n";
4625   outs() << "      bind_size " << dc.bind_size;
4626   big_size = dc.bind_off;
4627   big_size += dc.bind_size;
4628   if (big_size > object_size)
4629     outs() << " (past end of file)\n";
4630   else
4631     outs() << "\n";
4632   outs() << "  weak_bind_off " << dc.weak_bind_off;
4633   if (dc.weak_bind_off > object_size)
4634     outs() << " (past end of file)\n";
4635   else
4636     outs() << "\n";
4637   outs() << " weak_bind_size " << dc.weak_bind_size;
4638   big_size = dc.weak_bind_off;
4639   big_size += dc.weak_bind_size;
4640   if (big_size > object_size)
4641     outs() << " (past end of file)\n";
4642   else
4643     outs() << "\n";
4644   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
4645   if (dc.lazy_bind_off > object_size)
4646     outs() << " (past end of file)\n";
4647   else
4648     outs() << "\n";
4649   outs() << " lazy_bind_size " << dc.lazy_bind_size;
4650   big_size = dc.lazy_bind_off;
4651   big_size += dc.lazy_bind_size;
4652   if (big_size > object_size)
4653     outs() << " (past end of file)\n";
4654   else
4655     outs() << "\n";
4656   outs() << "     export_off " << dc.export_off;
4657   if (dc.export_off > object_size)
4658     outs() << " (past end of file)\n";
4659   else
4660     outs() << "\n";
4661   outs() << "    export_size " << dc.export_size;
4662   big_size = dc.export_off;
4663   big_size += dc.export_size;
4664   if (big_size > object_size)
4665     outs() << " (past end of file)\n";
4666   else
4667     outs() << "\n";
4668 }
4669
4670 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
4671                                  const char *Ptr) {
4672   if (dyld.cmd == MachO::LC_ID_DYLINKER)
4673     outs() << "          cmd LC_ID_DYLINKER\n";
4674   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
4675     outs() << "          cmd LC_LOAD_DYLINKER\n";
4676   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
4677     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
4678   else
4679     outs() << "          cmd ?(" << dyld.cmd << ")\n";
4680   outs() << "      cmdsize " << dyld.cmdsize;
4681   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4682     outs() << " Incorrect size\n";
4683   else
4684     outs() << "\n";
4685   if (dyld.name >= dyld.cmdsize)
4686     outs() << "         name ?(bad offset " << dyld.name << ")\n";
4687   else {
4688     const char *P = (const char *)(Ptr) + dyld.name;
4689     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
4690   }
4691 }
4692
4693 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4694   outs() << "     cmd LC_UUID\n";
4695   outs() << " cmdsize " << uuid.cmdsize;
4696   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4697     outs() << " Incorrect size\n";
4698   else
4699     outs() << "\n";
4700   outs() << "    uuid ";
4701   outs() << format("%02" PRIX32, uuid.uuid[0]);
4702   outs() << format("%02" PRIX32, uuid.uuid[1]);
4703   outs() << format("%02" PRIX32, uuid.uuid[2]);
4704   outs() << format("%02" PRIX32, uuid.uuid[3]);
4705   outs() << "-";
4706   outs() << format("%02" PRIX32, uuid.uuid[4]);
4707   outs() << format("%02" PRIX32, uuid.uuid[5]);
4708   outs() << "-";
4709   outs() << format("%02" PRIX32, uuid.uuid[6]);
4710   outs() << format("%02" PRIX32, uuid.uuid[7]);
4711   outs() << "-";
4712   outs() << format("%02" PRIX32, uuid.uuid[8]);
4713   outs() << format("%02" PRIX32, uuid.uuid[9]);
4714   outs() << "-";
4715   outs() << format("%02" PRIX32, uuid.uuid[10]);
4716   outs() << format("%02" PRIX32, uuid.uuid[11]);
4717   outs() << format("%02" PRIX32, uuid.uuid[12]);
4718   outs() << format("%02" PRIX32, uuid.uuid[13]);
4719   outs() << format("%02" PRIX32, uuid.uuid[14]);
4720   outs() << format("%02" PRIX32, uuid.uuid[15]);
4721   outs() << "\n";
4722 }
4723
4724 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
4725   outs() << "          cmd LC_RPATH\n";
4726   outs() << "      cmdsize " << rpath.cmdsize;
4727   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4728     outs() << " Incorrect size\n";
4729   else
4730     outs() << "\n";
4731   if (rpath.path >= rpath.cmdsize)
4732     outs() << "         path ?(bad offset " << rpath.path << ")\n";
4733   else {
4734     const char *P = (const char *)(Ptr) + rpath.path;
4735     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
4736   }
4737 }
4738
4739 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4740   if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4741     outs() << "      cmd LC_VERSION_MIN_MACOSX\n";
4742   else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4743     outs() << "      cmd LC_VERSION_MIN_IPHONEOS\n";
4744   else
4745     outs() << "      cmd " << vd.cmd << " (?)\n";
4746   outs() << "  cmdsize " << vd.cmdsize;
4747   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4748     outs() << " Incorrect size\n";
4749   else
4750     outs() << "\n";
4751   outs() << "  version " << ((vd.version >> 16) & 0xffff) << "."
4752          << ((vd.version >> 8) & 0xff);
4753   if ((vd.version & 0xff) != 0)
4754     outs() << "." << (vd.version & 0xff);
4755   outs() << "\n";
4756   if (vd.sdk == 0)
4757     outs() << "      sdk n/a";
4758   else {
4759     outs() << "      sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4760            << ((vd.sdk >> 8) & 0xff);
4761   }
4762   if ((vd.sdk & 0xff) != 0)
4763     outs() << "." << (vd.sdk & 0xff);
4764   outs() << "\n";
4765 }
4766
4767 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4768   outs() << "      cmd LC_SOURCE_VERSION\n";
4769   outs() << "  cmdsize " << sd.cmdsize;
4770   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4771     outs() << " Incorrect size\n";
4772   else
4773     outs() << "\n";
4774   uint64_t a = (sd.version >> 40) & 0xffffff;
4775   uint64_t b = (sd.version >> 30) & 0x3ff;
4776   uint64_t c = (sd.version >> 20) & 0x3ff;
4777   uint64_t d = (sd.version >> 10) & 0x3ff;
4778   uint64_t e = sd.version & 0x3ff;
4779   outs() << "  version " << a << "." << b;
4780   if (e != 0)
4781     outs() << "." << c << "." << d << "." << e;
4782   else if (d != 0)
4783     outs() << "." << c << "." << d;
4784   else if (c != 0)
4785     outs() << "." << c;
4786   outs() << "\n";
4787 }
4788
4789 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4790   outs() << "       cmd LC_MAIN\n";
4791   outs() << "   cmdsize " << ep.cmdsize;
4792   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4793     outs() << " Incorrect size\n";
4794   else
4795     outs() << "\n";
4796   outs() << "  entryoff " << ep.entryoff << "\n";
4797   outs() << " stacksize " << ep.stacksize << "\n";
4798 }
4799
4800 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4801                                        uint32_t object_size) {
4802   outs() << "          cmd LC_ENCRYPTION_INFO\n";
4803   outs() << "      cmdsize " << ec.cmdsize;
4804   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4805     outs() << " Incorrect size\n";
4806   else
4807     outs() << "\n";
4808   outs() << "     cryptoff " << ec.cryptoff;
4809   if (ec.cryptoff > object_size)
4810     outs() << " (past end of file)\n";
4811   else
4812     outs() << "\n";
4813   outs() << "    cryptsize " << ec.cryptsize;
4814   if (ec.cryptsize > object_size)
4815     outs() << " (past end of file)\n";
4816   else
4817     outs() << "\n";
4818   outs() << "      cryptid " << ec.cryptid << "\n";
4819 }
4820
4821 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
4822                                          uint32_t object_size) {
4823   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
4824   outs() << "      cmdsize " << ec.cmdsize;
4825   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4826     outs() << " Incorrect size\n";
4827   else
4828     outs() << "\n";
4829   outs() << "     cryptoff " << ec.cryptoff;
4830   if (ec.cryptoff > object_size)
4831     outs() << " (past end of file)\n";
4832   else
4833     outs() << "\n";
4834   outs() << "    cryptsize " << ec.cryptsize;
4835   if (ec.cryptsize > object_size)
4836     outs() << " (past end of file)\n";
4837   else
4838     outs() << "\n";
4839   outs() << "      cryptid " << ec.cryptid << "\n";
4840   outs() << "          pad " << ec.pad << "\n";
4841 }
4842
4843 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4844                                      const char *Ptr) {
4845   outs() << "     cmd LC_LINKER_OPTION\n";
4846   outs() << " cmdsize " << lo.cmdsize;
4847   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4848     outs() << " Incorrect size\n";
4849   else
4850     outs() << "\n";
4851   outs() << "   count " << lo.count << "\n";
4852   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4853   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4854   uint32_t i = 0;
4855   while (left > 0) {
4856     while (*string == '\0' && left > 0) {
4857       string++;
4858       left--;
4859     }
4860     if (left > 0) {
4861       i++;
4862       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
4863       uint32_t NullPos = StringRef(string, left).find('\0');
4864       uint32_t len = std::min(NullPos, left) + 1;
4865       string += len;
4866       left -= len;
4867     }
4868   }
4869   if (lo.count != i)
4870     outs() << "   count " << lo.count << " does not match number of strings "
4871            << i << "\n";
4872 }
4873
4874 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4875                                      const char *Ptr) {
4876   outs() << "          cmd LC_SUB_FRAMEWORK\n";
4877   outs() << "      cmdsize " << sub.cmdsize;
4878   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4879     outs() << " Incorrect size\n";
4880   else
4881     outs() << "\n";
4882   if (sub.umbrella < sub.cmdsize) {
4883     const char *P = Ptr + sub.umbrella;
4884     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
4885   } else {
4886     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
4887   }
4888 }
4889
4890 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4891                                     const char *Ptr) {
4892   outs() << "          cmd LC_SUB_UMBRELLA\n";
4893   outs() << "      cmdsize " << sub.cmdsize;
4894   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4895     outs() << " Incorrect size\n";
4896   else
4897     outs() << "\n";
4898   if (sub.sub_umbrella < sub.cmdsize) {
4899     const char *P = Ptr + sub.sub_umbrella;
4900     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4901   } else {
4902     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4903   }
4904 }
4905
4906 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4907                                    const char *Ptr) {
4908   outs() << "          cmd LC_SUB_LIBRARY\n";
4909   outs() << "      cmdsize " << sub.cmdsize;
4910   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4911     outs() << " Incorrect size\n";
4912   else
4913     outs() << "\n";
4914   if (sub.sub_library < sub.cmdsize) {
4915     const char *P = Ptr + sub.sub_library;
4916     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
4917   } else {
4918     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
4919   }
4920 }
4921
4922 static void PrintSubClientCommand(MachO::sub_client_command sub,
4923                                   const char *Ptr) {
4924   outs() << "          cmd LC_SUB_CLIENT\n";
4925   outs() << "      cmdsize " << sub.cmdsize;
4926   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4927     outs() << " Incorrect size\n";
4928   else
4929     outs() << "\n";
4930   if (sub.client < sub.cmdsize) {
4931     const char *P = Ptr + sub.client;
4932     outs() << "       client " << P << " (offset " << sub.client << ")\n";
4933   } else {
4934     outs() << "       client ?(bad offset " << sub.client << ")\n";
4935   }
4936 }
4937
4938 static void PrintRoutinesCommand(MachO::routines_command r) {
4939   outs() << "          cmd LC_ROUTINES\n";
4940   outs() << "      cmdsize " << r.cmdsize;
4941   if (r.cmdsize != sizeof(struct MachO::routines_command))
4942     outs() << " Incorrect size\n";
4943   else
4944     outs() << "\n";
4945   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4946   outs() << "  init_module " << r.init_module << "\n";
4947   outs() << "    reserved1 " << r.reserved1 << "\n";
4948   outs() << "    reserved2 " << r.reserved2 << "\n";
4949   outs() << "    reserved3 " << r.reserved3 << "\n";
4950   outs() << "    reserved4 " << r.reserved4 << "\n";
4951   outs() << "    reserved5 " << r.reserved5 << "\n";
4952   outs() << "    reserved6 " << r.reserved6 << "\n";
4953 }
4954
4955 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4956   outs() << "          cmd LC_ROUTINES_64\n";
4957   outs() << "      cmdsize " << r.cmdsize;
4958   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4959     outs() << " Incorrect size\n";
4960   else
4961     outs() << "\n";
4962   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4963   outs() << "  init_module " << r.init_module << "\n";
4964   outs() << "    reserved1 " << r.reserved1 << "\n";
4965   outs() << "    reserved2 " << r.reserved2 << "\n";
4966   outs() << "    reserved3 " << r.reserved3 << "\n";
4967   outs() << "    reserved4 " << r.reserved4 << "\n";
4968   outs() << "    reserved5 " << r.reserved5 << "\n";
4969   outs() << "    reserved6 " << r.reserved6 << "\n";
4970 }
4971
4972 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4973   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
4974   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4975   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4976   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
4977   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4978   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4979   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
4980   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4981   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4982   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
4983   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4984   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4985   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
4986   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4987   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4988   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
4989   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4990   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
4991   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
4992   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4993   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4994 }
4995
4996 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
4997   uint32_t f;
4998   outs() << "\t      mmst_reg  ";
4999   for (f = 0; f < 10; f++)
5000     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
5001   outs() << "\n";
5002   outs() << "\t      mmst_rsrv ";
5003   for (f = 0; f < 6; f++)
5004     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
5005   outs() << "\n";
5006 }
5007
5008 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
5009   uint32_t f;
5010   outs() << "\t      xmm_reg ";
5011   for (f = 0; f < 16; f++)
5012     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
5013   outs() << "\n";
5014 }
5015
5016 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
5017   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
5018   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
5019   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
5020   outs() << " denorm " << fpu.fpu_fcw.denorm;
5021   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
5022   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
5023   outs() << " undfl " << fpu.fpu_fcw.undfl;
5024   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
5025   outs() << "\t\t     pc ";
5026   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
5027     outs() << "FP_PREC_24B ";
5028   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
5029     outs() << "FP_PREC_53B ";
5030   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
5031     outs() << "FP_PREC_64B ";
5032   else
5033     outs() << fpu.fpu_fcw.pc << " ";
5034   outs() << "rc ";
5035   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
5036     outs() << "FP_RND_NEAR ";
5037   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
5038     outs() << "FP_RND_DOWN ";
5039   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
5040     outs() << "FP_RND_UP ";
5041   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
5042     outs() << "FP_CHOP ";
5043   outs() << "\n";
5044   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
5045   outs() << " denorm " << fpu.fpu_fsw.denorm;
5046   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
5047   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
5048   outs() << " undfl " << fpu.fpu_fsw.undfl;
5049   outs() << " precis " << fpu.fpu_fsw.precis;
5050   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
5051   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
5052   outs() << " c0 " << fpu.fpu_fsw.c0;
5053   outs() << " c1 " << fpu.fpu_fsw.c1;
5054   outs() << " c2 " << fpu.fpu_fsw.c2;
5055   outs() << " tos " << fpu.fpu_fsw.tos;
5056   outs() << " c3 " << fpu.fpu_fsw.c3;
5057   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
5058   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
5059   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
5060   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
5061   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
5062   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
5063   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
5064   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
5065   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
5066   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
5067   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
5068   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
5069   outs() << "\n";
5070   outs() << "\t    fpu_stmm0:\n";
5071   Print_mmst_reg(fpu.fpu_stmm0);
5072   outs() << "\t    fpu_stmm1:\n";
5073   Print_mmst_reg(fpu.fpu_stmm1);
5074   outs() << "\t    fpu_stmm2:\n";
5075   Print_mmst_reg(fpu.fpu_stmm2);
5076   outs() << "\t    fpu_stmm3:\n";
5077   Print_mmst_reg(fpu.fpu_stmm3);
5078   outs() << "\t    fpu_stmm4:\n";
5079   Print_mmst_reg(fpu.fpu_stmm4);
5080   outs() << "\t    fpu_stmm5:\n";
5081   Print_mmst_reg(fpu.fpu_stmm5);
5082   outs() << "\t    fpu_stmm6:\n";
5083   Print_mmst_reg(fpu.fpu_stmm6);
5084   outs() << "\t    fpu_stmm7:\n";
5085   Print_mmst_reg(fpu.fpu_stmm7);
5086   outs() << "\t    fpu_xmm0:\n";
5087   Print_xmm_reg(fpu.fpu_xmm0);
5088   outs() << "\t    fpu_xmm1:\n";
5089   Print_xmm_reg(fpu.fpu_xmm1);
5090   outs() << "\t    fpu_xmm2:\n";
5091   Print_xmm_reg(fpu.fpu_xmm2);
5092   outs() << "\t    fpu_xmm3:\n";
5093   Print_xmm_reg(fpu.fpu_xmm3);
5094   outs() << "\t    fpu_xmm4:\n";
5095   Print_xmm_reg(fpu.fpu_xmm4);
5096   outs() << "\t    fpu_xmm5:\n";
5097   Print_xmm_reg(fpu.fpu_xmm5);
5098   outs() << "\t    fpu_xmm6:\n";
5099   Print_xmm_reg(fpu.fpu_xmm6);
5100   outs() << "\t    fpu_xmm7:\n";
5101   Print_xmm_reg(fpu.fpu_xmm7);
5102   outs() << "\t    fpu_xmm8:\n";
5103   Print_xmm_reg(fpu.fpu_xmm8);
5104   outs() << "\t    fpu_xmm9:\n";
5105   Print_xmm_reg(fpu.fpu_xmm9);
5106   outs() << "\t    fpu_xmm10:\n";
5107   Print_xmm_reg(fpu.fpu_xmm10);
5108   outs() << "\t    fpu_xmm11:\n";
5109   Print_xmm_reg(fpu.fpu_xmm11);
5110   outs() << "\t    fpu_xmm12:\n";
5111   Print_xmm_reg(fpu.fpu_xmm12);
5112   outs() << "\t    fpu_xmm13:\n";
5113   Print_xmm_reg(fpu.fpu_xmm13);
5114   outs() << "\t    fpu_xmm14:\n";
5115   Print_xmm_reg(fpu.fpu_xmm14);
5116   outs() << "\t    fpu_xmm15:\n";
5117   Print_xmm_reg(fpu.fpu_xmm15);
5118   outs() << "\t    fpu_rsrv4:\n";
5119   for (uint32_t f = 0; f < 6; f++) {
5120     outs() << "\t            ";
5121     for (uint32_t g = 0; g < 16; g++)
5122       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
5123     outs() << "\n";
5124   }
5125   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
5126   outs() << "\n";
5127 }
5128
5129 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
5130   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
5131   outs() << " err " << format("0x%08" PRIx32, exc64.err);
5132   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
5133 }
5134
5135 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
5136                                bool isLittleEndian, uint32_t cputype) {
5137   if (t.cmd == MachO::LC_THREAD)
5138     outs() << "        cmd LC_THREAD\n";
5139   else if (t.cmd == MachO::LC_UNIXTHREAD)
5140     outs() << "        cmd LC_UNIXTHREAD\n";
5141   else
5142     outs() << "        cmd " << t.cmd << " (unknown)\n";
5143   outs() << "    cmdsize " << t.cmdsize;
5144   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
5145     outs() << " Incorrect size\n";
5146   else
5147     outs() << "\n";
5148
5149   const char *begin = Ptr + sizeof(struct MachO::thread_command);
5150   const char *end = Ptr + t.cmdsize;
5151   uint32_t flavor, count, left;
5152   if (cputype == MachO::CPU_TYPE_X86_64) {
5153     while (begin < end) {
5154       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5155         memcpy((char *)&flavor, begin, sizeof(uint32_t));
5156         begin += sizeof(uint32_t);
5157       } else {
5158         flavor = 0;
5159         begin = end;
5160       }
5161       if (isLittleEndian != sys::IsLittleEndianHost)
5162         sys::swapByteOrder(flavor);
5163       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5164         memcpy((char *)&count, begin, sizeof(uint32_t));
5165         begin += sizeof(uint32_t);
5166       } else {
5167         count = 0;
5168         begin = end;
5169       }
5170       if (isLittleEndian != sys::IsLittleEndianHost)
5171         sys::swapByteOrder(count);
5172       if (flavor == MachO::x86_THREAD_STATE64) {
5173         outs() << "     flavor x86_THREAD_STATE64\n";
5174         if (count == MachO::x86_THREAD_STATE64_COUNT)
5175           outs() << "      count x86_THREAD_STATE64_COUNT\n";
5176         else
5177           outs() << "      count " << count
5178                  << " (not x86_THREAD_STATE64_COUNT)\n";
5179         MachO::x86_thread_state64_t cpu64;
5180         left = end - begin;
5181         if (left >= sizeof(MachO::x86_thread_state64_t)) {
5182           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
5183           begin += sizeof(MachO::x86_thread_state64_t);
5184         } else {
5185           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
5186           memcpy(&cpu64, begin, left);
5187           begin += left;
5188         }
5189         if (isLittleEndian != sys::IsLittleEndianHost)
5190           swapStruct(cpu64);
5191         Print_x86_thread_state64_t(cpu64);
5192       } else if (flavor == MachO::x86_THREAD_STATE) {
5193         outs() << "     flavor x86_THREAD_STATE\n";
5194         if (count == MachO::x86_THREAD_STATE_COUNT)
5195           outs() << "      count x86_THREAD_STATE_COUNT\n";
5196         else
5197           outs() << "      count " << count
5198                  << " (not x86_THREAD_STATE_COUNT)\n";
5199         struct MachO::x86_thread_state_t ts;
5200         left = end - begin;
5201         if (left >= sizeof(MachO::x86_thread_state_t)) {
5202           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
5203           begin += sizeof(MachO::x86_thread_state_t);
5204         } else {
5205           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
5206           memcpy(&ts, begin, left);
5207           begin += left;
5208         }
5209         if (isLittleEndian != sys::IsLittleEndianHost)
5210           swapStruct(ts);
5211         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
5212           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
5213           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
5214             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
5215           else
5216             outs() << "tsh.count " << ts.tsh.count
5217                    << " (not x86_THREAD_STATE64_COUNT\n";
5218           Print_x86_thread_state64_t(ts.uts.ts64);
5219         } else {
5220           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
5221                  << ts.tsh.count << "\n";
5222         }
5223       } else if (flavor == MachO::x86_FLOAT_STATE) {
5224         outs() << "     flavor x86_FLOAT_STATE\n";
5225         if (count == MachO::x86_FLOAT_STATE_COUNT)
5226           outs() << "      count x86_FLOAT_STATE_COUNT\n";
5227         else
5228           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
5229         struct MachO::x86_float_state_t fs;
5230         left = end - begin;
5231         if (left >= sizeof(MachO::x86_float_state_t)) {
5232           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
5233           begin += sizeof(MachO::x86_float_state_t);
5234         } else {
5235           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
5236           memcpy(&fs, begin, left);
5237           begin += left;
5238         }
5239         if (isLittleEndian != sys::IsLittleEndianHost)
5240           swapStruct(fs);
5241         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
5242           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
5243           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
5244             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
5245           else
5246             outs() << "fsh.count " << fs.fsh.count
5247                    << " (not x86_FLOAT_STATE64_COUNT\n";
5248           Print_x86_float_state_t(fs.ufs.fs64);
5249         } else {
5250           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
5251                  << fs.fsh.count << "\n";
5252         }
5253       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
5254         outs() << "     flavor x86_EXCEPTION_STATE\n";
5255         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
5256           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
5257         else
5258           outs() << "      count " << count
5259                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
5260         struct MachO::x86_exception_state_t es;
5261         left = end - begin;
5262         if (left >= sizeof(MachO::x86_exception_state_t)) {
5263           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
5264           begin += sizeof(MachO::x86_exception_state_t);
5265         } else {
5266           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
5267           memcpy(&es, begin, left);
5268           begin += left;
5269         }
5270         if (isLittleEndian != sys::IsLittleEndianHost)
5271           swapStruct(es);
5272         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
5273           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
5274           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
5275             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
5276           else
5277             outs() << "\t    esh.count " << es.esh.count
5278                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
5279           Print_x86_exception_state_t(es.ues.es64);
5280         } else {
5281           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
5282                  << es.esh.count << "\n";
5283         }
5284       } else {
5285         outs() << "     flavor " << flavor << " (unknown)\n";
5286         outs() << "      count " << count << "\n";
5287         outs() << "      state (unknown)\n";
5288         begin += count * sizeof(uint32_t);
5289       }
5290     }
5291   } else {
5292     while (begin < end) {
5293       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5294         memcpy((char *)&flavor, begin, sizeof(uint32_t));
5295         begin += sizeof(uint32_t);
5296       } else {
5297         flavor = 0;
5298         begin = end;
5299       }
5300       if (isLittleEndian != sys::IsLittleEndianHost)
5301         sys::swapByteOrder(flavor);
5302       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5303         memcpy((char *)&count, begin, sizeof(uint32_t));
5304         begin += sizeof(uint32_t);
5305       } else {
5306         count = 0;
5307         begin = end;
5308       }
5309       if (isLittleEndian != sys::IsLittleEndianHost)
5310         sys::swapByteOrder(count);
5311       outs() << "     flavor " << flavor << "\n";
5312       outs() << "      count " << count << "\n";
5313       outs() << "      state (Unknown cputype/cpusubtype)\n";
5314       begin += count * sizeof(uint32_t);
5315     }
5316   }
5317 }
5318
5319 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
5320   if (dl.cmd == MachO::LC_ID_DYLIB)
5321     outs() << "          cmd LC_ID_DYLIB\n";
5322   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
5323     outs() << "          cmd LC_LOAD_DYLIB\n";
5324   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
5325     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
5326   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
5327     outs() << "          cmd LC_REEXPORT_DYLIB\n";
5328   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
5329     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
5330   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
5331     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
5332   else
5333     outs() << "          cmd " << dl.cmd << " (unknown)\n";
5334   outs() << "      cmdsize " << dl.cmdsize;
5335   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
5336     outs() << " Incorrect size\n";
5337   else
5338     outs() << "\n";
5339   if (dl.dylib.name < dl.cmdsize) {
5340     const char *P = (const char *)(Ptr) + dl.dylib.name;
5341     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
5342   } else {
5343     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
5344   }
5345   outs() << "   time stamp " << dl.dylib.timestamp << " ";
5346   time_t t = dl.dylib.timestamp;
5347   outs() << ctime(&t);
5348   outs() << "      current version ";
5349   if (dl.dylib.current_version == 0xffffffff)
5350     outs() << "n/a\n";
5351   else
5352     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
5353            << ((dl.dylib.current_version >> 8) & 0xff) << "."
5354            << (dl.dylib.current_version & 0xff) << "\n";
5355   outs() << "compatibility version ";
5356   if (dl.dylib.compatibility_version == 0xffffffff)
5357     outs() << "n/a\n";
5358   else
5359     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
5360            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
5361            << (dl.dylib.compatibility_version & 0xff) << "\n";
5362 }
5363
5364 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
5365                                      uint32_t object_size) {
5366   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
5367     outs() << "      cmd LC_FUNCTION_STARTS\n";
5368   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
5369     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
5370   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
5371     outs() << "      cmd LC_FUNCTION_STARTS\n";
5372   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
5373     outs() << "      cmd LC_DATA_IN_CODE\n";
5374   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
5375     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
5376   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
5377     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
5378   else
5379     outs() << "      cmd " << ld.cmd << " (?)\n";
5380   outs() << "  cmdsize " << ld.cmdsize;
5381   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
5382     outs() << " Incorrect size\n";
5383   else
5384     outs() << "\n";
5385   outs() << "  dataoff " << ld.dataoff;
5386   if (ld.dataoff > object_size)
5387     outs() << " (past end of file)\n";
5388   else
5389     outs() << "\n";
5390   outs() << " datasize " << ld.datasize;
5391   uint64_t big_size = ld.dataoff;
5392   big_size += ld.datasize;
5393   if (big_size > object_size)
5394     outs() << " (past end of file)\n";
5395   else
5396     outs() << "\n";
5397 }
5398
5399 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
5400                               uint32_t filetype, uint32_t cputype,
5401                               bool verbose) {
5402   if (ncmds == 0)
5403     return;
5404   StringRef Buf = Obj->getData();
5405   MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
5406   for (unsigned i = 0;; ++i) {
5407     outs() << "Load command " << i << "\n";
5408     if (Command.C.cmd == MachO::LC_SEGMENT) {
5409       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
5410       const char *sg_segname = SLC.segname;
5411       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
5412                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
5413                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
5414                           verbose);
5415       for (unsigned j = 0; j < SLC.nsects; j++) {
5416         MachO::section S = Obj->getSection(Command, j);
5417         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
5418                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
5419                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
5420       }
5421     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
5422       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
5423       const char *sg_segname = SLC_64.segname;
5424       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
5425                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
5426                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
5427                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
5428       for (unsigned j = 0; j < SLC_64.nsects; j++) {
5429         MachO::section_64 S_64 = Obj->getSection64(Command, j);
5430         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
5431                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
5432                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
5433                      sg_segname, filetype, Buf.size(), verbose);
5434       }
5435     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
5436       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5437       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
5438     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
5439       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
5440       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5441       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
5442                                Obj->is64Bit());
5443     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
5444                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
5445       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
5446       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
5447     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
5448                Command.C.cmd == MachO::LC_ID_DYLINKER ||
5449                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
5450       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
5451       PrintDyldLoadCommand(Dyld, Command.Ptr);
5452     } else if (Command.C.cmd == MachO::LC_UUID) {
5453       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
5454       PrintUuidLoadCommand(Uuid);
5455     } else if (Command.C.cmd == MachO::LC_RPATH) {
5456       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
5457       PrintRpathLoadCommand(Rpath, Command.Ptr);
5458     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
5459                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
5460       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
5461       PrintVersionMinLoadCommand(Vd);
5462     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
5463       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
5464       PrintSourceVersionCommand(Sd);
5465     } else if (Command.C.cmd == MachO::LC_MAIN) {
5466       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
5467       PrintEntryPointCommand(Ep);
5468     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
5469       MachO::encryption_info_command Ei =
5470           Obj->getEncryptionInfoCommand(Command);
5471       PrintEncryptionInfoCommand(Ei, Buf.size());
5472     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
5473       MachO::encryption_info_command_64 Ei =
5474           Obj->getEncryptionInfoCommand64(Command);
5475       PrintEncryptionInfoCommand64(Ei, Buf.size());
5476     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
5477       MachO::linker_option_command Lo =
5478           Obj->getLinkerOptionLoadCommand(Command);
5479       PrintLinkerOptionCommand(Lo, Command.Ptr);
5480     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
5481       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
5482       PrintSubFrameworkCommand(Sf, Command.Ptr);
5483     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
5484       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
5485       PrintSubUmbrellaCommand(Sf, Command.Ptr);
5486     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
5487       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
5488       PrintSubLibraryCommand(Sl, Command.Ptr);
5489     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
5490       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
5491       PrintSubClientCommand(Sc, Command.Ptr);
5492     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
5493       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
5494       PrintRoutinesCommand(Rc);
5495     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
5496       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
5497       PrintRoutinesCommand64(Rc);
5498     } else if (Command.C.cmd == MachO::LC_THREAD ||
5499                Command.C.cmd == MachO::LC_UNIXTHREAD) {
5500       MachO::thread_command Tc = Obj->getThreadCommand(Command);
5501       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
5502     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
5503                Command.C.cmd == MachO::LC_ID_DYLIB ||
5504                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
5505                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
5506                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
5507                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
5508       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
5509       PrintDylibCommand(Dl, Command.Ptr);
5510     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
5511                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
5512                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
5513                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
5514                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
5515                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
5516       MachO::linkedit_data_command Ld =
5517           Obj->getLinkeditDataLoadCommand(Command);
5518       PrintLinkEditDataCommand(Ld, Buf.size());
5519     } else {
5520       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
5521              << ")\n";
5522       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
5523       // TODO: get and print the raw bytes of the load command.
5524     }
5525     // TODO: print all the other kinds of load commands.
5526     if (i == ncmds - 1)
5527       break;
5528     else
5529       Command = Obj->getNextLoadCommandInfo(Command);
5530   }
5531 }
5532
5533 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
5534                                   uint32_t &filetype, uint32_t &cputype,
5535                                   bool verbose) {
5536   if (Obj->is64Bit()) {
5537     MachO::mach_header_64 H_64;
5538     H_64 = Obj->getHeader64();
5539     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
5540                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
5541     ncmds = H_64.ncmds;
5542     filetype = H_64.filetype;
5543     cputype = H_64.cputype;
5544   } else {
5545     MachO::mach_header H;
5546     H = Obj->getHeader();
5547     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
5548                     H.sizeofcmds, H.flags, verbose);
5549     ncmds = H.ncmds;
5550     filetype = H.filetype;
5551     cputype = H.cputype;
5552   }
5553 }
5554
5555 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
5556   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
5557   uint32_t ncmds = 0;
5558   uint32_t filetype = 0;
5559   uint32_t cputype = 0;
5560   getAndPrintMachHeader(file, ncmds, filetype, cputype, !NonVerbose);
5561   PrintLoadCommands(file, ncmds, filetype, cputype, !NonVerbose);
5562 }
5563
5564 //===----------------------------------------------------------------------===//
5565 // export trie dumping
5566 //===----------------------------------------------------------------------===//
5567
5568 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
5569   for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
5570     uint64_t Flags = Entry.flags();
5571     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
5572     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
5573     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5574                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
5575     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5576                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
5577     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
5578     if (ReExport)
5579       outs() << "[re-export] ";
5580     else
5581       outs() << format("0x%08llX  ",
5582                        Entry.address()); // FIXME:add in base address
5583     outs() << Entry.name();
5584     if (WeakDef || ThreadLocal || Resolver || Abs) {
5585       bool NeedsComma = false;
5586       outs() << " [";
5587       if (WeakDef) {
5588         outs() << "weak_def";
5589         NeedsComma = true;
5590       }
5591       if (ThreadLocal) {
5592         if (NeedsComma)
5593           outs() << ", ";
5594         outs() << "per-thread";
5595         NeedsComma = true;
5596       }
5597       if (Abs) {
5598         if (NeedsComma)
5599           outs() << ", ";
5600         outs() << "absolute";
5601         NeedsComma = true;
5602       }
5603       if (Resolver) {
5604         if (NeedsComma)
5605           outs() << ", ";
5606         outs() << format("resolver=0x%08llX", Entry.other());
5607         NeedsComma = true;
5608       }
5609       outs() << "]";
5610     }
5611     if (ReExport) {
5612       StringRef DylibName = "unknown";
5613       int Ordinal = Entry.other() - 1;
5614       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
5615       if (Entry.otherName().empty())
5616         outs() << " (from " << DylibName << ")";
5617       else
5618         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
5619     }
5620     outs() << "\n";
5621   }
5622 }
5623
5624 //===----------------------------------------------------------------------===//
5625 // rebase table dumping
5626 //===----------------------------------------------------------------------===//
5627
5628 namespace {
5629 class SegInfo {
5630 public:
5631   SegInfo(const object::MachOObjectFile *Obj);
5632
5633   StringRef segmentName(uint32_t SegIndex);
5634   StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
5635   uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
5636
5637 private:
5638   struct SectionInfo {
5639     uint64_t Address;
5640     uint64_t Size;
5641     StringRef SectionName;
5642     StringRef SegmentName;
5643     uint64_t OffsetInSegment;
5644     uint64_t SegmentStartAddress;
5645     uint32_t SegmentIndex;
5646   };
5647   const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
5648   SmallVector<SectionInfo, 32> Sections;
5649 };
5650 }
5651
5652 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
5653   // Build table of sections so segIndex/offset pairs can be translated.
5654   uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
5655   StringRef CurSegName;
5656   uint64_t CurSegAddress;
5657   for (const SectionRef &Section : Obj->sections()) {
5658     SectionInfo Info;
5659     if (error(Section.getName(Info.SectionName)))
5660       return;
5661     Info.Address = Section.getAddress();
5662     Info.Size = Section.getSize();
5663     Info.SegmentName =
5664         Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
5665     if (!Info.SegmentName.equals(CurSegName)) {
5666       ++CurSegIndex;
5667       CurSegName = Info.SegmentName;
5668       CurSegAddress = Info.Address;
5669     }
5670     Info.SegmentIndex = CurSegIndex - 1;
5671     Info.OffsetInSegment = Info.Address - CurSegAddress;
5672     Info.SegmentStartAddress = CurSegAddress;
5673     Sections.push_back(Info);
5674   }
5675 }
5676
5677 StringRef SegInfo::segmentName(uint32_t SegIndex) {
5678   for (const SectionInfo &SI : Sections) {
5679     if (SI.SegmentIndex == SegIndex)
5680       return SI.SegmentName;
5681   }
5682   llvm_unreachable("invalid segIndex");
5683 }
5684
5685 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5686                                                  uint64_t OffsetInSeg) {
5687   for (const SectionInfo &SI : Sections) {
5688     if (SI.SegmentIndex != SegIndex)
5689       continue;
5690     if (SI.OffsetInSegment > OffsetInSeg)
5691       continue;
5692     if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5693       continue;
5694     return SI;
5695   }
5696   llvm_unreachable("segIndex and offset not in any section");
5697 }
5698
5699 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5700   return findSection(SegIndex, OffsetInSeg).SectionName;
5701 }
5702
5703 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5704   const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5705   return SI.SegmentStartAddress + OffsetInSeg;
5706 }
5707
5708 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5709   // Build table of sections so names can used in final output.
5710   SegInfo sectionTable(Obj);
5711
5712   outs() << "segment  section            address     type\n";
5713   for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5714     uint32_t SegIndex = Entry.segmentIndex();
5715     uint64_t OffsetInSeg = Entry.segmentOffset();
5716     StringRef SegmentName = sectionTable.segmentName(SegIndex);
5717     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5718     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5719
5720     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
5721     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
5722                      SegmentName.str().c_str(), SectionName.str().c_str(),
5723                      Address, Entry.typeName().str().c_str());
5724   }
5725 }
5726
5727 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5728   StringRef DylibName;
5729   switch (Ordinal) {
5730   case MachO::BIND_SPECIAL_DYLIB_SELF:
5731     return "this-image";
5732   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5733     return "main-executable";
5734   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5735     return "flat-namespace";
5736   default:
5737     if (Ordinal > 0) {
5738       std::error_code EC =
5739           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
5740       if (EC)
5741         return "<<bad library ordinal>>";
5742       return DylibName;
5743     }
5744   }
5745   return "<<unknown special ordinal>>";
5746 }
5747
5748 //===----------------------------------------------------------------------===//
5749 // bind table dumping
5750 //===----------------------------------------------------------------------===//
5751
5752 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5753   // Build table of sections so names can used in final output.
5754   SegInfo sectionTable(Obj);
5755
5756   outs() << "segment  section            address    type       "
5757             "addend dylib            symbol\n";
5758   for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5759     uint32_t SegIndex = Entry.segmentIndex();
5760     uint64_t OffsetInSeg = Entry.segmentOffset();
5761     StringRef SegmentName = sectionTable.segmentName(SegIndex);
5762     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5763     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5764
5765     // Table lines look like:
5766     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
5767     StringRef Attr;
5768     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
5769       Attr = " (weak_import)";
5770     outs() << left_justify(SegmentName, 8) << " "
5771            << left_justify(SectionName, 18) << " "
5772            << format_hex(Address, 10, true) << " "
5773            << left_justify(Entry.typeName(), 8) << " "
5774            << format_decimal(Entry.addend(), 8) << " "
5775            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5776            << Entry.symbolName() << Attr << "\n";
5777   }
5778 }
5779
5780 //===----------------------------------------------------------------------===//
5781 // lazy bind table dumping
5782 //===----------------------------------------------------------------------===//
5783
5784 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5785   // Build table of sections so names can used in final output.
5786   SegInfo sectionTable(Obj);
5787
5788   outs() << "segment  section            address     "
5789             "dylib            symbol\n";
5790   for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5791     uint32_t SegIndex = Entry.segmentIndex();
5792     uint64_t OffsetInSeg = Entry.segmentOffset();
5793     StringRef SegmentName = sectionTable.segmentName(SegIndex);
5794     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5795     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5796
5797     // Table lines look like:
5798     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
5799     outs() << left_justify(SegmentName, 8) << " "
5800            << left_justify(SectionName, 18) << " "
5801            << format_hex(Address, 10, true) << " "
5802            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5803            << Entry.symbolName() << "\n";
5804   }
5805 }
5806
5807 //===----------------------------------------------------------------------===//
5808 // weak bind table dumping
5809 //===----------------------------------------------------------------------===//
5810
5811 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5812   // Build table of sections so names can used in final output.
5813   SegInfo sectionTable(Obj);
5814
5815   outs() << "segment  section            address     "
5816             "type       addend   symbol\n";
5817   for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5818     // Strong symbols don't have a location to update.
5819     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
5820       outs() << "                                        strong              "
5821              << Entry.symbolName() << "\n";
5822       continue;
5823     }
5824     uint32_t SegIndex = Entry.segmentIndex();
5825     uint64_t OffsetInSeg = Entry.segmentOffset();
5826     StringRef SegmentName = sectionTable.segmentName(SegIndex);
5827     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5828     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5829
5830     // Table lines look like:
5831     // __DATA  __data  0x00001000  pointer    0   _foo
5832     outs() << left_justify(SegmentName, 8) << " "
5833            << left_justify(SectionName, 18) << " "
5834            << format_hex(Address, 10, true) << " "
5835            << left_justify(Entry.typeName(), 8) << " "
5836            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
5837            << "\n";
5838   }
5839 }
5840
5841 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
5842 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5843 // information for that address. If the address is found its binding symbol
5844 // name is returned.  If not nullptr is returned.
5845 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5846                                                  struct DisassembleInfo *info) {
5847   if (info->bindtable == nullptr) {
5848     info->bindtable = new (BindTable);
5849     SegInfo sectionTable(info->O);
5850     for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5851       uint32_t SegIndex = Entry.segmentIndex();
5852       uint64_t OffsetInSeg = Entry.segmentOffset();
5853       uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5854       const char *SymbolName = nullptr;
5855       StringRef name = Entry.symbolName();
5856       if (!name.empty())
5857         SymbolName = name.data();
5858       info->bindtable->push_back(std::make_pair(Address, SymbolName));
5859     }
5860   }
5861   for (bind_table_iterator BI = info->bindtable->begin(),
5862                            BE = info->bindtable->end();
5863        BI != BE; ++BI) {
5864     uint64_t Address = BI->first;
5865     if (ReferenceValue == Address) {
5866       const char *SymbolName = BI->second;
5867       return SymbolName;
5868     }
5869   }
5870   return nullptr;
5871 }