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