xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision 7116e8963df0f3507b86c36953b22d4958b299f1)
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     typedef support::ulittle32_t U32;
599 
600     if (MI) {
601       SmallString<40> InstStr;
602       raw_svector_ostream IS(InstStr);
603 
604       IP.printInst(MI, IS, "", STI);
605 
606       OS << left_justify(IS.str(), 60);
607     } else {
608       // an unrecognized encoding - this is probably data so represent it
609       // using the .long directive, or .byte directive if fewer than 4 bytes
610       // remaining
611       if (Bytes.size() >= 4) {
612         OS << format("\t.long 0x%08" PRIx32 " ",
613                      static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
614         OS.indent(42);
615       } else {
616           OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
617           for (unsigned int i = 1; i < Bytes.size(); i++)
618             OS << format(", 0x%02" PRIx8, Bytes[i]);
619           OS.indent(55 - (6 * Bytes.size()));
620       }
621     }
622 
623     OS << format("// %012" PRIX64 ": ", Address);
624     if (Bytes.size() >=4) {
625       for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
626                                  Bytes.size() / sizeof(U32)))
627         // D should be explicitly casted to uint32_t here as it is passed
628         // by format to snprintf as vararg.
629         OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
630     } else {
631       for (unsigned int i = 0; i < Bytes.size(); i++)
632         OS << format("%02" PRIX8 " ", Bytes[i]);
633     }
634 
635     if (!Annot.empty())
636       OS << "// " << Annot;
637   }
638 };
639 AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
640 
641 class BPFPrettyPrinter : public PrettyPrinter {
642 public:
643   void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
644                  uint64_t Address, raw_ostream &OS, StringRef Annot,
645                  MCSubtargetInfo const &STI, SourcePrinter *SP) override {
646     if (SP && (PrintSource || PrintLines))
647       SP->printSourceLine(OS, Address);
648     if (!NoLeadingAddr)
649       OS << format("%8" PRId64 ":", Address / 8);
650     if (!NoShowRawInsn) {
651       OS << "\t";
652       dumpBytes(Bytes, OS);
653     }
654     if (MI)
655       IP.printInst(MI, OS, "", STI);
656     else
657       OS << " <unknown>";
658   }
659 };
660 BPFPrettyPrinter BPFPrettyPrinterInst;
661 
662 PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
663   switch(Triple.getArch()) {
664   default:
665     return PrettyPrinterInst;
666   case Triple::hexagon:
667     return HexagonPrettyPrinterInst;
668   case Triple::amdgcn:
669     return AMDGCNPrettyPrinterInst;
670   case Triple::bpfel:
671   case Triple::bpfeb:
672     return BPFPrettyPrinterInst;
673   }
674 }
675 }
676 
677 template <class ELFT>
678 static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
679                                                 const RelocationRef &RelRef,
680                                                 SmallVectorImpl<char> &Result) {
681   DataRefImpl Rel = RelRef.getRawDataRefImpl();
682 
683   typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
684   typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
685   typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
686 
687   const ELFFile<ELFT> &EF = *Obj->getELFFile();
688 
689   auto SecOrErr = EF.getSection(Rel.d.a);
690   if (!SecOrErr)
691     return errorToErrorCode(SecOrErr.takeError());
692   const Elf_Shdr *Sec = *SecOrErr;
693   auto SymTabOrErr = EF.getSection(Sec->sh_link);
694   if (!SymTabOrErr)
695     return errorToErrorCode(SymTabOrErr.takeError());
696   const Elf_Shdr *SymTab = *SymTabOrErr;
697   assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
698          SymTab->sh_type == ELF::SHT_DYNSYM);
699   auto StrTabSec = EF.getSection(SymTab->sh_link);
700   if (!StrTabSec)
701     return errorToErrorCode(StrTabSec.takeError());
702   auto StrTabOrErr = EF.getStringTable(*StrTabSec);
703   if (!StrTabOrErr)
704     return errorToErrorCode(StrTabOrErr.takeError());
705   StringRef StrTab = *StrTabOrErr;
706   uint8_t type = RelRef.getType();
707   StringRef res;
708   int64_t addend = 0;
709   switch (Sec->sh_type) {
710   default:
711     return object_error::parse_failed;
712   case ELF::SHT_REL: {
713     // TODO: Read implicit addend from section data.
714     break;
715   }
716   case ELF::SHT_RELA: {
717     const Elf_Rela *ERela = Obj->getRela(Rel);
718     addend = ERela->r_addend;
719     break;
720   }
721   }
722   symbol_iterator SI = RelRef.getSymbol();
723   const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
724   StringRef Target;
725   if (symb->getType() == ELF::STT_SECTION) {
726     Expected<section_iterator> SymSI = SI->getSection();
727     if (!SymSI)
728       return errorToErrorCode(SymSI.takeError());
729     const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
730     auto SecName = EF.getSectionName(SymSec);
731     if (!SecName)
732       return errorToErrorCode(SecName.takeError());
733     Target = *SecName;
734   } else {
735     Expected<StringRef> SymName = symb->getName(StrTab);
736     if (!SymName)
737       return errorToErrorCode(SymName.takeError());
738     Target = *SymName;
739   }
740   switch (EF.getHeader()->e_machine) {
741   case ELF::EM_X86_64:
742     switch (type) {
743     case ELF::R_X86_64_PC8:
744     case ELF::R_X86_64_PC16:
745     case ELF::R_X86_64_PC32: {
746       std::string fmtbuf;
747       raw_string_ostream fmt(fmtbuf);
748       fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
749       fmt.flush();
750       Result.append(fmtbuf.begin(), fmtbuf.end());
751     } break;
752     case ELF::R_X86_64_8:
753     case ELF::R_X86_64_16:
754     case ELF::R_X86_64_32:
755     case ELF::R_X86_64_32S:
756     case ELF::R_X86_64_64: {
757       std::string fmtbuf;
758       raw_string_ostream fmt(fmtbuf);
759       fmt << Target << (addend < 0 ? "" : "+") << addend;
760       fmt.flush();
761       Result.append(fmtbuf.begin(), fmtbuf.end());
762     } break;
763     default:
764       res = "Unknown";
765     }
766     break;
767   case ELF::EM_LANAI:
768   case ELF::EM_AVR:
769   case ELF::EM_AARCH64: {
770     std::string fmtbuf;
771     raw_string_ostream fmt(fmtbuf);
772     fmt << Target;
773     if (addend != 0)
774       fmt << (addend < 0 ? "" : "+") << addend;
775     fmt.flush();
776     Result.append(fmtbuf.begin(), fmtbuf.end());
777     break;
778   }
779   case ELF::EM_386:
780   case ELF::EM_IAMCU:
781   case ELF::EM_ARM:
782   case ELF::EM_HEXAGON:
783   case ELF::EM_MIPS:
784   case ELF::EM_BPF:
785   case ELF::EM_RISCV:
786     res = Target;
787     break;
788   case ELF::EM_WEBASSEMBLY:
789     switch (type) {
790     case ELF::R_WEBASSEMBLY_DATA: {
791       std::string fmtbuf;
792       raw_string_ostream fmt(fmtbuf);
793       fmt << Target << (addend < 0 ? "" : "+") << addend;
794       fmt.flush();
795       Result.append(fmtbuf.begin(), fmtbuf.end());
796       break;
797     }
798     case ELF::R_WEBASSEMBLY_FUNCTION:
799       res = Target;
800       break;
801     default:
802       res = "Unknown";
803     }
804     break;
805   default:
806     res = "Unknown";
807   }
808   if (Result.empty())
809     Result.append(res.begin(), res.end());
810   return std::error_code();
811 }
812 
813 static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
814                                                 const RelocationRef &Rel,
815                                                 SmallVectorImpl<char> &Result) {
816   if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
817     return getRelocationValueString(ELF32LE, Rel, Result);
818   if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
819     return getRelocationValueString(ELF64LE, Rel, Result);
820   if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
821     return getRelocationValueString(ELF32BE, Rel, Result);
822   auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
823   return getRelocationValueString(ELF64BE, Rel, Result);
824 }
825 
826 static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
827                                                 const RelocationRef &Rel,
828                                                 SmallVectorImpl<char> &Result) {
829   symbol_iterator SymI = Rel.getSymbol();
830   Expected<StringRef> SymNameOrErr = SymI->getName();
831   if (!SymNameOrErr)
832     return errorToErrorCode(SymNameOrErr.takeError());
833   StringRef SymName = *SymNameOrErr;
834   Result.append(SymName.begin(), SymName.end());
835   return std::error_code();
836 }
837 
838 static void printRelocationTargetName(const MachOObjectFile *O,
839                                       const MachO::any_relocation_info &RE,
840                                       raw_string_ostream &fmt) {
841   bool IsScattered = O->isRelocationScattered(RE);
842 
843   // Target of a scattered relocation is an address.  In the interest of
844   // generating pretty output, scan through the symbol table looking for a
845   // symbol that aligns with that address.  If we find one, print it.
846   // Otherwise, we just print the hex address of the target.
847   if (IsScattered) {
848     uint32_t Val = O->getPlainRelocationSymbolNum(RE);
849 
850     for (const SymbolRef &Symbol : O->symbols()) {
851       std::error_code ec;
852       Expected<uint64_t> Addr = Symbol.getAddress();
853       if (!Addr)
854         report_error(O->getFileName(), Addr.takeError());
855       if (*Addr != Val)
856         continue;
857       Expected<StringRef> Name = Symbol.getName();
858       if (!Name)
859         report_error(O->getFileName(), Name.takeError());
860       fmt << *Name;
861       return;
862     }
863 
864     // If we couldn't find a symbol that this relocation refers to, try
865     // to find a section beginning instead.
866     for (const SectionRef &Section : ToolSectionFilter(*O)) {
867       std::error_code ec;
868 
869       StringRef Name;
870       uint64_t Addr = Section.getAddress();
871       if (Addr != Val)
872         continue;
873       if ((ec = Section.getName(Name)))
874         report_error(O->getFileName(), ec);
875       fmt << Name;
876       return;
877     }
878 
879     fmt << format("0x%x", Val);
880     return;
881   }
882 
883   StringRef S;
884   bool isExtern = O->getPlainRelocationExternal(RE);
885   uint64_t Val = O->getPlainRelocationSymbolNum(RE);
886 
887   if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
888     fmt << format("0x%0" PRIx64, Val);
889     return;
890   } else if (isExtern) {
891     symbol_iterator SI = O->symbol_begin();
892     advance(SI, Val);
893     Expected<StringRef> SOrErr = SI->getName();
894     if (!SOrErr)
895       report_error(O->getFileName(), SOrErr.takeError());
896     S = *SOrErr;
897   } else {
898     section_iterator SI = O->section_begin();
899     // Adjust for the fact that sections are 1-indexed.
900     if (Val == 0) {
901       fmt << "0 (?,?)";
902       return;
903     }
904     uint32_t i = Val - 1;
905     while (i != 0 && SI != O->section_end()) {
906       i--;
907       advance(SI, 1);
908     }
909     if (SI == O->section_end())
910       fmt << Val << " (?,?)";
911     else
912       SI->getName(S);
913   }
914 
915   fmt << S;
916 }
917 
918 static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
919                                                 const RelocationRef &RelRef,
920                                                 SmallVectorImpl<char> &Result) {
921   const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
922   std::string fmtbuf;
923   raw_string_ostream fmt(fmtbuf);
924   fmt << Rel.Index << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
925   fmt.flush();
926   Result.append(fmtbuf.begin(), fmtbuf.end());
927   return std::error_code();
928 }
929 
930 static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
931                                                 const RelocationRef &RelRef,
932                                                 SmallVectorImpl<char> &Result) {
933   DataRefImpl Rel = RelRef.getRawDataRefImpl();
934   MachO::any_relocation_info RE = Obj->getRelocation(Rel);
935 
936   unsigned Arch = Obj->getArch();
937 
938   std::string fmtbuf;
939   raw_string_ostream fmt(fmtbuf);
940   unsigned Type = Obj->getAnyRelocationType(RE);
941   bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
942 
943   // Determine any addends that should be displayed with the relocation.
944   // These require decoding the relocation type, which is triple-specific.
945 
946   // X86_64 has entirely custom relocation types.
947   if (Arch == Triple::x86_64) {
948     bool isPCRel = Obj->getAnyRelocationPCRel(RE);
949 
950     switch (Type) {
951     case MachO::X86_64_RELOC_GOT_LOAD:
952     case MachO::X86_64_RELOC_GOT: {
953       printRelocationTargetName(Obj, RE, fmt);
954       fmt << "@GOT";
955       if (isPCRel)
956         fmt << "PCREL";
957       break;
958     }
959     case MachO::X86_64_RELOC_SUBTRACTOR: {
960       DataRefImpl RelNext = Rel;
961       Obj->moveRelocationNext(RelNext);
962       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
963 
964       // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
965       // X86_64_RELOC_UNSIGNED.
966       // NOTE: Scattered relocations don't exist on x86_64.
967       unsigned RType = Obj->getAnyRelocationType(RENext);
968       if (RType != MachO::X86_64_RELOC_UNSIGNED)
969         report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
970                      "X86_64_RELOC_SUBTRACTOR.");
971 
972       // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
973       // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
974       printRelocationTargetName(Obj, RENext, fmt);
975       fmt << "-";
976       printRelocationTargetName(Obj, RE, fmt);
977       break;
978     }
979     case MachO::X86_64_RELOC_TLV:
980       printRelocationTargetName(Obj, RE, fmt);
981       fmt << "@TLV";
982       if (isPCRel)
983         fmt << "P";
984       break;
985     case MachO::X86_64_RELOC_SIGNED_1:
986       printRelocationTargetName(Obj, RE, fmt);
987       fmt << "-1";
988       break;
989     case MachO::X86_64_RELOC_SIGNED_2:
990       printRelocationTargetName(Obj, RE, fmt);
991       fmt << "-2";
992       break;
993     case MachO::X86_64_RELOC_SIGNED_4:
994       printRelocationTargetName(Obj, RE, fmt);
995       fmt << "-4";
996       break;
997     default:
998       printRelocationTargetName(Obj, RE, fmt);
999       break;
1000     }
1001     // X86 and ARM share some relocation types in common.
1002   } else if (Arch == Triple::x86 || Arch == Triple::arm ||
1003              Arch == Triple::ppc) {
1004     // Generic relocation types...
1005     switch (Type) {
1006     case MachO::GENERIC_RELOC_PAIR: // prints no info
1007       return std::error_code();
1008     case MachO::GENERIC_RELOC_SECTDIFF: {
1009       DataRefImpl RelNext = Rel;
1010       Obj->moveRelocationNext(RelNext);
1011       MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1012 
1013       // X86 sect diff's must be followed by a relocation of type
1014       // GENERIC_RELOC_PAIR.
1015       unsigned RType = Obj->getAnyRelocationType(RENext);
1016 
1017       if (RType != MachO::GENERIC_RELOC_PAIR)
1018         report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
1019                      "GENERIC_RELOC_SECTDIFF.");
1020 
1021       printRelocationTargetName(Obj, RE, fmt);
1022       fmt << "-";
1023       printRelocationTargetName(Obj, RENext, fmt);
1024       break;
1025     }
1026     }
1027 
1028     if (Arch == Triple::x86 || Arch == Triple::ppc) {
1029       switch (Type) {
1030       case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
1031         DataRefImpl RelNext = Rel;
1032         Obj->moveRelocationNext(RelNext);
1033         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1034 
1035         // X86 sect diff's must be followed by a relocation of type
1036         // GENERIC_RELOC_PAIR.
1037         unsigned RType = Obj->getAnyRelocationType(RENext);
1038         if (RType != MachO::GENERIC_RELOC_PAIR)
1039           report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
1040                        "GENERIC_RELOC_LOCAL_SECTDIFF.");
1041 
1042         printRelocationTargetName(Obj, RE, fmt);
1043         fmt << "-";
1044         printRelocationTargetName(Obj, RENext, fmt);
1045         break;
1046       }
1047       case MachO::GENERIC_RELOC_TLV: {
1048         printRelocationTargetName(Obj, RE, fmt);
1049         fmt << "@TLV";
1050         if (IsPCRel)
1051           fmt << "P";
1052         break;
1053       }
1054       default:
1055         printRelocationTargetName(Obj, RE, fmt);
1056       }
1057     } else { // ARM-specific relocations
1058       switch (Type) {
1059       case MachO::ARM_RELOC_HALF:
1060       case MachO::ARM_RELOC_HALF_SECTDIFF: {
1061         // Half relocations steal a bit from the length field to encode
1062         // whether this is an upper16 or a lower16 relocation.
1063         bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
1064 
1065         if (isUpper)
1066           fmt << ":upper16:(";
1067         else
1068           fmt << ":lower16:(";
1069         printRelocationTargetName(Obj, RE, fmt);
1070 
1071         DataRefImpl RelNext = Rel;
1072         Obj->moveRelocationNext(RelNext);
1073         MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1074 
1075         // ARM half relocs must be followed by a relocation of type
1076         // ARM_RELOC_PAIR.
1077         unsigned RType = Obj->getAnyRelocationType(RENext);
1078         if (RType != MachO::ARM_RELOC_PAIR)
1079           report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
1080                        "ARM_RELOC_HALF");
1081 
1082         // NOTE: The half of the target virtual address is stashed in the
1083         // address field of the secondary relocation, but we can't reverse
1084         // engineer the constant offset from it without decoding the movw/movt
1085         // instruction to find the other half in its immediate field.
1086 
1087         // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1088         // symbol/section pointer of the follow-on relocation.
1089         if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1090           fmt << "-";
1091           printRelocationTargetName(Obj, RENext, fmt);
1092         }
1093 
1094         fmt << ")";
1095         break;
1096       }
1097       default: { printRelocationTargetName(Obj, RE, fmt); }
1098       }
1099     }
1100   } else
1101     printRelocationTargetName(Obj, RE, fmt);
1102 
1103   fmt.flush();
1104   Result.append(fmtbuf.begin(), fmtbuf.end());
1105   return std::error_code();
1106 }
1107 
1108 static std::error_code getRelocationValueString(const RelocationRef &Rel,
1109                                                 SmallVectorImpl<char> &Result) {
1110   const ObjectFile *Obj = Rel.getObject();
1111   if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1112     return getRelocationValueString(ELF, Rel, Result);
1113   if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1114     return getRelocationValueString(COFF, Rel, Result);
1115   if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
1116     return getRelocationValueString(Wasm, Rel, Result);
1117   if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
1118     return getRelocationValueString(MachO, Rel, Result);
1119   llvm_unreachable("unknown object file format");
1120 }
1121 
1122 /// @brief Indicates whether this relocation should hidden when listing
1123 /// relocations, usually because it is the trailing part of a multipart
1124 /// relocation that will be printed as part of the leading relocation.
1125 static bool getHidden(RelocationRef RelRef) {
1126   const ObjectFile *Obj = RelRef.getObject();
1127   auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1128   if (!MachO)
1129     return false;
1130 
1131   unsigned Arch = MachO->getArch();
1132   DataRefImpl Rel = RelRef.getRawDataRefImpl();
1133   uint64_t Type = MachO->getRelocationType(Rel);
1134 
1135   // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1136   // is always hidden.
1137   if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1138     if (Type == MachO::GENERIC_RELOC_PAIR)
1139       return true;
1140   } else if (Arch == Triple::x86_64) {
1141     // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1142     // an X86_64_RELOC_SUBTRACTOR.
1143     if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1144       DataRefImpl RelPrev = Rel;
1145       RelPrev.d.a--;
1146       uint64_t PrevType = MachO->getRelocationType(RelPrev);
1147       if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1148         return true;
1149     }
1150   }
1151 
1152   return false;
1153 }
1154 
1155 static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1156   assert(Obj->isELF());
1157   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1158     return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1159   if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1160     return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1161   if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1162     return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1163   if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1164     return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1165   llvm_unreachable("Unsupported binary format");
1166 }
1167 
1168 template <class ELFT> static void
1169 addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1170                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1171   for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1172     uint8_t SymbolType = Symbol.getELFType();
1173     if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1174       continue;
1175 
1176     Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1177     if (!AddressOrErr)
1178       report_error(Obj->getFileName(), AddressOrErr.takeError());
1179     uint64_t Address = *AddressOrErr;
1180 
1181     Expected<StringRef> Name = Symbol.getName();
1182     if (!Name)
1183       report_error(Obj->getFileName(), Name.takeError());
1184     if (Name->empty())
1185       continue;
1186 
1187     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1188     if (!SectionOrErr)
1189       report_error(Obj->getFileName(), SectionOrErr.takeError());
1190     section_iterator SecI = *SectionOrErr;
1191     if (SecI == Obj->section_end())
1192       continue;
1193 
1194     AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1195   }
1196 }
1197 
1198 static void
1199 addDynamicElfSymbols(const ObjectFile *Obj,
1200                      std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1201   assert(Obj->isELF());
1202   if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1203     addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1204   else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1205     addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1206   else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1207     addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1208   else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1209     addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1210   else
1211     llvm_unreachable("Unsupported binary format");
1212 }
1213 
1214 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1215   if (StartAddress > StopAddress)
1216     error("Start address should be less than stop address");
1217 
1218   const Target *TheTarget = getTarget(Obj);
1219 
1220   // Package up features to be passed to target/subtarget
1221   SubtargetFeatures Features = Obj->getFeatures();
1222   if (MAttrs.size()) {
1223     for (unsigned i = 0; i != MAttrs.size(); ++i)
1224       Features.AddFeature(MAttrs[i]);
1225   }
1226 
1227   std::unique_ptr<const MCRegisterInfo> MRI(
1228       TheTarget->createMCRegInfo(TripleName));
1229   if (!MRI)
1230     report_error(Obj->getFileName(), "no register info for target " +
1231                  TripleName);
1232 
1233   // Set up disassembler.
1234   std::unique_ptr<const MCAsmInfo> AsmInfo(
1235       TheTarget->createMCAsmInfo(*MRI, TripleName));
1236   if (!AsmInfo)
1237     report_error(Obj->getFileName(), "no assembly info for target " +
1238                  TripleName);
1239   std::unique_ptr<const MCSubtargetInfo> STI(
1240       TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1241   if (!STI)
1242     report_error(Obj->getFileName(), "no subtarget info for target " +
1243                  TripleName);
1244   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1245   if (!MII)
1246     report_error(Obj->getFileName(), "no instruction info for target " +
1247                  TripleName);
1248   MCObjectFileInfo MOFI;
1249   MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1250   // FIXME: for now initialize MCObjectFileInfo with default values
1251   MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1252 
1253   std::unique_ptr<MCDisassembler> DisAsm(
1254     TheTarget->createMCDisassembler(*STI, Ctx));
1255   if (!DisAsm)
1256     report_error(Obj->getFileName(), "no disassembler for target " +
1257                  TripleName);
1258 
1259   std::unique_ptr<const MCInstrAnalysis> MIA(
1260       TheTarget->createMCInstrAnalysis(MII.get()));
1261 
1262   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1263   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1264       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1265   if (!IP)
1266     report_error(Obj->getFileName(), "no instruction printer for target " +
1267                  TripleName);
1268   IP->setPrintImmHex(PrintImmHex);
1269   PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1270 
1271   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
1272                                                  "\t\t\t%08" PRIx64 ":  ";
1273 
1274   SourcePrinter SP(Obj, TheTarget->getName());
1275 
1276   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1277   // in RelocSecs contain the relocations for section S.
1278   std::error_code EC;
1279   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
1280   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1281     section_iterator Sec2 = Section.getRelocatedSection();
1282     if (Sec2 != Obj->section_end())
1283       SectionRelocMap[*Sec2].push_back(Section);
1284   }
1285 
1286   // Create a mapping from virtual address to symbol name.  This is used to
1287   // pretty print the symbols while disassembling.
1288   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1289   for (const SymbolRef &Symbol : Obj->symbols()) {
1290     Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1291     if (!AddressOrErr)
1292       report_error(Obj->getFileName(), AddressOrErr.takeError());
1293     uint64_t Address = *AddressOrErr;
1294 
1295     Expected<StringRef> Name = Symbol.getName();
1296     if (!Name)
1297       report_error(Obj->getFileName(), Name.takeError());
1298     if (Name->empty())
1299       continue;
1300 
1301     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1302     if (!SectionOrErr)
1303       report_error(Obj->getFileName(), SectionOrErr.takeError());
1304     section_iterator SecI = *SectionOrErr;
1305     if (SecI == Obj->section_end())
1306       continue;
1307 
1308     uint8_t SymbolType = ELF::STT_NOTYPE;
1309     if (Obj->isELF())
1310       SymbolType = getElfSymbolType(Obj, Symbol);
1311 
1312     AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1313 
1314   }
1315   if (AllSymbols.empty() && Obj->isELF())
1316     addDynamicElfSymbols(Obj, AllSymbols);
1317 
1318   // Create a mapping from virtual address to section.
1319   std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1320   for (SectionRef Sec : Obj->sections())
1321     SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1322   array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1323 
1324   // Linked executables (.exe and .dll files) typically don't include a real
1325   // symbol table but they might contain an export table.
1326   if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1327     for (const auto &ExportEntry : COFFObj->export_directories()) {
1328       StringRef Name;
1329       error(ExportEntry.getSymbolName(Name));
1330       if (Name.empty())
1331         continue;
1332       uint32_t RVA;
1333       error(ExportEntry.getExportRVA(RVA));
1334 
1335       uint64_t VA = COFFObj->getImageBase() + RVA;
1336       auto Sec = std::upper_bound(
1337           SectionAddresses.begin(), SectionAddresses.end(), VA,
1338           [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1339             return LHS < RHS.first;
1340           });
1341       if (Sec != SectionAddresses.begin())
1342         --Sec;
1343       else
1344         Sec = SectionAddresses.end();
1345 
1346       if (Sec != SectionAddresses.end())
1347         AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1348     }
1349   }
1350 
1351   // Sort all the symbols, this allows us to use a simple binary search to find
1352   // a symbol near an address.
1353   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1354     array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1355 
1356   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1357     if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1358       continue;
1359 
1360     uint64_t SectionAddr = Section.getAddress();
1361     uint64_t SectSize = Section.getSize();
1362     if (!SectSize)
1363       continue;
1364 
1365     // Get the list of all the symbols in this section.
1366     SectionSymbolsTy &Symbols = AllSymbols[Section];
1367     std::vector<uint64_t> DataMappingSymsAddr;
1368     std::vector<uint64_t> TextMappingSymsAddr;
1369     if (isArmElf(Obj)) {
1370       for (const auto &Symb : Symbols) {
1371         uint64_t Address = std::get<0>(Symb);
1372         StringRef Name = std::get<1>(Symb);
1373         if (Name.startswith("$d"))
1374           DataMappingSymsAddr.push_back(Address - SectionAddr);
1375         if (Name.startswith("$x"))
1376           TextMappingSymsAddr.push_back(Address - SectionAddr);
1377         if (Name.startswith("$a"))
1378           TextMappingSymsAddr.push_back(Address - SectionAddr);
1379         if (Name.startswith("$t"))
1380           TextMappingSymsAddr.push_back(Address - SectionAddr);
1381       }
1382     }
1383 
1384     std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1385     std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
1386 
1387     if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1388       // AMDGPU disassembler uses symbolizer for printing labels
1389       std::unique_ptr<MCRelocationInfo> RelInfo(
1390         TheTarget->createMCRelocationInfo(TripleName, Ctx));
1391       if (RelInfo) {
1392         std::unique_ptr<MCSymbolizer> Symbolizer(
1393           TheTarget->createMCSymbolizer(
1394             TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1395         DisAsm->setSymbolizer(std::move(Symbolizer));
1396       }
1397     }
1398 
1399     // Make a list of all the relocations for this section.
1400     std::vector<RelocationRef> Rels;
1401     if (InlineRelocs) {
1402       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1403         for (const RelocationRef &Reloc : RelocSec.relocations()) {
1404           Rels.push_back(Reloc);
1405         }
1406       }
1407     }
1408 
1409     // Sort relocations by address.
1410     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1411 
1412     StringRef SegmentName = "";
1413     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1414       DataRefImpl DR = Section.getRawDataRefImpl();
1415       SegmentName = MachO->getSectionFinalSegmentName(DR);
1416     }
1417     StringRef SectionName;
1418     error(Section.getName(SectionName));
1419 
1420     // If the section has no symbol at the start, just insert a dummy one.
1421     if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1422       Symbols.insert(
1423           Symbols.begin(),
1424           std::make_tuple(SectionAddr, SectionName,
1425                           Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1426     }
1427 
1428     SmallString<40> Comments;
1429     raw_svector_ostream CommentStream(Comments);
1430 
1431     StringRef BytesStr;
1432     error(Section.getContents(BytesStr));
1433     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1434                             BytesStr.size());
1435 
1436     uint64_t Size;
1437     uint64_t Index;
1438     bool PrintedSection = false;
1439 
1440     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1441     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1442     // Disassemble symbol by symbol.
1443     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1444       uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
1445       // The end is either the section end or the beginning of the next
1446       // symbol.
1447       uint64_t End =
1448           (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
1449       // Don't try to disassemble beyond the end of section contents.
1450       if (End > SectSize)
1451         End = SectSize;
1452       // If this symbol has the same address as the next symbol, then skip it.
1453       if (Start >= End)
1454         continue;
1455 
1456       // Check if we need to skip symbol
1457       // Skip if the symbol's data is not between StartAddress and StopAddress
1458       if (End + SectionAddr < StartAddress ||
1459           Start + SectionAddr > StopAddress) {
1460         continue;
1461       }
1462 
1463       /// Skip if user requested specific symbols and this is not in the list
1464       if (!DisasmFuncsSet.empty() &&
1465           !DisasmFuncsSet.count(std::get<1>(Symbols[si])))
1466         continue;
1467 
1468       if (!PrintedSection) {
1469         PrintedSection = true;
1470         outs() << "Disassembly of section ";
1471         if (!SegmentName.empty())
1472           outs() << SegmentName << ",";
1473         outs() << SectionName << ':';
1474       }
1475 
1476       // Stop disassembly at the stop address specified
1477       if (End + SectionAddr > StopAddress)
1478         End = StopAddress - SectionAddr;
1479 
1480       if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1481         if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1482           // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1483           Start += 256;
1484         }
1485         if (si == se - 1 ||
1486             std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1487           // cut trailing zeroes at the end of kernel
1488           // cut up to 256 bytes
1489           const uint64_t EndAlign = 256;
1490           const auto Limit = End - (std::min)(EndAlign, End - Start);
1491           while (End > Limit &&
1492             *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1493             End -= 4;
1494         }
1495       }
1496 
1497       outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
1498 
1499 #ifndef NDEBUG
1500       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1501 #else
1502       raw_ostream &DebugOut = nulls();
1503 #endif
1504 
1505       for (Index = Start; Index < End; Index += Size) {
1506         MCInst Inst;
1507 
1508         if (Index + SectionAddr < StartAddress ||
1509             Index + SectionAddr > StopAddress) {
1510           // skip byte by byte till StartAddress is reached
1511           Size = 1;
1512           continue;
1513         }
1514         // AArch64 ELF binaries can interleave data and text in the
1515         // same section. We rely on the markers introduced to
1516         // understand what we need to dump. If the data marker is within a
1517         // function, it is denoted as a word/short etc
1518         if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1519             !DisassembleAll) {
1520           uint64_t Stride = 0;
1521 
1522           auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1523                                       DataMappingSymsAddr.end(), Index);
1524           if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1525             // Switch to data.
1526             while (Index < End) {
1527               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1528               outs() << "\t";
1529               if (Index + 4 <= End) {
1530                 Stride = 4;
1531                 dumpBytes(Bytes.slice(Index, 4), outs());
1532                 outs() << "\t.word\t";
1533                 uint32_t Data = 0;
1534                 if (Obj->isLittleEndian()) {
1535                   const auto Word =
1536                       reinterpret_cast<const support::ulittle32_t *>(
1537                           Bytes.data() + Index);
1538                   Data = *Word;
1539                 } else {
1540                   const auto Word = reinterpret_cast<const support::ubig32_t *>(
1541                       Bytes.data() + Index);
1542                   Data = *Word;
1543                 }
1544                 outs() << "0x" << format("%08" PRIx32, Data);
1545               } else if (Index + 2 <= End) {
1546                 Stride = 2;
1547                 dumpBytes(Bytes.slice(Index, 2), outs());
1548                 outs() << "\t\t.short\t";
1549                 uint16_t Data = 0;
1550                 if (Obj->isLittleEndian()) {
1551                   const auto Short =
1552                       reinterpret_cast<const support::ulittle16_t *>(
1553                           Bytes.data() + Index);
1554                   Data = *Short;
1555                 } else {
1556                   const auto Short =
1557                       reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1558                                                                   Index);
1559                   Data = *Short;
1560                 }
1561                 outs() << "0x" << format("%04" PRIx16, Data);
1562               } else {
1563                 Stride = 1;
1564                 dumpBytes(Bytes.slice(Index, 1), outs());
1565                 outs() << "\t\t.byte\t";
1566                 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
1567               }
1568               Index += Stride;
1569               outs() << "\n";
1570               auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1571                                           TextMappingSymsAddr.end(), Index);
1572               if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1573                 break;
1574             }
1575           }
1576         }
1577 
1578         // If there is a data symbol inside an ELF text section and we are only
1579         // disassembling text (applicable all architectures),
1580         // we are in a situation where we must print the data and not
1581         // disassemble it.
1582         if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1583             !DisassembleAll && Section.isText()) {
1584           // print out data up to 8 bytes at a time in hex and ascii
1585           uint8_t AsciiData[9] = {'\0'};
1586           uint8_t Byte;
1587           int NumBytes = 0;
1588 
1589           for (Index = Start; Index < End; Index += 1) {
1590             if (((SectionAddr + Index) < StartAddress) ||
1591                 ((SectionAddr + Index) > StopAddress))
1592               continue;
1593             if (NumBytes == 0) {
1594               outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1595               outs() << "\t";
1596             }
1597             Byte = Bytes.slice(Index)[0];
1598             outs() << format(" %02x", Byte);
1599             AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1600 
1601             uint8_t IndentOffset = 0;
1602             NumBytes++;
1603             if (Index == End - 1 || NumBytes > 8) {
1604               // Indent the space for less than 8 bytes data.
1605               // 2 spaces for byte and one for space between bytes
1606               IndentOffset = 3 * (8 - NumBytes);
1607               for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1608                 AsciiData[Excess] = '\0';
1609               NumBytes = 8;
1610             }
1611             if (NumBytes == 8) {
1612               AsciiData[8] = '\0';
1613               outs() << std::string(IndentOffset, ' ') << "         ";
1614               outs() << reinterpret_cast<char *>(AsciiData);
1615               outs() << '\n';
1616               NumBytes = 0;
1617             }
1618           }
1619         }
1620         if (Index >= End)
1621           break;
1622 
1623         // Disassemble a real instruction or a data when disassemble all is
1624         // provided
1625         bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1626                                                    SectionAddr + Index, DebugOut,
1627                                                    CommentStream);
1628         if (Size == 0)
1629           Size = 1;
1630 
1631         PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1632                       Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1633                       *STI, &SP);
1634         outs() << CommentStream.str();
1635         Comments.clear();
1636 
1637         // Try to resolve the target of a call, tail call, etc. to a specific
1638         // symbol.
1639         if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1640                     MIA->isConditionalBranch(Inst))) {
1641           uint64_t Target;
1642           if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1643             // In a relocatable object, the target's section must reside in
1644             // the same section as the call instruction or it is accessed
1645             // through a relocation.
1646             //
1647             // In a non-relocatable object, the target may be in any section.
1648             //
1649             // N.B. We don't walk the relocations in the relocatable case yet.
1650             auto *TargetSectionSymbols = &Symbols;
1651             if (!Obj->isRelocatableObject()) {
1652               auto SectionAddress = std::upper_bound(
1653                   SectionAddresses.begin(), SectionAddresses.end(), Target,
1654                   [](uint64_t LHS,
1655                       const std::pair<uint64_t, SectionRef> &RHS) {
1656                     return LHS < RHS.first;
1657                   });
1658               if (SectionAddress != SectionAddresses.begin()) {
1659                 --SectionAddress;
1660                 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1661               } else {
1662                 TargetSectionSymbols = nullptr;
1663               }
1664             }
1665 
1666             // Find the first symbol in the section whose offset is less than
1667             // or equal to the target.
1668             if (TargetSectionSymbols) {
1669               auto TargetSym = std::upper_bound(
1670                   TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1671                   Target, [](uint64_t LHS,
1672                              const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1673                     return LHS < std::get<0>(RHS);
1674                   });
1675               if (TargetSym != TargetSectionSymbols->begin()) {
1676                 --TargetSym;
1677                 uint64_t TargetAddress = std::get<0>(*TargetSym);
1678                 StringRef TargetName = std::get<1>(*TargetSym);
1679                 outs() << " <" << TargetName;
1680                 uint64_t Disp = Target - TargetAddress;
1681                 if (Disp)
1682                   outs() << "+0x" << Twine::utohexstr(Disp);
1683                 outs() << '>';
1684               }
1685             }
1686           }
1687         }
1688         outs() << "\n";
1689 
1690         // Print relocation for instruction.
1691         while (rel_cur != rel_end) {
1692           bool hidden = getHidden(*rel_cur);
1693           uint64_t addr = rel_cur->getOffset();
1694           SmallString<16> name;
1695           SmallString<32> val;
1696 
1697           // If this relocation is hidden, skip it.
1698           if (hidden || ((SectionAddr + addr) < StartAddress)) {
1699             ++rel_cur;
1700             continue;
1701           }
1702 
1703           // Stop when rel_cur's address is past the current instruction.
1704           if (addr >= Index + Size) break;
1705           rel_cur->getTypeName(name);
1706           error(getRelocationValueString(*rel_cur, val));
1707           outs() << format(Fmt.data(), SectionAddr + addr) << name
1708                  << "\t" << val << "\n";
1709           ++rel_cur;
1710         }
1711       }
1712     }
1713   }
1714 }
1715 
1716 void llvm::PrintRelocations(const ObjectFile *Obj) {
1717   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1718                                                  "%08" PRIx64;
1719   // Regular objdump doesn't print relocations in non-relocatable object
1720   // files.
1721   if (!Obj->isRelocatableObject())
1722     return;
1723 
1724   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1725     if (Section.relocation_begin() == Section.relocation_end())
1726       continue;
1727     StringRef secname;
1728     error(Section.getName(secname));
1729     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1730     for (const RelocationRef &Reloc : Section.relocations()) {
1731       bool hidden = getHidden(Reloc);
1732       uint64_t address = Reloc.getOffset();
1733       SmallString<32> relocname;
1734       SmallString<32> valuestr;
1735       if (address < StartAddress || address > StopAddress || hidden)
1736         continue;
1737       Reloc.getTypeName(relocname);
1738       error(getRelocationValueString(Reloc, valuestr));
1739       outs() << format(Fmt.data(), address) << " " << relocname << " "
1740              << valuestr << "\n";
1741     }
1742     outs() << "\n";
1743   }
1744 }
1745 
1746 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1747   outs() << "Sections:\n"
1748             "Idx Name          Size      Address          Type\n";
1749   unsigned i = 0;
1750   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1751     StringRef Name;
1752     error(Section.getName(Name));
1753     uint64_t Address = Section.getAddress();
1754     uint64_t Size = Section.getSize();
1755     bool Text = Section.isText();
1756     bool Data = Section.isData();
1757     bool BSS = Section.isBSS();
1758     std::string Type = (std::string(Text ? "TEXT " : "") +
1759                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1760     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1761                      Name.str().c_str(), Size, Address, Type.c_str());
1762     ++i;
1763   }
1764 }
1765 
1766 void llvm::PrintSectionContents(const ObjectFile *Obj) {
1767   std::error_code EC;
1768   for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1769     StringRef Name;
1770     StringRef Contents;
1771     error(Section.getName(Name));
1772     uint64_t BaseAddr = Section.getAddress();
1773     uint64_t Size = Section.getSize();
1774     if (!Size)
1775       continue;
1776 
1777     outs() << "Contents of section " << Name << ":\n";
1778     if (Section.isBSS()) {
1779       outs() << format("<skipping contents of bss section at [%04" PRIx64
1780                        ", %04" PRIx64 ")>\n",
1781                        BaseAddr, BaseAddr + Size);
1782       continue;
1783     }
1784 
1785     error(Section.getContents(Contents));
1786 
1787     // Dump out the content as hex and printable ascii characters.
1788     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1789       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
1790       // Dump line of hex.
1791       for (std::size_t i = 0; i < 16; ++i) {
1792         if (i != 0 && i % 4 == 0)
1793           outs() << ' ';
1794         if (addr + i < end)
1795           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1796                  << hexdigit(Contents[addr + i] & 0xF, true);
1797         else
1798           outs() << "  ";
1799       }
1800       // Print ascii.
1801       outs() << "  ";
1802       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1803         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1804           outs() << Contents[addr + i];
1805         else
1806           outs() << ".";
1807       }
1808       outs() << "\n";
1809     }
1810   }
1811 }
1812 
1813 void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1814                             StringRef ArchitectureName) {
1815   outs() << "SYMBOL TABLE:\n";
1816 
1817   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1818     printCOFFSymbolTable(coff);
1819     return;
1820   }
1821   for (const SymbolRef &Symbol : o->symbols()) {
1822     Expected<uint64_t> AddressOrError = Symbol.getAddress();
1823     if (!AddressOrError)
1824       report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1825                    ArchitectureName);
1826     uint64_t Address = *AddressOrError;
1827     if ((Address < StartAddress) || (Address > StopAddress))
1828       continue;
1829     Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1830     if (!TypeOrError)
1831       report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1832                    ArchitectureName);
1833     SymbolRef::Type Type = *TypeOrError;
1834     uint32_t Flags = Symbol.getFlags();
1835     Expected<section_iterator> SectionOrErr = Symbol.getSection();
1836     if (!SectionOrErr)
1837       report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1838                    ArchitectureName);
1839     section_iterator Section = *SectionOrErr;
1840     StringRef Name;
1841     if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1842       Section->getName(Name);
1843     } else {
1844       Expected<StringRef> NameOrErr = Symbol.getName();
1845       if (!NameOrErr)
1846         report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1847                      ArchitectureName);
1848       Name = *NameOrErr;
1849     }
1850 
1851     bool Global = Flags & SymbolRef::SF_Global;
1852     bool Weak = Flags & SymbolRef::SF_Weak;
1853     bool Absolute = Flags & SymbolRef::SF_Absolute;
1854     bool Common = Flags & SymbolRef::SF_Common;
1855     bool Hidden = Flags & SymbolRef::SF_Hidden;
1856 
1857     char GlobLoc = ' ';
1858     if (Type != SymbolRef::ST_Unknown)
1859       GlobLoc = Global ? 'g' : 'l';
1860     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1861                  ? 'd' : ' ';
1862     char FileFunc = ' ';
1863     if (Type == SymbolRef::ST_File)
1864       FileFunc = 'f';
1865     else if (Type == SymbolRef::ST_Function)
1866       FileFunc = 'F';
1867 
1868     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1869                                                    "%08" PRIx64;
1870 
1871     outs() << format(Fmt, Address) << " "
1872            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1873            << (Weak ? 'w' : ' ') // Weak?
1874            << ' ' // Constructor. Not supported yet.
1875            << ' ' // Warning. Not supported yet.
1876            << ' ' // Indirect reference to another symbol.
1877            << Debug // Debugging (d) or dynamic (D) symbol.
1878            << FileFunc // Name of function (F), file (f) or object (O).
1879            << ' ';
1880     if (Absolute) {
1881       outs() << "*ABS*";
1882     } else if (Common) {
1883       outs() << "*COM*";
1884     } else if (Section == o->section_end()) {
1885       outs() << "*UND*";
1886     } else {
1887       if (const MachOObjectFile *MachO =
1888           dyn_cast<const MachOObjectFile>(o)) {
1889         DataRefImpl DR = Section->getRawDataRefImpl();
1890         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1891         outs() << SegmentName << ",";
1892       }
1893       StringRef SectionName;
1894       error(Section->getName(SectionName));
1895       outs() << SectionName;
1896     }
1897 
1898     outs() << '\t';
1899     if (Common || isa<ELFObjectFileBase>(o)) {
1900       uint64_t Val =
1901           Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
1902       outs() << format("\t %08" PRIx64 " ", Val);
1903     }
1904 
1905     if (Hidden) {
1906       outs() << ".hidden ";
1907     }
1908     outs() << Name
1909            << '\n';
1910   }
1911 }
1912 
1913 static void PrintUnwindInfo(const ObjectFile *o) {
1914   outs() << "Unwind info:\n\n";
1915 
1916   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1917     printCOFFUnwindInfo(coff);
1918   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1919     printMachOUnwindInfo(MachO);
1920   else {
1921     // TODO: Extract DWARF dump tool to objdump.
1922     errs() << "This operation is only currently supported "
1923               "for COFF and MachO object files.\n";
1924     return;
1925   }
1926 }
1927 
1928 void llvm::printExportsTrie(const ObjectFile *o) {
1929   outs() << "Exports trie:\n";
1930   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1931     printMachOExportsTrie(MachO);
1932   else {
1933     errs() << "This operation is only currently supported "
1934               "for Mach-O executable files.\n";
1935     return;
1936   }
1937 }
1938 
1939 void llvm::printRebaseTable(ObjectFile *o) {
1940   outs() << "Rebase table:\n";
1941   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1942     printMachORebaseTable(MachO);
1943   else {
1944     errs() << "This operation is only currently supported "
1945               "for Mach-O executable files.\n";
1946     return;
1947   }
1948 }
1949 
1950 void llvm::printBindTable(ObjectFile *o) {
1951   outs() << "Bind table:\n";
1952   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1953     printMachOBindTable(MachO);
1954   else {
1955     errs() << "This operation is only currently supported "
1956               "for Mach-O executable files.\n";
1957     return;
1958   }
1959 }
1960 
1961 void llvm::printLazyBindTable(ObjectFile *o) {
1962   outs() << "Lazy bind table:\n";
1963   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1964     printMachOLazyBindTable(MachO);
1965   else {
1966     errs() << "This operation is only currently supported "
1967               "for Mach-O executable files.\n";
1968     return;
1969   }
1970 }
1971 
1972 void llvm::printWeakBindTable(ObjectFile *o) {
1973   outs() << "Weak bind table:\n";
1974   if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1975     printMachOWeakBindTable(MachO);
1976   else {
1977     errs() << "This operation is only currently supported "
1978               "for Mach-O executable files.\n";
1979     return;
1980   }
1981 }
1982 
1983 /// Dump the raw contents of the __clangast section so the output can be piped
1984 /// into llvm-bcanalyzer.
1985 void llvm::printRawClangAST(const ObjectFile *Obj) {
1986   if (outs().is_displayed()) {
1987     errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1988               "the clang ast section.\n"
1989               "Please redirect the output to a file or another program such as "
1990               "llvm-bcanalyzer.\n";
1991     return;
1992   }
1993 
1994   StringRef ClangASTSectionName("__clangast");
1995   if (isa<COFFObjectFile>(Obj)) {
1996     ClangASTSectionName = "clangast";
1997   }
1998 
1999   Optional<object::SectionRef> ClangASTSection;
2000   for (auto Sec : ToolSectionFilter(*Obj)) {
2001     StringRef Name;
2002     Sec.getName(Name);
2003     if (Name == ClangASTSectionName) {
2004       ClangASTSection = Sec;
2005       break;
2006     }
2007   }
2008   if (!ClangASTSection)
2009     return;
2010 
2011   StringRef ClangASTContents;
2012   error(ClangASTSection.getValue().getContents(ClangASTContents));
2013   outs().write(ClangASTContents.data(), ClangASTContents.size());
2014 }
2015 
2016 static void printFaultMaps(const ObjectFile *Obj) {
2017   const char *FaultMapSectionName = nullptr;
2018 
2019   if (isa<ELFObjectFileBase>(Obj)) {
2020     FaultMapSectionName = ".llvm_faultmaps";
2021   } else if (isa<MachOObjectFile>(Obj)) {
2022     FaultMapSectionName = "__llvm_faultmaps";
2023   } else {
2024     errs() << "This operation is only currently supported "
2025               "for ELF and Mach-O executable files.\n";
2026     return;
2027   }
2028 
2029   Optional<object::SectionRef> FaultMapSection;
2030 
2031   for (auto Sec : ToolSectionFilter(*Obj)) {
2032     StringRef Name;
2033     Sec.getName(Name);
2034     if (Name == FaultMapSectionName) {
2035       FaultMapSection = Sec;
2036       break;
2037     }
2038   }
2039 
2040   outs() << "FaultMap table:\n";
2041 
2042   if (!FaultMapSection.hasValue()) {
2043     outs() << "<not found>\n";
2044     return;
2045   }
2046 
2047   StringRef FaultMapContents;
2048   error(FaultMapSection.getValue().getContents(FaultMapContents));
2049 
2050   FaultMapParser FMP(FaultMapContents.bytes_begin(),
2051                      FaultMapContents.bytes_end());
2052 
2053   outs() << FMP;
2054 }
2055 
2056 static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
2057   if (o->isELF())
2058     return printELFFileHeader(o);
2059   if (o->isCOFF())
2060     return printCOFFFileHeader(o);
2061   if (o->isWasm())
2062     return printWasmFileHeader(o);
2063   if (o->isMachO()) {
2064     printMachOFileHeader(o);
2065     if (!onlyFirst)
2066       printMachOLoadCommands(o);
2067     return;
2068   }
2069   report_error(o->getFileName(), "Invalid/Unsupported object file format");
2070 }
2071 
2072 static void DumpObject(ObjectFile *o, const Archive *a = nullptr) {
2073   StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
2074   // Avoid other output when using a raw option.
2075   if (!RawClangAST) {
2076     outs() << '\n';
2077     if (a)
2078       outs() << a->getFileName() << "(" << o->getFileName() << ")";
2079     else
2080       outs() << o->getFileName();
2081     outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
2082   }
2083 
2084   if (Disassemble)
2085     DisassembleObject(o, Relocations);
2086   if (Relocations && !Disassemble)
2087     PrintRelocations(o);
2088   if (SectionHeaders)
2089     PrintSectionHeaders(o);
2090   if (SectionContents)
2091     PrintSectionContents(o);
2092   if (SymbolTable)
2093     PrintSymbolTable(o, ArchiveName);
2094   if (UnwindInfo)
2095     PrintUnwindInfo(o);
2096   if (PrivateHeaders || FirstPrivateHeader)
2097     printPrivateFileHeaders(o, FirstPrivateHeader);
2098   if (ExportsTrie)
2099     printExportsTrie(o);
2100   if (Rebase)
2101     printRebaseTable(o);
2102   if (Bind)
2103     printBindTable(o);
2104   if (LazyBind)
2105     printLazyBindTable(o);
2106   if (WeakBind)
2107     printWeakBindTable(o);
2108   if (RawClangAST)
2109     printRawClangAST(o);
2110   if (PrintFaultMaps)
2111     printFaultMaps(o);
2112   if (DwarfDumpType != DIDT_Null) {
2113     std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
2114     // Dump the complete DWARF structure.
2115     DIDumpOptions DumpOpts;
2116     DumpOpts.DumpType = DwarfDumpType;
2117     DICtx->dump(outs(), DumpOpts);
2118   }
2119 }
2120 
2121 static void DumpObject(const COFFImportFile *I, const Archive *A) {
2122   StringRef ArchiveName = A ? A->getFileName() : "";
2123 
2124   // Avoid other output when using a raw option.
2125   if (!RawClangAST)
2126     outs() << '\n'
2127            << ArchiveName << "(" << I->getFileName() << ")"
2128            << ":\tfile format COFF-import-file"
2129            << "\n\n";
2130 
2131   if (SymbolTable)
2132     printCOFFSymbolTable(I);
2133 }
2134 
2135 /// @brief Dump each object file in \a a;
2136 static void DumpArchive(const Archive *a) {
2137   Error Err = Error::success();
2138   for (auto &C : a->children(Err)) {
2139     Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2140     if (!ChildOrErr) {
2141       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2142         report_error(a->getFileName(), C, std::move(E));
2143       continue;
2144     }
2145     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2146       DumpObject(o, a);
2147     else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2148       DumpObject(I, a);
2149     else
2150       report_error(a->getFileName(), object_error::invalid_file_type);
2151   }
2152   if (Err)
2153     report_error(a->getFileName(), std::move(Err));
2154 }
2155 
2156 /// @brief Open file and figure out how to dump it.
2157 static void DumpInput(StringRef file) {
2158 
2159   // If we are using the Mach-O specific object file parser, then let it parse
2160   // the file and process the command line options.  So the -arch flags can
2161   // be used to select specific slices, etc.
2162   if (MachOOpt) {
2163     ParseInputMachO(file);
2164     return;
2165   }
2166 
2167   // Attempt to open the binary.
2168   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2169   if (!BinaryOrErr)
2170     report_error(file, BinaryOrErr.takeError());
2171   Binary &Binary = *BinaryOrErr.get().getBinary();
2172 
2173   if (Archive *a = dyn_cast<Archive>(&Binary))
2174     DumpArchive(a);
2175   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
2176     DumpObject(o);
2177   else
2178     report_error(file, object_error::invalid_file_type);
2179 }
2180 
2181 int main(int argc, char **argv) {
2182   // Print a stack trace if we signal out.
2183   sys::PrintStackTraceOnErrorSignal(argv[0]);
2184   PrettyStackTraceProgram X(argc, argv);
2185   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
2186 
2187   // Initialize targets and assembly printers/parsers.
2188   llvm::InitializeAllTargetInfos();
2189   llvm::InitializeAllTargetMCs();
2190   llvm::InitializeAllDisassemblers();
2191 
2192   // Register the target printer for --version.
2193   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2194 
2195   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2196   TripleName = Triple::normalize(TripleName);
2197 
2198   ToolName = argv[0];
2199 
2200   // Defaults to a.out if no filenames specified.
2201   if (InputFilenames.size() == 0)
2202     InputFilenames.push_back("a.out");
2203 
2204   if (DisassembleAll || PrintSource || PrintLines)
2205     Disassemble = true;
2206   if (!Disassemble
2207       && !Relocations
2208       && !SectionHeaders
2209       && !SectionContents
2210       && !SymbolTable
2211       && !UnwindInfo
2212       && !PrivateHeaders
2213       && !FirstPrivateHeader
2214       && !ExportsTrie
2215       && !Rebase
2216       && !Bind
2217       && !LazyBind
2218       && !WeakBind
2219       && !RawClangAST
2220       && !(UniversalHeaders && MachOOpt)
2221       && !(ArchiveHeaders && MachOOpt)
2222       && !(IndirectSymbols && MachOOpt)
2223       && !(DataInCode && MachOOpt)
2224       && !(LinkOptHints && MachOOpt)
2225       && !(InfoPlist && MachOOpt)
2226       && !(DylibsUsed && MachOOpt)
2227       && !(DylibId && MachOOpt)
2228       && !(ObjcMetaData && MachOOpt)
2229       && !(FilterSections.size() != 0 && MachOOpt)
2230       && !PrintFaultMaps
2231       && DwarfDumpType == DIDT_Null) {
2232     cl::PrintHelpMessage();
2233     return 2;
2234   }
2235 
2236   DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2237                         DisassembleFunctions.end());
2238 
2239   llvm::for_each(InputFilenames, DumpInput);
2240 
2241   return EXIT_SUCCESS;
2242 }
2243