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