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