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