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