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