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