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