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