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