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