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