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