xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision 307a83d76a4ad4c7684837ec2c7357b69b614dd0)
1 //===-- llvm-objdump.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 program is a utility that works like binutils "objdump", that is, it
11 // dumps out a plethora of information about an object file depending on the
12 // flags.
13 //
14 // The flags and output of this program should be near identical to those of
15 // binutils objdump.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm-objdump.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/FaultMaps.h"
25 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
29 #include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCInstPrinter.h"
32 #include "llvm/MC/MCInstrAnalysis.h"
33 #include "llvm/MC/MCInstrInfo.h"
34 #include "llvm/MC/MCObjectFileInfo.h"
35 #include "llvm/MC/MCRegisterInfo.h"
36 #include "llvm/MC/MCSubtargetInfo.h"
37 #include "llvm/Object/Archive.h"
38 #include "llvm/Object/COFF.h"
39 #include "llvm/Object/ELFObjectFile.h"
40 #include "llvm/Object/MachO.h"
41 #include "llvm/Object/ObjectFile.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/Errc.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/Format.h"
48 #include "llvm/Support/GraphWriter.h"
49 #include "llvm/Support/Host.h"
50 #include "llvm/Support/ManagedStatic.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/PrettyStackTrace.h"
53 #include "llvm/Support/Signals.h"
54 #include "llvm/Support/SourceMgr.h"
55 #include "llvm/Support/TargetRegistry.h"
56 #include "llvm/Support/TargetSelect.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include <algorithm>
59 #include <cctype>
60 #include <cstring>
61 #include <system_error>
62 
63 using namespace llvm;
64 using namespace object;
65 
66 static cl::list<std::string>
67 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
68 
69 cl::opt<bool>
70 llvm::Disassemble("disassemble",
71   cl::desc("Display assembler mnemonics for the machine instructions"));
72 static cl::alias
73 Disassembled("d", cl::desc("Alias for --disassemble"),
74              cl::aliasopt(Disassemble));
75 
76 cl::opt<bool>
77 llvm::DisassembleAll("disassemble-all",
78   cl::desc("Display assembler mnemonics for the machine instructions"));
79 static cl::alias
80 DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
81              cl::aliasopt(DisassembleAll));
82 
83 cl::opt<bool>
84 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
85 
86 cl::opt<bool>
87 llvm::SectionContents("s", cl::desc("Display the content of each section"));
88 
89 cl::opt<bool>
90 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
91 
92 cl::opt<bool>
93 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
94 
95 cl::opt<bool>
96 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
97 
98 cl::opt<bool>
99 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
100 
101 cl::opt<bool>
102 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
103 
104 cl::opt<bool>
105 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
106 
107 cl::opt<bool>
108 llvm::RawClangAST("raw-clang-ast",
109     cl::desc("Dump the raw binary contents of the clang AST section"));
110 
111 static cl::opt<bool>
112 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
113 static cl::alias
114 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
115 
116 cl::opt<std::string>
117 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
118                                     "see -version for available targets"));
119 
120 cl::opt<std::string>
121 llvm::MCPU("mcpu",
122      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
123      cl::value_desc("cpu-name"),
124      cl::init(""));
125 
126 cl::opt<std::string>
127 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
128                                 "see -version for available targets"));
129 
130 cl::opt<bool>
131 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
132                                                  "headers for each section."));
133 static cl::alias
134 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
135                     cl::aliasopt(SectionHeaders));
136 static cl::alias
137 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
138                       cl::aliasopt(SectionHeaders));
139 
140 cl::list<std::string>
141 llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
142                                          "With -macho dump segment,section"));
143 cl::alias
144 static FilterSectionsj("j", cl::desc("Alias for --section"),
145                  cl::aliasopt(llvm::FilterSections));
146 
147 cl::list<std::string>
148 llvm::MAttrs("mattr",
149   cl::CommaSeparated,
150   cl::desc("Target specific attributes"),
151   cl::value_desc("a1,+a2,-a3,..."));
152 
153 cl::opt<bool>
154 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
155                                                  "instructions, do not print "
156                                                  "the instruction bytes."));
157 
158 cl::opt<bool>
159 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
160 
161 static cl::alias
162 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
163                 cl::aliasopt(UnwindInfo));
164 
165 cl::opt<bool>
166 llvm::PrivateHeaders("private-headers",
167                      cl::desc("Display format specific file headers"));
168 
169 cl::opt<bool>
170 llvm::FirstPrivateHeader("private-header",
171                          cl::desc("Display only the first format specific file "
172                                   "header"));
173 
174 static cl::alias
175 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
176                     cl::aliasopt(PrivateHeaders));
177 
178 cl::opt<bool>
179     llvm::PrintImmHex("print-imm-hex",
180                       cl::desc("Use hex format for immediate values"));
181 
182 cl::opt<bool> PrintFaultMaps("fault-map-section",
183                              cl::desc("Display contents of faultmap section"));
184 
185 cl::opt<DIDumpType> llvm::DwarfDumpType(
186     "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
187     cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
188                clEnumValEnd));
189 
190 static StringRef ToolName;
191 
192 namespace {
193 typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
194 
195 class SectionFilterIterator {
196 public:
197   SectionFilterIterator(FilterPredicate P,
198                         llvm::object::section_iterator const &I,
199                         llvm::object::section_iterator const &E)
200       : Predicate(P), Iterator(I), End(E) {
201     ScanPredicate();
202   }
203   const llvm::object::SectionRef &operator*() const { return *Iterator; }
204   SectionFilterIterator &operator++() {
205     ++Iterator;
206     ScanPredicate();
207     return *this;
208   }
209   bool operator!=(SectionFilterIterator const &Other) const {
210     return Iterator != Other.Iterator;
211   }
212 
213 private:
214   void ScanPredicate() {
215     while (Iterator != End && !Predicate(*Iterator)) {
216       ++Iterator;
217     }
218   }
219   FilterPredicate Predicate;
220   llvm::object::section_iterator Iterator;
221   llvm::object::section_iterator End;
222 };
223 
224 class SectionFilter {
225 public:
226   SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
227       : Predicate(P), Object(O) {}
228   SectionFilterIterator begin() {
229     return SectionFilterIterator(Predicate, Object.section_begin(),
230                                  Object.section_end());
231   }
232   SectionFilterIterator end() {
233     return SectionFilterIterator(Predicate, Object.section_end(),
234                                  Object.section_end());
235   }
236 
237 private:
238   FilterPredicate Predicate;
239   llvm::object::ObjectFile const &Object;
240 };
241 SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
242   return SectionFilter([](llvm::object::SectionRef const &S) {
243                          if(FilterSections.empty())
244                            return true;
245                          llvm::StringRef String;
246                          std::error_code error = S.getName(String);
247                          if (error)
248                            return false;
249                          return std::find(FilterSections.begin(),
250                                           FilterSections.end(),
251                                           String) != FilterSections.end();
252                        },
253                        O);
254 }
255 }
256 
257 void llvm::error(std::error_code EC) {
258   if (!EC)
259     return;
260 
261   errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
262   errs().flush();
263   exit(1);
264 }
265 
266 LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
267                                                 std::error_code EC) {
268   assert(EC);
269   errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
270   exit(1);
271 }
272 
273 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
274   // Figure out the target triple.
275   llvm::Triple TheTriple("unknown-unknown-unknown");
276   if (TripleName.empty()) {
277     if (Obj) {
278       TheTriple.setArch(Triple::ArchType(Obj->getArch()));
279       // TheTriple defaults to ELF, and COFF doesn't have an environment:
280       // the best we can do here is indicate that it is mach-o.
281       if (Obj->isMachO())
282         TheTriple.setObjectFormat(Triple::MachO);
283 
284       if (Obj->isCOFF()) {
285         const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
286         if (COFFObj->getArch() == Triple::thumb)
287           TheTriple.setTriple("thumbv7-windows");
288       }
289     }
290   } else
291     TheTriple.setTriple(Triple::normalize(TripleName));
292 
293   // Get the target specific parser.
294   std::string Error;
295   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
296                                                          Error);
297   if (!TheTarget)
298     report_fatal_error("can't find target: " + Error);
299 
300   // Update the triple name and return the found target.
301   TripleName = TheTriple.getTriple();
302   return TheTarget;
303 }
304 
305 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
306   return a.getOffset() < b.getOffset();
307 }
308 
309 namespace {
310 class PrettyPrinter {
311 public:
312   virtual ~PrettyPrinter(){}
313   virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
314                          ArrayRef<uint8_t> Bytes, uint64_t Address,
315                          raw_ostream &OS, StringRef Annot,
316                          MCSubtargetInfo const &STI) {
317     OS << format("%8" PRIx64 ":", Address);
318     if (!NoShowRawInsn) {
319       OS << "\t";
320       dumpBytes(Bytes, OS);
321     }
322     if (MI)
323       IP.printInst(MI, OS, "", STI);
324     else
325       OS << " <unknown>";
326   }
327 };
328 PrettyPrinter PrettyPrinterInst;
329 class HexagonPrettyPrinter : public PrettyPrinter {
330 public:
331   void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
332                  raw_ostream &OS) {
333     uint32_t opcode =
334       (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
335     OS << format("%8" PRIx64 ":", Address);
336     if (!NoShowRawInsn) {
337       OS << "\t";
338       dumpBytes(Bytes.slice(0, 4), OS);
339       OS << format("%08" PRIx32, opcode);
340     }
341   }
342   void printInst(MCInstPrinter &IP, const MCInst *MI,
343                  ArrayRef<uint8_t> Bytes, uint64_t Address,
344                  raw_ostream &OS, StringRef Annot,
345                  MCSubtargetInfo const &STI) override {
346     if (!MI) {
347       printLead(Bytes, Address, OS);
348       OS << " <unknown>";
349       return;
350     }
351     std::string Buffer;
352     {
353       raw_string_ostream TempStream(Buffer);
354       IP.printInst(MI, TempStream, "", STI);
355     }
356     StringRef Contents(Buffer);
357     // Split off bundle attributes
358     auto PacketBundle = Contents.rsplit('\n');
359     // Split off first instruction from the rest
360     auto HeadTail = PacketBundle.first.split('\n');
361     auto Preamble = " { ";
362     auto Separator = "";
363     while(!HeadTail.first.empty()) {
364       OS << Separator;
365       Separator = "\n";
366       printLead(Bytes, Address, OS);
367       OS << Preamble;
368       Preamble = "   ";
369       StringRef Inst;
370       auto Duplex = HeadTail.first.split('\v');
371       if(!Duplex.second.empty()){
372         OS << Duplex.first;
373         OS << "; ";
374         Inst = Duplex.second;
375       }
376       else
377         Inst = HeadTail.first;
378       OS << Inst;
379       Bytes = Bytes.slice(4);
380       Address += 4;
381       HeadTail = HeadTail.second.split('\n');
382     }
383     OS << " } " << PacketBundle.second;
384   }
385 };
386 HexagonPrettyPrinter HexagonPrettyPrinterInst;
387 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
388   switch(Triple.getArch()) {
389   default:
390     return PrettyPrinterInst;
391   case Triple::hexagon:
392     return HexagonPrettyPrinterInst;
393   }
394 }
395 }
396 
397 template <class ELFT>
398 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
399                                                 const RelocationRef &RelRef,
400                                                 SmallVectorImpl<char> &Result) {
401   DataRefImpl Rel = RelRef.getRawDataRefImpl();
402 
403   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
404   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
405   typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
406 
407   const ELFFile<ELFT> &EF = *Obj->getELFFile();
408 
409   ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
410   if (std::error_code EC = SecOrErr.getError())
411     return EC;
412   const Elf_Shdr *Sec = *SecOrErr;
413   ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
414   if (std::error_code EC = SymTabOrErr.getError())
415     return EC;
416   const Elf_Shdr *SymTab = *SymTabOrErr;
417   assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
418          SymTab->sh_type == ELF::SHT_DYNSYM);
419   ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
420   if (std::error_code EC = StrTabSec.getError())
421     return EC;
422   ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
423   if (std::error_code EC = StrTabOrErr.getError())
424     return EC;
425   StringRef StrTab = *StrTabOrErr;
426   uint8_t type = RelRef.getType();
427   StringRef res;
428   int64_t addend = 0;
429   switch (Sec->sh_type) {
430   default:
431     return object_error::parse_failed;
432   case ELF::SHT_REL: {
433     // TODO: Read implicit addend from section data.
434     break;
435   }
436   case ELF::SHT_RELA: {
437     const Elf_Rela *ERela = Obj->getRela(Rel);
438     addend = ERela->r_addend;
439     break;
440   }
441   }
442   symbol_iterator SI = RelRef.getSymbol();
443   const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
444   StringRef Target;
445   if (symb->getType() == ELF::STT_SECTION) {
446     ErrorOr<section_iterator> SymSI = SI->getSection();
447     if (std::error_code EC = SymSI.getError())
448       return EC;
449     const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
450     ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
451     if (std::error_code EC = SecName.getError())
452       return EC;
453     Target = *SecName;
454   } else {
455     ErrorOr<StringRef> SymName = symb->getName(StrTab);
456     if (!SymName)
457       return SymName.getError();
458     Target = *SymName;
459   }
460   switch (EF.getHeader()->e_machine) {
461   case ELF::EM_X86_64:
462     switch (type) {
463     case ELF::R_X86_64_PC8:
464     case ELF::R_X86_64_PC16:
465     case ELF::R_X86_64_PC32: {
466       std::string fmtbuf;
467       raw_string_ostream fmt(fmtbuf);
468       fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
469       fmt.flush();
470       Result.append(fmtbuf.begin(), fmtbuf.end());
471     } break;
472     case ELF::R_X86_64_8:
473     case ELF::R_X86_64_16:
474     case ELF::R_X86_64_32:
475     case ELF::R_X86_64_32S:
476     case ELF::R_X86_64_64: {
477       std::string fmtbuf;
478       raw_string_ostream fmt(fmtbuf);
479       fmt << Target << (addend < 0 ? "" : "+") << addend;
480       fmt.flush();
481       Result.append(fmtbuf.begin(), fmtbuf.end());
482     } break;
483     default:
484       res = "Unknown";
485     }
486     break;
487   case ELF::EM_LANAI:
488   case ELF::EM_AARCH64: {
489     std::string fmtbuf;
490     raw_string_ostream fmt(fmtbuf);
491     fmt << Target;
492     if (addend != 0)
493       fmt << (addend < 0 ? "" : "+") << addend;
494     fmt.flush();
495     Result.append(fmtbuf.begin(), fmtbuf.end());
496     break;
497   }
498   case ELF::EM_386:
499   case ELF::EM_IAMCU:
500   case ELF::EM_ARM:
501   case ELF::EM_HEXAGON:
502   case ELF::EM_MIPS:
503     res = Target;
504     break;
505   case ELF::EM_WEBASSEMBLY:
506     switch (type) {
507     case ELF::R_WEBASSEMBLY_DATA: {
508       std::string fmtbuf;
509       raw_string_ostream fmt(fmtbuf);
510       fmt << Target << (addend < 0 ? "" : "+") << addend;
511       fmt.flush();
512       Result.append(fmtbuf.begin(), fmtbuf.end());
513       break;
514     }
515     case ELF::R_WEBASSEMBLY_FUNCTION:
516       res = Target;
517       break;
518     default:
519       res = "Unknown";
520     }
521     break;
522   default:
523     res = "Unknown";
524   }
525   if (Result.empty())
526     Result.append(res.begin(), res.end());
527   return std::error_code();
528 }
529 
530 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
531                                                 const RelocationRef &Rel,
532                                                 SmallVectorImpl<char> &Result) {
533   if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
534     return getRelocationValueString(ELF32LE, Rel, Result);
535   if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
536     return getRelocationValueString(ELF64LE, Rel, Result);
537   if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
538     return getRelocationValueString(ELF32BE, Rel, Result);
539   auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
540   return getRelocationValueString(ELF64BE, Rel, Result);
541 }
542 
543 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
544                                                 const RelocationRef &Rel,
545                                                 SmallVectorImpl<char> &Result) {
546   symbol_iterator SymI = Rel.getSymbol();
547   ErrorOr<StringRef> SymNameOrErr = SymI->getName();
548   if (std::error_code EC = SymNameOrErr.getError())
549     return EC;
550   StringRef SymName = *SymNameOrErr;
551   Result.append(SymName.begin(), SymName.end());
552   return std::error_code();
553 }
554 
555 static void printRelocationTargetName(const MachOObjectFile *O,
556                                       const MachO::any_relocation_info &RE,
557                                       raw_string_ostream &fmt) {
558   bool IsScattered = O->isRelocationScattered(RE);
559 
560   // Target of a scattered relocation is an address.  In the interest of
561   // generating pretty output, scan through the symbol table looking for a
562   // symbol that aligns with that address.  If we find one, print it.
563   // Otherwise, we just print the hex address of the target.
564   if (IsScattered) {
565     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
566 
567     for (const SymbolRef &Symbol : O->symbols()) {
568       std::error_code ec;
569       ErrorOr<uint64_t> Addr = Symbol.getAddress();
570       if ((ec = Addr.getError()))
571         report_fatal_error(ec.message());
572       if (*Addr != Val)
573         continue;
574       ErrorOr<StringRef> Name = Symbol.getName();
575       if (std::error_code EC = Name.getError())
576         report_fatal_error(EC.message());
577       fmt << *Name;
578       return;
579     }
580 
581     // If we couldn't find a symbol that this relocation refers to, try
582     // to find a section beginning instead.
583     for (const SectionRef &Section : ToolSectionFilter(*O)) {
584       std::error_code ec;
585 
586       StringRef Name;
587       uint64_t Addr = Section.getAddress();
588       if (Addr != Val)
589         continue;
590       if ((ec = Section.getName(Name)))
591         report_fatal_error(ec.message());
592       fmt << Name;
593       return;
594     }
595 
596     fmt << format("0x%x", Val);
597     return;
598   }
599 
600   StringRef S;
601   bool isExtern = O->getPlainRelocationExternal(RE);
602   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
603 
604   if (isExtern) {
605     symbol_iterator SI = O->symbol_begin();
606     advance(SI, Val);
607     ErrorOr<StringRef> SOrErr = SI->getName();
608     error(SOrErr.getError());
609     S = *SOrErr;
610   } else {
611     section_iterator SI = O->section_begin();
612     // Adjust for the fact that sections are 1-indexed.
613     advance(SI, Val - 1);
614     SI->getName(S);
615   }
616 
617   fmt << S;
618 }
619 
620 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
621                                                 const RelocationRef &RelRef,
622                                                 SmallVectorImpl<char> &Result) {
623   DataRefImpl Rel = RelRef.getRawDataRefImpl();
624   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
625 
626   unsigned Arch = Obj->getArch();
627 
628   std::string fmtbuf;
629   raw_string_ostream fmt(fmtbuf);
630   unsigned Type = Obj->getAnyRelocationType(RE);
631   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
632 
633   // Determine any addends that should be displayed with the relocation.
634   // These require decoding the relocation type, which is triple-specific.
635 
636   // X86_64 has entirely custom relocation types.
637   if (Arch == Triple::x86_64) {
638     bool isPCRel = Obj->getAnyRelocationPCRel(RE);
639 
640     switch (Type) {
641     case MachO::X86_64_RELOC_GOT_LOAD:
642     case MachO::X86_64_RELOC_GOT: {
643       printRelocationTargetName(Obj, RE, fmt);
644       fmt << "@GOT";
645       if (isPCRel)
646         fmt << "PCREL";
647       break;
648     }
649     case MachO::X86_64_RELOC_SUBTRACTOR: {
650       DataRefImpl RelNext = Rel;
651       Obj->moveRelocationNext(RelNext);
652       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
653 
654       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
655       // X86_64_RELOC_UNSIGNED.
656       // NOTE: Scattered relocations don't exist on x86_64.
657       unsigned RType = Obj->getAnyRelocationType(RENext);
658       if (RType != MachO::X86_64_RELOC_UNSIGNED)
659         report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
660                            "X86_64_RELOC_SUBTRACTOR.");
661 
662       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
663       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
664       printRelocationTargetName(Obj, RENext, fmt);
665       fmt << "-";
666       printRelocationTargetName(Obj, RE, fmt);
667       break;
668     }
669     case MachO::X86_64_RELOC_TLV:
670       printRelocationTargetName(Obj, RE, fmt);
671       fmt << "@TLV";
672       if (isPCRel)
673         fmt << "P";
674       break;
675     case MachO::X86_64_RELOC_SIGNED_1:
676       printRelocationTargetName(Obj, RE, fmt);
677       fmt << "-1";
678       break;
679     case MachO::X86_64_RELOC_SIGNED_2:
680       printRelocationTargetName(Obj, RE, fmt);
681       fmt << "-2";
682       break;
683     case MachO::X86_64_RELOC_SIGNED_4:
684       printRelocationTargetName(Obj, RE, fmt);
685       fmt << "-4";
686       break;
687     default:
688       printRelocationTargetName(Obj, RE, fmt);
689       break;
690     }
691     // X86 and ARM share some relocation types in common.
692   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
693              Arch == Triple::ppc) {
694     // Generic relocation types...
695     switch (Type) {
696     case MachO::GENERIC_RELOC_PAIR: // prints no info
697       return std::error_code();
698     case MachO::GENERIC_RELOC_SECTDIFF: {
699       DataRefImpl RelNext = Rel;
700       Obj->moveRelocationNext(RelNext);
701       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
702 
703       // X86 sect diff's must be followed by a relocation of type
704       // GENERIC_RELOC_PAIR.
705       unsigned RType = Obj->getAnyRelocationType(RENext);
706 
707       if (RType != MachO::GENERIC_RELOC_PAIR)
708         report_fatal_error("Expected GENERIC_RELOC_PAIR after "
709                            "GENERIC_RELOC_SECTDIFF.");
710 
711       printRelocationTargetName(Obj, RE, fmt);
712       fmt << "-";
713       printRelocationTargetName(Obj, RENext, fmt);
714       break;
715     }
716     }
717 
718     if (Arch == Triple::x86 || Arch == Triple::ppc) {
719       switch (Type) {
720       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
721         DataRefImpl RelNext = Rel;
722         Obj->moveRelocationNext(RelNext);
723         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
724 
725         // X86 sect diff's must be followed by a relocation of type
726         // GENERIC_RELOC_PAIR.
727         unsigned RType = Obj->getAnyRelocationType(RENext);
728         if (RType != MachO::GENERIC_RELOC_PAIR)
729           report_fatal_error("Expected GENERIC_RELOC_PAIR after "
730                              "GENERIC_RELOC_LOCAL_SECTDIFF.");
731 
732         printRelocationTargetName(Obj, RE, fmt);
733         fmt << "-";
734         printRelocationTargetName(Obj, RENext, fmt);
735         break;
736       }
737       case MachO::GENERIC_RELOC_TLV: {
738         printRelocationTargetName(Obj, RE, fmt);
739         fmt << "@TLV";
740         if (IsPCRel)
741           fmt << "P";
742         break;
743       }
744       default:
745         printRelocationTargetName(Obj, RE, fmt);
746       }
747     } else { // ARM-specific relocations
748       switch (Type) {
749       case MachO::ARM_RELOC_HALF:
750       case MachO::ARM_RELOC_HALF_SECTDIFF: {
751         // Half relocations steal a bit from the length field to encode
752         // whether this is an upper16 or a lower16 relocation.
753         bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
754 
755         if (isUpper)
756           fmt << ":upper16:(";
757         else
758           fmt << ":lower16:(";
759         printRelocationTargetName(Obj, RE, fmt);
760 
761         DataRefImpl RelNext = Rel;
762         Obj->moveRelocationNext(RelNext);
763         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
764 
765         // ARM half relocs must be followed by a relocation of type
766         // ARM_RELOC_PAIR.
767         unsigned RType = Obj->getAnyRelocationType(RENext);
768         if (RType != MachO::ARM_RELOC_PAIR)
769           report_fatal_error("Expected ARM_RELOC_PAIR after "
770                              "ARM_RELOC_HALF");
771 
772         // NOTE: The half of the target virtual address is stashed in the
773         // address field of the secondary relocation, but we can't reverse
774         // engineer the constant offset from it without decoding the movw/movt
775         // instruction to find the other half in its immediate field.
776 
777         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
778         // symbol/section pointer of the follow-on relocation.
779         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
780           fmt << "-";
781           printRelocationTargetName(Obj, RENext, fmt);
782         }
783 
784         fmt << ")";
785         break;
786       }
787       default: { printRelocationTargetName(Obj, RE, fmt); }
788       }
789     }
790   } else
791     printRelocationTargetName(Obj, RE, fmt);
792 
793   fmt.flush();
794   Result.append(fmtbuf.begin(), fmtbuf.end());
795   return std::error_code();
796 }
797 
798 static std::error_code getRelocationValueString(const RelocationRef &Rel,
799                                                 SmallVectorImpl<char> &Result) {
800   const ObjectFile *Obj = Rel.getObject();
801   if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
802     return getRelocationValueString(ELF, Rel, Result);
803   if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
804     return getRelocationValueString(COFF, Rel, Result);
805   auto *MachO = cast<MachOObjectFile>(Obj);
806   return getRelocationValueString(MachO, Rel, Result);
807 }
808 
809 /// @brief Indicates whether this relocation should hidden when listing
810 /// relocations, usually because it is the trailing part of a multipart
811 /// relocation that will be printed as part of the leading relocation.
812 static bool getHidden(RelocationRef RelRef) {
813   const ObjectFile *Obj = RelRef.getObject();
814   auto *MachO = dyn_cast<MachOObjectFile>(Obj);
815   if (!MachO)
816     return false;
817 
818   unsigned Arch = MachO->getArch();
819   DataRefImpl Rel = RelRef.getRawDataRefImpl();
820   uint64_t Type = MachO->getRelocationType(Rel);
821 
822   // On arches that use the generic relocations, GENERIC_RELOC_PAIR
823   // is always hidden.
824   if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
825     if (Type == MachO::GENERIC_RELOC_PAIR)
826       return true;
827   } else if (Arch == Triple::x86_64) {
828     // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
829     // an X86_64_RELOC_SUBTRACTOR.
830     if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
831       DataRefImpl RelPrev = Rel;
832       RelPrev.d.a--;
833       uint64_t PrevType = MachO->getRelocationType(RelPrev);
834       if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
835         return true;
836     }
837   }
838 
839   return false;
840 }
841 
842 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
843   const Target *TheTarget = getTarget(Obj);
844 
845   // Package up features to be passed to target/subtarget
846   std::string FeaturesStr;
847   if (MAttrs.size()) {
848     SubtargetFeatures Features;
849     for (unsigned i = 0; i != MAttrs.size(); ++i)
850       Features.AddFeature(MAttrs[i]);
851     FeaturesStr = Features.getString();
852   }
853 
854   std::unique_ptr<const MCRegisterInfo> MRI(
855       TheTarget->createMCRegInfo(TripleName));
856   if (!MRI)
857     report_fatal_error("error: no register info for target " + TripleName);
858 
859   // Set up disassembler.
860   std::unique_ptr<const MCAsmInfo> AsmInfo(
861       TheTarget->createMCAsmInfo(*MRI, TripleName));
862   if (!AsmInfo)
863     report_fatal_error("error: no assembly info for target " + TripleName);
864   std::unique_ptr<const MCSubtargetInfo> STI(
865       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
866   if (!STI)
867     report_fatal_error("error: no subtarget info for target " + TripleName);
868   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
869   if (!MII)
870     report_fatal_error("error: no instruction info for target " + TripleName);
871   std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
872   MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
873 
874   std::unique_ptr<MCDisassembler> DisAsm(
875     TheTarget->createMCDisassembler(*STI, Ctx));
876   if (!DisAsm)
877     report_fatal_error("error: no disassembler for target " + TripleName);
878 
879   std::unique_ptr<const MCInstrAnalysis> MIA(
880       TheTarget->createMCInstrAnalysis(MII.get()));
881 
882   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
883   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
884       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
885   if (!IP)
886     report_fatal_error("error: no instruction printer for target " +
887                        TripleName);
888   IP->setPrintImmHex(PrintImmHex);
889   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
890 
891   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
892                                                  "\t\t\t%08" PRIx64 ":  ";
893 
894   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
895   // in RelocSecs contain the relocations for section S.
896   std::error_code EC;
897   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
898   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
899     section_iterator Sec2 = Section.getRelocatedSection();
900     if (Sec2 != Obj->section_end())
901       SectionRelocMap[*Sec2].push_back(Section);
902   }
903 
904   // Create a mapping from virtual address to symbol name.  This is used to
905   // pretty print the symbols while disassembling.
906   typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
907   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
908   for (const SymbolRef &Symbol : Obj->symbols()) {
909     ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
910     error(AddressOrErr.getError());
911     uint64_t Address = *AddressOrErr;
912 
913     ErrorOr<StringRef> Name = Symbol.getName();
914     error(Name.getError());
915     if (Name->empty())
916       continue;
917 
918     ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
919     error(SectionOrErr.getError());
920     section_iterator SecI = *SectionOrErr;
921     if (SecI == Obj->section_end())
922       continue;
923 
924     AllSymbols[*SecI].emplace_back(Address, *Name);
925   }
926 
927   // Create a mapping from virtual address to section.
928   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
929   for (SectionRef Sec : Obj->sections())
930     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
931   array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
932 
933   // Linked executables (.exe and .dll files) typically don't include a real
934   // symbol table but they might contain an export table.
935   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
936     for (const auto &ExportEntry : COFFObj->export_directories()) {
937       StringRef Name;
938       error(ExportEntry.getSymbolName(Name));
939       if (Name.empty())
940         continue;
941       uint32_t RVA;
942       error(ExportEntry.getExportRVA(RVA));
943 
944       uint64_t VA = COFFObj->getImageBase() + RVA;
945       auto Sec = std::upper_bound(
946           SectionAddresses.begin(), SectionAddresses.end(), VA,
947           [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
948             return LHS < RHS.first;
949           });
950       if (Sec != SectionAddresses.begin())
951         --Sec;
952       else
953         Sec = SectionAddresses.end();
954 
955       if (Sec != SectionAddresses.end())
956         AllSymbols[Sec->second].emplace_back(VA, Name);
957     }
958   }
959 
960   // Sort all the symbols, this allows us to use a simple binary search to find
961   // a symbol near an address.
962   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
963     array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
964 
965   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
966     if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
967       continue;
968 
969     uint64_t SectionAddr = Section.getAddress();
970     uint64_t SectSize = Section.getSize();
971     if (!SectSize)
972       continue;
973 
974     // Get the list of all the symbols in this section.
975     SectionSymbolsTy &Symbols = AllSymbols[Section];
976     std::vector<uint64_t> DataMappingSymsAddr;
977     std::vector<uint64_t> TextMappingSymsAddr;
978     if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
979       for (const auto &Symb : Symbols) {
980         uint64_t Address = Symb.first;
981         StringRef Name = Symb.second;
982         if (Name.startswith("$d"))
983           DataMappingSymsAddr.push_back(Address - SectionAddr);
984         if (Name.startswith("$x"))
985           TextMappingSymsAddr.push_back(Address - SectionAddr);
986       }
987     }
988 
989     std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
990     std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
991 
992     // Make a list of all the relocations for this section.
993     std::vector<RelocationRef> Rels;
994     if (InlineRelocs) {
995       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
996         for (const RelocationRef &Reloc : RelocSec.relocations()) {
997           Rels.push_back(Reloc);
998         }
999       }
1000     }
1001 
1002     // Sort relocations by address.
1003     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1004 
1005     StringRef SegmentName = "";
1006     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1007       DataRefImpl DR = Section.getRawDataRefImpl();
1008       SegmentName = MachO->getSectionFinalSegmentName(DR);
1009     }
1010     StringRef name;
1011     error(Section.getName(name));
1012     outs() << "Disassembly of section ";
1013     if (!SegmentName.empty())
1014       outs() << SegmentName << ",";
1015     outs() << name << ':';
1016 
1017     // If the section has no symbol at the start, just insert a dummy one.
1018     if (Symbols.empty() || Symbols[0].first != 0)
1019       Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
1020 
1021     SmallString<40> Comments;
1022     raw_svector_ostream CommentStream(Comments);
1023 
1024     StringRef BytesStr;
1025     error(Section.getContents(BytesStr));
1026     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1027                             BytesStr.size());
1028 
1029     uint64_t Size;
1030     uint64_t Index;
1031 
1032     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1033     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1034     // Disassemble symbol by symbol.
1035     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1036 
1037       uint64_t Start = Symbols[si].first - SectionAddr;
1038       // The end is either the section end or the beginning of the next
1039       // symbol.
1040       uint64_t End =
1041           (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1042       // Don't try to disassemble beyond the end of section contents.
1043       if (End > SectSize)
1044         End = SectSize;
1045       // If this symbol has the same address as the next symbol, then skip it.
1046       if (Start >= End)
1047         continue;
1048 
1049       outs() << '\n' << Symbols[si].second << ":\n";
1050 
1051 #ifndef NDEBUG
1052       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1053 #else
1054       raw_ostream &DebugOut = nulls();
1055 #endif
1056 
1057       for (Index = Start; Index < End; Index += Size) {
1058         MCInst Inst;
1059 
1060         // AArch64 ELF binaries can interleave data and text in the
1061         // same section. We rely on the markers introduced to
1062         // understand what we need to dump.
1063         if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1064           uint64_t Stride = 0;
1065 
1066           auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1067                                       DataMappingSymsAddr.end(), Index);
1068           if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1069             // Switch to data.
1070             while (Index < End) {
1071               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1072               outs() << "\t";
1073               if (Index + 4 <= End) {
1074                 Stride = 4;
1075                 dumpBytes(Bytes.slice(Index, 4), outs());
1076                 outs() << "\t.word";
1077               } else if (Index + 2 <= End) {
1078                 Stride = 2;
1079                 dumpBytes(Bytes.slice(Index, 2), outs());
1080                 outs() << "\t.short";
1081               } else {
1082                 Stride = 1;
1083                 dumpBytes(Bytes.slice(Index, 1), outs());
1084                 outs() << "\t.byte";
1085               }
1086               Index += Stride;
1087               outs() << "\n";
1088               auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1089                                           TextMappingSymsAddr.end(), Index);
1090               if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1091                 break;
1092             }
1093           }
1094         }
1095 
1096         if (Index >= End)
1097           break;
1098 
1099         bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1100                                                    SectionAddr + Index, DebugOut,
1101                                                    CommentStream);
1102         if (Size == 0)
1103           Size = 1;
1104         PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1105                       Bytes.slice(Index, Size),
1106                       SectionAddr + Index, outs(), "", *STI);
1107         outs() << CommentStream.str();
1108         Comments.clear();
1109 
1110         // Try to resolve the target of a call, tail call, etc. to a specific
1111         // symbol.
1112         if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1113                     MIA->isConditionalBranch(Inst))) {
1114           uint64_t Target;
1115           if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1116             // In a relocatable object, the target's section must reside in
1117             // the same section as the call instruction or it is accessed
1118             // through a relocation.
1119             //
1120             // In a non-relocatable object, the target may be in any section.
1121             //
1122             // N.B. We don't walk the relocations in the relocatable case yet.
1123             auto *TargetSectionSymbols = &Symbols;
1124             if (!Obj->isRelocatableObject()) {
1125               auto SectionAddress = std::upper_bound(
1126                   SectionAddresses.begin(), SectionAddresses.end(), Target,
1127                   [](uint64_t LHS,
1128                       const std::pair<uint64_t, SectionRef> &RHS) {
1129                     return LHS < RHS.first;
1130                   });
1131               if (SectionAddress != SectionAddresses.begin()) {
1132                 --SectionAddress;
1133                 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1134               } else {
1135                 TargetSectionSymbols = nullptr;
1136               }
1137             }
1138 
1139             // Find the first symbol in the section whose offset is less than
1140             // or equal to the target.
1141             if (TargetSectionSymbols) {
1142               auto TargetSym = std::upper_bound(
1143                   TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1144                   Target, [](uint64_t LHS,
1145                               const std::pair<uint64_t, StringRef> &RHS) {
1146                     return LHS < RHS.first;
1147                   });
1148               if (TargetSym != TargetSectionSymbols->begin()) {
1149                 --TargetSym;
1150                 uint64_t TargetAddress = std::get<0>(*TargetSym);
1151                 StringRef TargetName = std::get<1>(*TargetSym);
1152                 outs() << " <" << TargetName;
1153                 uint64_t Disp = Target - TargetAddress;
1154                 if (Disp)
1155                   outs() << "+0x" << utohexstr(Disp);
1156                 outs() << '>';
1157               }
1158             }
1159           }
1160         }
1161         outs() << "\n";
1162 
1163         // Print relocation for instruction.
1164         while (rel_cur != rel_end) {
1165           bool hidden = getHidden(*rel_cur);
1166           uint64_t addr = rel_cur->getOffset();
1167           SmallString<16> name;
1168           SmallString<32> val;
1169 
1170           // If this relocation is hidden, skip it.
1171           if (hidden) goto skip_print_rel;
1172 
1173           // Stop when rel_cur's address is past the current instruction.
1174           if (addr >= Index + Size) break;
1175           rel_cur->getTypeName(name);
1176           error(getRelocationValueString(*rel_cur, val));
1177           outs() << format(Fmt.data(), SectionAddr + addr) << name
1178                  << "\t" << val << "\n";
1179 
1180         skip_print_rel:
1181           ++rel_cur;
1182         }
1183       }
1184     }
1185   }
1186 }
1187 
1188 void llvm::PrintRelocations(const ObjectFile *Obj) {
1189   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1190                                                  "%08" PRIx64;
1191   // Regular objdump doesn't print relocations in non-relocatable object
1192   // files.
1193   if (!Obj->isRelocatableObject())
1194     return;
1195 
1196   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1197     if (Section.relocation_begin() == Section.relocation_end())
1198       continue;
1199     StringRef secname;
1200     error(Section.getName(secname));
1201     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1202     for (const RelocationRef &Reloc : Section.relocations()) {
1203       bool hidden = getHidden(Reloc);
1204       uint64_t address = Reloc.getOffset();
1205       SmallString<32> relocname;
1206       SmallString<32> valuestr;
1207       if (hidden)
1208         continue;
1209       Reloc.getTypeName(relocname);
1210       error(getRelocationValueString(Reloc, valuestr));
1211       outs() << format(Fmt.data(), address) << " " << relocname << " "
1212              << valuestr << "\n";
1213     }
1214     outs() << "\n";
1215   }
1216 }
1217 
1218 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1219   outs() << "Sections:\n"
1220             "Idx Name          Size      Address          Type\n";
1221   unsigned i = 0;
1222   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1223     StringRef Name;
1224     error(Section.getName(Name));
1225     uint64_t Address = Section.getAddress();
1226     uint64_t Size = Section.getSize();
1227     bool Text = Section.isText();
1228     bool Data = Section.isData();
1229     bool BSS = Section.isBSS();
1230     std::string Type = (std::string(Text ? "TEXT " : "") +
1231                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1232     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1233                      Name.str().c_str(), Size, Address, Type.c_str());
1234     ++i;
1235   }
1236 }
1237 
1238 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1239   std::error_code EC;
1240   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1241     StringRef Name;
1242     StringRef Contents;
1243     error(Section.getName(Name));
1244     uint64_t BaseAddr = Section.getAddress();
1245     uint64_t Size = Section.getSize();
1246     if (!Size)
1247       continue;
1248 
1249     outs() << "Contents of section " << Name << ":\n";
1250     if (Section.isBSS()) {
1251       outs() << format("<skipping contents of bss section at [%04" PRIx64
1252                        ", %04" PRIx64 ")>\n",
1253                        BaseAddr, BaseAddr + Size);
1254       continue;
1255     }
1256 
1257     error(Section.getContents(Contents));
1258 
1259     // Dump out the content as hex and printable ascii characters.
1260     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1261       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1262       // Dump line of hex.
1263       for (std::size_t i = 0; i < 16; ++i) {
1264         if (i != 0 && i % 4 == 0)
1265           outs() << ' ';
1266         if (addr + i < end)
1267           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1268                  << hexdigit(Contents[addr + i] & 0xF, true);
1269         else
1270           outs() << "  ";
1271       }
1272       // Print ascii.
1273       outs() << "  ";
1274       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1275         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1276           outs() << Contents[addr + i];
1277         else
1278           outs() << ".";
1279       }
1280       outs() << "\n";
1281     }
1282   }
1283 }
1284 
1285 void llvm::PrintSymbolTable(const ObjectFile *o) {
1286   outs() << "SYMBOL TABLE:\n";
1287 
1288   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1289     printCOFFSymbolTable(coff);
1290     return;
1291   }
1292   for (const SymbolRef &Symbol : o->symbols()) {
1293     ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1294     error(AddressOrError.getError());
1295     uint64_t Address = *AddressOrError;
1296     SymbolRef::Type Type = Symbol.getType();
1297     uint32_t Flags = Symbol.getFlags();
1298     ErrorOr<section_iterator> SectionOrErr = Symbol.getSection();
1299     error(SectionOrErr.getError());
1300     section_iterator Section = *SectionOrErr;
1301     StringRef Name;
1302     if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1303       Section->getName(Name);
1304     } else {
1305       ErrorOr<StringRef> NameOrErr = Symbol.getName();
1306       error(NameOrErr.getError());
1307       Name = *NameOrErr;
1308     }
1309 
1310     bool Global = Flags & SymbolRef::SF_Global;
1311     bool Weak = Flags & SymbolRef::SF_Weak;
1312     bool Absolute = Flags & SymbolRef::SF_Absolute;
1313     bool Common = Flags & SymbolRef::SF_Common;
1314     bool Hidden = Flags & SymbolRef::SF_Hidden;
1315 
1316     char GlobLoc = ' ';
1317     if (Type != SymbolRef::ST_Unknown)
1318       GlobLoc = Global ? 'g' : 'l';
1319     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1320                  ? 'd' : ' ';
1321     char FileFunc = ' ';
1322     if (Type == SymbolRef::ST_File)
1323       FileFunc = 'f';
1324     else if (Type == SymbolRef::ST_Function)
1325       FileFunc = 'F';
1326 
1327     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1328                                                    "%08" PRIx64;
1329 
1330     outs() << format(Fmt, Address) << " "
1331            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1332            << (Weak ? 'w' : ' ') // Weak?
1333            << ' ' // Constructor. Not supported yet.
1334            << ' ' // Warning. Not supported yet.
1335            << ' ' // Indirect reference to another symbol.
1336            << Debug // Debugging (d) or dynamic (D) symbol.
1337            << FileFunc // Name of function (F), file (f) or object (O).
1338            << ' ';
1339     if (Absolute) {
1340       outs() << "*ABS*";
1341     } else if (Common) {
1342       outs() << "*COM*";
1343     } else if (Section == o->section_end()) {
1344       outs() << "*UND*";
1345     } else {
1346       if (const MachOObjectFile *MachO =
1347           dyn_cast<const MachOObjectFile>(o)) {
1348         DataRefImpl DR = Section->getRawDataRefImpl();
1349         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1350         outs() << SegmentName << ",";
1351       }
1352       StringRef SectionName;
1353       error(Section->getName(SectionName));
1354       outs() << SectionName;
1355     }
1356 
1357     outs() << '\t';
1358     if (Common || isa<ELFObjectFileBase>(o)) {
1359       uint64_t Val =
1360           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1361       outs() << format("\t %08" PRIx64 " ", Val);
1362     }
1363 
1364     if (Hidden) {
1365       outs() << ".hidden ";
1366     }
1367     outs() << Name
1368            << '\n';
1369   }
1370 }
1371 
1372 static void PrintUnwindInfo(const ObjectFile *o) {
1373   outs() << "Unwind info:\n\n";
1374 
1375   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1376     printCOFFUnwindInfo(coff);
1377   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1378     printMachOUnwindInfo(MachO);
1379   else {
1380     // TODO: Extract DWARF dump tool to objdump.
1381     errs() << "This operation is only currently supported "
1382               "for COFF and MachO object files.\n";
1383     return;
1384   }
1385 }
1386 
1387 void llvm::printExportsTrie(const ObjectFile *o) {
1388   outs() << "Exports trie:\n";
1389   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1390     printMachOExportsTrie(MachO);
1391   else {
1392     errs() << "This operation is only currently supported "
1393               "for Mach-O executable files.\n";
1394     return;
1395   }
1396 }
1397 
1398 void llvm::printRebaseTable(const ObjectFile *o) {
1399   outs() << "Rebase table:\n";
1400   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1401     printMachORebaseTable(MachO);
1402   else {
1403     errs() << "This operation is only currently supported "
1404               "for Mach-O executable files.\n";
1405     return;
1406   }
1407 }
1408 
1409 void llvm::printBindTable(const ObjectFile *o) {
1410   outs() << "Bind table:\n";
1411   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1412     printMachOBindTable(MachO);
1413   else {
1414     errs() << "This operation is only currently supported "
1415               "for Mach-O executable files.\n";
1416     return;
1417   }
1418 }
1419 
1420 void llvm::printLazyBindTable(const ObjectFile *o) {
1421   outs() << "Lazy bind table:\n";
1422   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1423     printMachOLazyBindTable(MachO);
1424   else {
1425     errs() << "This operation is only currently supported "
1426               "for Mach-O executable files.\n";
1427     return;
1428   }
1429 }
1430 
1431 void llvm::printWeakBindTable(const ObjectFile *o) {
1432   outs() << "Weak bind table:\n";
1433   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1434     printMachOWeakBindTable(MachO);
1435   else {
1436     errs() << "This operation is only currently supported "
1437               "for Mach-O executable files.\n";
1438     return;
1439   }
1440 }
1441 
1442 /// Dump the raw contents of the __clangast section so the output can be piped
1443 /// into llvm-bcanalyzer.
1444 void llvm::printRawClangAST(const ObjectFile *Obj) {
1445   if (outs().is_displayed()) {
1446     errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1447               "the clang ast section.\n"
1448               "Please redirect the output to a file or another program such as "
1449               "llvm-bcanalyzer.\n";
1450     return;
1451   }
1452 
1453   StringRef ClangASTSectionName("__clangast");
1454   if (isa<COFFObjectFile>(Obj)) {
1455     ClangASTSectionName = "clangast";
1456   }
1457 
1458   Optional<object::SectionRef> ClangASTSection;
1459   for (auto Sec : ToolSectionFilter(*Obj)) {
1460     StringRef Name;
1461     Sec.getName(Name);
1462     if (Name == ClangASTSectionName) {
1463       ClangASTSection = Sec;
1464       break;
1465     }
1466   }
1467   if (!ClangASTSection)
1468     return;
1469 
1470   StringRef ClangASTContents;
1471   error(ClangASTSection.getValue().getContents(ClangASTContents));
1472   outs().write(ClangASTContents.data(), ClangASTContents.size());
1473 }
1474 
1475 static void printFaultMaps(const ObjectFile *Obj) {
1476   const char *FaultMapSectionName = nullptr;
1477 
1478   if (isa<ELFObjectFileBase>(Obj)) {
1479     FaultMapSectionName = ".llvm_faultmaps";
1480   } else if (isa<MachOObjectFile>(Obj)) {
1481     FaultMapSectionName = "__llvm_faultmaps";
1482   } else {
1483     errs() << "This operation is only currently supported "
1484               "for ELF and Mach-O executable files.\n";
1485     return;
1486   }
1487 
1488   Optional<object::SectionRef> FaultMapSection;
1489 
1490   for (auto Sec : ToolSectionFilter(*Obj)) {
1491     StringRef Name;
1492     Sec.getName(Name);
1493     if (Name == FaultMapSectionName) {
1494       FaultMapSection = Sec;
1495       break;
1496     }
1497   }
1498 
1499   outs() << "FaultMap table:\n";
1500 
1501   if (!FaultMapSection.hasValue()) {
1502     outs() << "<not found>\n";
1503     return;
1504   }
1505 
1506   StringRef FaultMapContents;
1507   error(FaultMapSection.getValue().getContents(FaultMapContents));
1508 
1509   FaultMapParser FMP(FaultMapContents.bytes_begin(),
1510                      FaultMapContents.bytes_end());
1511 
1512   outs() << FMP;
1513 }
1514 
1515 static void printPrivateFileHeaders(const ObjectFile *o) {
1516   if (o->isELF())
1517     printELFFileHeader(o);
1518   else if (o->isCOFF())
1519     printCOFFFileHeader(o);
1520   else if (o->isMachO()) {
1521     printMachOFileHeader(o);
1522     printMachOLoadCommands(o);
1523   } else
1524     report_fatal_error("Invalid/Unsupported object file format");
1525 }
1526 
1527 static void printFirstPrivateFileHeader(const ObjectFile *o) {
1528   if (o->isELF())
1529     printELFFileHeader(o);
1530   else if (o->isCOFF())
1531     printCOFFFileHeader(o);
1532   else if (o->isMachO())
1533     printMachOFileHeader(o);
1534   else
1535     report_fatal_error("Invalid/Unsupported object file format");
1536 }
1537 
1538 static void DumpObject(const ObjectFile *o) {
1539   // Avoid other output when using a raw option.
1540   if (!RawClangAST) {
1541     outs() << '\n';
1542     outs() << o->getFileName()
1543            << ":\tfile format " << o->getFileFormatName() << "\n\n";
1544   }
1545 
1546   if (Disassemble)
1547     DisassembleObject(o, Relocations);
1548   if (Relocations && !Disassemble)
1549     PrintRelocations(o);
1550   if (SectionHeaders)
1551     PrintSectionHeaders(o);
1552   if (SectionContents)
1553     PrintSectionContents(o);
1554   if (SymbolTable)
1555     PrintSymbolTable(o);
1556   if (UnwindInfo)
1557     PrintUnwindInfo(o);
1558   if (PrivateHeaders)
1559     printPrivateFileHeaders(o);
1560   if (FirstPrivateHeader)
1561     printFirstPrivateFileHeader(o);
1562   if (ExportsTrie)
1563     printExportsTrie(o);
1564   if (Rebase)
1565     printRebaseTable(o);
1566   if (Bind)
1567     printBindTable(o);
1568   if (LazyBind)
1569     printLazyBindTable(o);
1570   if (WeakBind)
1571     printWeakBindTable(o);
1572   if (RawClangAST)
1573     printRawClangAST(o);
1574   if (PrintFaultMaps)
1575     printFaultMaps(o);
1576   if (DwarfDumpType != DIDT_Null) {
1577     std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1578     // Dump the complete DWARF structure.
1579     DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1580   }
1581 }
1582 
1583 /// @brief Dump each object file in \a a;
1584 static void DumpArchive(const Archive *a) {
1585   for (auto &ErrorOrChild : a->children()) {
1586     if (std::error_code EC = ErrorOrChild.getError())
1587       report_error(a->getFileName(), EC);
1588     const Archive::Child &C = *ErrorOrChild;
1589     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1590     if (std::error_code EC = ChildOrErr.getError())
1591       if (EC != object_error::invalid_file_type)
1592         report_error(a->getFileName(), EC);
1593     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1594       DumpObject(o);
1595     else
1596       report_error(a->getFileName(), object_error::invalid_file_type);
1597   }
1598 }
1599 
1600 /// @brief Open file and figure out how to dump it.
1601 static void DumpInput(StringRef file) {
1602 
1603   // If we are using the Mach-O specific object file parser, then let it parse
1604   // the file and process the command line options.  So the -arch flags can
1605   // be used to select specific slices, etc.
1606   if (MachOOpt) {
1607     ParseInputMachO(file);
1608     return;
1609   }
1610 
1611   // Attempt to open the binary.
1612   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1613   if (std::error_code EC = BinaryOrErr.getError())
1614     report_error(file, EC);
1615   Binary &Binary = *BinaryOrErr.get().getBinary();
1616 
1617   if (Archive *a = dyn_cast<Archive>(&Binary))
1618     DumpArchive(a);
1619   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
1620     DumpObject(o);
1621   else
1622     report_error(file, object_error::invalid_file_type);
1623 }
1624 
1625 int main(int argc, char **argv) {
1626   // Print a stack trace if we signal out.
1627   sys::PrintStackTraceOnErrorSignal();
1628   PrettyStackTraceProgram X(argc, argv);
1629   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
1630 
1631   // Initialize targets and assembly printers/parsers.
1632   llvm::InitializeAllTargetInfos();
1633   llvm::InitializeAllTargetMCs();
1634   llvm::InitializeAllDisassemblers();
1635 
1636   // Register the target printer for --version.
1637   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1638 
1639   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1640   TripleName = Triple::normalize(TripleName);
1641 
1642   ToolName = argv[0];
1643 
1644   // Defaults to a.out if no filenames specified.
1645   if (InputFilenames.size() == 0)
1646     InputFilenames.push_back("a.out");
1647 
1648   if (DisassembleAll)
1649     Disassemble = true;
1650   if (!Disassemble
1651       && !Relocations
1652       && !SectionHeaders
1653       && !SectionContents
1654       && !SymbolTable
1655       && !UnwindInfo
1656       && !PrivateHeaders
1657       && !FirstPrivateHeader
1658       && !ExportsTrie
1659       && !Rebase
1660       && !Bind
1661       && !LazyBind
1662       && !WeakBind
1663       && !RawClangAST
1664       && !(UniversalHeaders && MachOOpt)
1665       && !(ArchiveHeaders && MachOOpt)
1666       && !(IndirectSymbols && MachOOpt)
1667       && !(DataInCode && MachOOpt)
1668       && !(LinkOptHints && MachOOpt)
1669       && !(InfoPlist && MachOOpt)
1670       && !(DylibsUsed && MachOOpt)
1671       && !(DylibId && MachOOpt)
1672       && !(ObjcMetaData && MachOOpt)
1673       && !(FilterSections.size() != 0 && MachOOpt)
1674       && !PrintFaultMaps
1675       && DwarfDumpType == DIDT_Null) {
1676     cl::PrintHelpMessage();
1677     return 2;
1678   }
1679 
1680   std::for_each(InputFilenames.begin(), InputFilenames.end(),
1681                 DumpInput);
1682 
1683   return EXIT_SUCCESS;
1684 }
1685