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