1 //===- ELFDumper.cpp - ELF-specific dumper --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements the ELF-specific dumper for llvm-readobj.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARMEHABIPrinter.h"
15 #include "DwarfCFIEHPrinter.h"
16 #include "ObjDumper.h"
17 #include "StackMapPrinter.h"
18 #include "llvm-readobj.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/MapVector.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/PointerIntPair.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/BinaryFormat/AMDGPUMetadataVerifier.h"
32 #include "llvm/BinaryFormat/ELF.h"
33 #include "llvm/Demangle/Demangle.h"
34 #include "llvm/Object/ELF.h"
35 #include "llvm/Object/ELFObjectFile.h"
36 #include "llvm/Object/ELFTypes.h"
37 #include "llvm/Object/Error.h"
38 #include "llvm/Object/ObjectFile.h"
39 #include "llvm/Object/RelocationResolver.h"
40 #include "llvm/Object/StackMapParser.h"
41 #include "llvm/Support/AMDGPUMetadata.h"
42 #include "llvm/Support/ARMAttributeParser.h"
43 #include "llvm/Support/ARMBuildAttributes.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Endian.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/Format.h"
49 #include "llvm/Support/FormatVariadic.h"
50 #include "llvm/Support/FormattedStream.h"
51 #include "llvm/Support/LEB128.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/MipsABIFlags.h"
54 #include "llvm/Support/RISCVAttributeParser.h"
55 #include "llvm/Support/RISCVAttributes.h"
56 #include "llvm/Support/ScopedPrinter.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include <algorithm>
59 #include <cinttypes>
60 #include <cstddef>
61 #include <cstdint>
62 #include <cstdlib>
63 #include <iterator>
64 #include <memory>
65 #include <string>
66 #include <system_error>
67 #include <vector>
68 
69 using namespace llvm;
70 using namespace llvm::object;
71 using namespace ELF;
72 
73 #define LLVM_READOBJ_ENUM_CASE(ns, enum)                                       \
74   case ns::enum:                                                               \
75     return #enum;
76 
77 #define ENUM_ENT(enum, altName)                                                \
78   { #enum, altName, ELF::enum }
79 
80 #define ENUM_ENT_1(enum)                                                       \
81   { #enum, #enum, ELF::enum }
82 
83 namespace {
84 
85 template <class ELFT> struct RelSymbol {
86   RelSymbol(const typename ELFT::Sym *S, StringRef N)
87       : Sym(S), Name(N.str()) {}
88   const typename ELFT::Sym *Sym;
89   std::string Name;
90 };
91 
92 /// Represents a contiguous uniform range in the file. We cannot just create a
93 /// range directly because when creating one of these from the .dynamic table
94 /// the size, entity size and virtual address are different entries in arbitrary
95 /// order (DT_REL, DT_RELSZ, DT_RELENT for example).
96 struct DynRegionInfo {
97   DynRegionInfo(const Binary &Owner, const ObjDumper &D)
98       : Obj(&Owner), Dumper(&D) {}
99   DynRegionInfo(const Binary &Owner, const ObjDumper &D, const uint8_t *A,
100                 uint64_t S, uint64_t ES)
101       : Addr(A), Size(S), EntSize(ES), Obj(&Owner), Dumper(&D) {}
102 
103   /// Address in current address space.
104   const uint8_t *Addr = nullptr;
105   /// Size in bytes of the region.
106   uint64_t Size = 0;
107   /// Size of each entity in the region.
108   uint64_t EntSize = 0;
109 
110   /// Owner object. Used for error reporting.
111   const Binary *Obj;
112   /// Dumper used for error reporting.
113   const ObjDumper *Dumper;
114   /// Error prefix. Used for error reporting to provide more information.
115   std::string Context;
116   /// Region size name. Used for error reporting.
117   StringRef SizePrintName = "size";
118   /// Entry size name. Used for error reporting. If this field is empty, errors
119   /// will not mention the entry size.
120   StringRef EntSizePrintName = "entry size";
121 
122   template <typename Type> ArrayRef<Type> getAsArrayRef() const {
123     const Type *Start = reinterpret_cast<const Type *>(Addr);
124     if (!Start)
125       return {Start, Start};
126 
127     const uint64_t Offset =
128         Addr - (const uint8_t *)Obj->getMemoryBufferRef().getBufferStart();
129     const uint64_t ObjSize = Obj->getMemoryBufferRef().getBufferSize();
130 
131     if (Size > ObjSize - Offset) {
132       Dumper->reportUniqueWarning(
133           "unable to read data at 0x" + Twine::utohexstr(Offset) +
134           " of size 0x" + Twine::utohexstr(Size) + " (" + SizePrintName +
135           "): it goes past the end of the file of size 0x" +
136           Twine::utohexstr(ObjSize));
137       return {Start, Start};
138     }
139 
140     if (EntSize == sizeof(Type) && (Size % EntSize == 0))
141       return {Start, Start + (Size / EntSize)};
142 
143     std::string Msg;
144     if (!Context.empty())
145       Msg += Context + " has ";
146 
147     Msg += ("invalid " + SizePrintName + " (0x" + Twine::utohexstr(Size) + ")")
148                .str();
149     if (!EntSizePrintName.empty())
150       Msg +=
151           (" or " + EntSizePrintName + " (0x" + Twine::utohexstr(EntSize) + ")")
152               .str();
153 
154     Dumper->reportUniqueWarning(Msg);
155     return {Start, Start};
156   }
157 };
158 
159 struct GroupMember {
160   StringRef Name;
161   uint64_t Index;
162 };
163 
164 struct GroupSection {
165   StringRef Name;
166   std::string Signature;
167   uint64_t ShName;
168   uint64_t Index;
169   uint32_t Link;
170   uint32_t Info;
171   uint32_t Type;
172   std::vector<GroupMember> Members;
173 };
174 
175 namespace {
176 
177 struct NoteType {
178   uint32_t ID;
179   StringRef Name;
180 };
181 
182 } // namespace
183 
184 template <class ELFT> class Relocation {
185 public:
186   Relocation(const typename ELFT::Rel &R, bool IsMips64EL)
187       : Type(R.getType(IsMips64EL)), Symbol(R.getSymbol(IsMips64EL)),
188         Offset(R.r_offset), Info(R.r_info) {}
189 
190   Relocation(const typename ELFT::Rela &R, bool IsMips64EL)
191       : Relocation((const typename ELFT::Rel &)R, IsMips64EL) {
192     Addend = R.r_addend;
193   }
194 
195   uint32_t Type;
196   uint32_t Symbol;
197   typename ELFT::uint Offset;
198   typename ELFT::uint Info;
199   Optional<int64_t> Addend;
200 };
201 
202 template <class ELFT> class MipsGOTParser;
203 
204 template <typename ELFT> class ELFDumper : public ObjDumper {
205   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
206 
207 public:
208   ELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer);
209 
210   void printUnwindInfo() override;
211   void printNeededLibraries() override;
212   void printHashTable() override;
213   void printGnuHashTable() override;
214   void printLoadName() override;
215   void printVersionInfo() override;
216   void printArchSpecificInfo() override;
217   void printStackMap() const override;
218 
219   const object::ELFObjectFile<ELFT> &getElfObject() const { return ObjF; };
220 
221   std::string describe(const Elf_Shdr &Sec) const;
222 
223   unsigned getHashTableEntSize() const {
224     // EM_S390 and ELF::EM_ALPHA platforms use 8-bytes entries in SHT_HASH
225     // sections. This violates the ELF specification.
226     if (Obj.getHeader().e_machine == ELF::EM_S390 ||
227         Obj.getHeader().e_machine == ELF::EM_ALPHA)
228       return 8;
229     return 4;
230   }
231 
232   Elf_Dyn_Range dynamic_table() const {
233     // A valid .dynamic section contains an array of entries terminated
234     // with a DT_NULL entry. However, sometimes the section content may
235     // continue past the DT_NULL entry, so to dump the section correctly,
236     // we first find the end of the entries by iterating over them.
237     Elf_Dyn_Range Table = DynamicTable.template getAsArrayRef<Elf_Dyn>();
238 
239     size_t Size = 0;
240     while (Size < Table.size())
241       if (Table[Size++].getTag() == DT_NULL)
242         break;
243 
244     return Table.slice(0, Size);
245   }
246 
247   Elf_Sym_Range dynamic_symbols() const {
248     if (!DynSymRegion)
249       return Elf_Sym_Range();
250     return DynSymRegion->template getAsArrayRef<Elf_Sym>();
251   }
252 
253   const Elf_Shdr *findSectionByName(StringRef Name) const;
254 
255   StringRef getDynamicStringTable() const { return DynamicStringTable; }
256 
257 protected:
258   virtual void printVersionSymbolSection(const Elf_Shdr *Sec) = 0;
259   virtual void printVersionDefinitionSection(const Elf_Shdr *Sec) = 0;
260   virtual void printVersionDependencySection(const Elf_Shdr *Sec) = 0;
261 
262   void
263   printDependentLibsHelper(function_ref<void(const Elf_Shdr &)> OnSectionStart,
264                            function_ref<void(StringRef, uint64_t)> OnLibEntry);
265 
266   virtual void printRelRelaReloc(const Relocation<ELFT> &R,
267                                  const RelSymbol<ELFT> &RelSym) = 0;
268   virtual void printRelrReloc(const Elf_Relr &R) = 0;
269   virtual void printDynamicRelocHeader(unsigned Type, StringRef Name,
270                                        const DynRegionInfo &Reg) {}
271   void printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
272                   const Elf_Shdr &Sec, const Elf_Shdr *SymTab);
273   void printDynamicReloc(const Relocation<ELFT> &R);
274   void printDynamicRelocationsHelper();
275   void printRelocationsHelper(const Elf_Shdr &Sec);
276   void forEachRelocationDo(
277       const Elf_Shdr &Sec, bool RawRelr,
278       llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
279                               const Elf_Shdr &, const Elf_Shdr *)>
280           RelRelaFn,
281       llvm::function_ref<void(const Elf_Relr &)> RelrFn);
282 
283   virtual void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
284                                   bool NonVisibilityBitsUsed) const {};
285   virtual void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
286                            DataRegion<Elf_Word> ShndxTable,
287                            Optional<StringRef> StrTable, bool IsDynamic,
288                            bool NonVisibilityBitsUsed) const = 0;
289 
290   virtual void printMipsABIFlags() = 0;
291   virtual void printMipsGOT(const MipsGOTParser<ELFT> &Parser) = 0;
292   virtual void printMipsPLT(const MipsGOTParser<ELFT> &Parser) = 0;
293 
294   Expected<ArrayRef<Elf_Versym>>
295   getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
296                   StringRef *StrTab, const Elf_Shdr **SymTabSec) const;
297   StringRef getPrintableSectionName(const Elf_Shdr &Sec) const;
298 
299   std::vector<GroupSection> getGroups();
300 
301   bool printFunctionStackSize(uint64_t SymValue,
302                               Optional<const Elf_Shdr *> FunctionSec,
303                               const Elf_Shdr &StackSizeSec, DataExtractor Data,
304                               uint64_t *Offset);
305   void printStackSize(const Relocation<ELFT> &R, const Elf_Shdr &RelocSec,
306                       unsigned Ndx, const Elf_Shdr *SymTab,
307                       const Elf_Shdr *FunctionSec, const Elf_Shdr &StackSizeSec,
308                       const RelocationResolver &Resolver, DataExtractor Data);
309   virtual void printStackSizeEntry(uint64_t Size, StringRef FuncName) = 0;
310 
311   void printRelocatableStackSizes(std::function<void()> PrintHeader);
312   void printNonRelocatableStackSizes(std::function<void()> PrintHeader);
313 
314   const object::ELFObjectFile<ELFT> &ObjF;
315   const ELFFile<ELFT> &Obj;
316   StringRef FileName;
317 
318   Expected<DynRegionInfo> createDRI(uint64_t Offset, uint64_t Size,
319                                     uint64_t EntSize) {
320     if (Offset + Size < Offset || Offset + Size > Obj.getBufSize())
321       return createError("offset (0x" + Twine::utohexstr(Offset) +
322                          ") + size (0x" + Twine::utohexstr(Size) +
323                          ") is greater than the file size (0x" +
324                          Twine::utohexstr(Obj.getBufSize()) + ")");
325     return DynRegionInfo(ObjF, *this, Obj.base() + Offset, Size, EntSize);
326   }
327 
328   void printAttributes();
329   void printMipsReginfo();
330   void printMipsOptions();
331 
332   std::pair<const Elf_Phdr *, const Elf_Shdr *> findDynamic();
333   void loadDynamicTable();
334   void parseDynamicTable();
335 
336   Expected<StringRef> getSymbolVersion(const Elf_Sym &Sym,
337                                        bool &IsDefault) const;
338   Expected<SmallVector<Optional<VersionEntry>, 0> *> getVersionMap() const;
339 
340   DynRegionInfo DynRelRegion;
341   DynRegionInfo DynRelaRegion;
342   DynRegionInfo DynRelrRegion;
343   DynRegionInfo DynPLTRelRegion;
344   Optional<DynRegionInfo> DynSymRegion;
345   DynRegionInfo DynSymTabShndxRegion;
346   DynRegionInfo DynamicTable;
347   StringRef DynamicStringTable;
348   const Elf_Hash *HashTable = nullptr;
349   const Elf_GnuHash *GnuHashTable = nullptr;
350   const Elf_Shdr *DotSymtabSec = nullptr;
351   const Elf_Shdr *DotDynsymSec = nullptr;
352   const Elf_Shdr *DotCGProfileSec = nullptr;
353   const Elf_Shdr *DotAddrsigSec = nullptr;
354   DenseMap<const Elf_Shdr *, ArrayRef<Elf_Word>> ShndxTables;
355   Optional<uint64_t> SONameOffset;
356 
357   const Elf_Shdr *SymbolVersionSection = nullptr;   // .gnu.version
358   const Elf_Shdr *SymbolVersionNeedSection = nullptr; // .gnu.version_r
359   const Elf_Shdr *SymbolVersionDefSection = nullptr; // .gnu.version_d
360 
361   std::string getFullSymbolName(const Elf_Sym &Symbol, unsigned SymIndex,
362                                 DataRegion<Elf_Word> ShndxTable,
363                                 Optional<StringRef> StrTable,
364                                 bool IsDynamic) const;
365   Expected<unsigned>
366   getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
367                         DataRegion<Elf_Word> ShndxTable) const;
368   Expected<StringRef> getSymbolSectionName(const Elf_Sym &Symbol,
369                                            unsigned SectionIndex) const;
370   std::string getStaticSymbolName(uint32_t Index) const;
371   StringRef getDynamicString(uint64_t Value) const;
372 
373   void printSymbolsHelper(bool IsDynamic) const;
374   std::string getDynamicEntry(uint64_t Type, uint64_t Value) const;
375 
376   Expected<RelSymbol<ELFT>> getRelocationTarget(const Relocation<ELFT> &R,
377                                                 const Elf_Shdr *SymTab) const;
378 
379   ArrayRef<Elf_Word> getShndxTable(const Elf_Shdr *Symtab) const;
380 
381 private:
382   mutable SmallVector<Optional<VersionEntry>, 0> VersionMap;
383 };
384 
385 template <class ELFT>
386 std::string ELFDumper<ELFT>::describe(const Elf_Shdr &Sec) const {
387   return ::describe(Obj, Sec);
388 }
389 
390 namespace {
391 
392 template <class ELFT> struct SymtabLink {
393   typename ELFT::SymRange Symbols;
394   StringRef StringTable;
395   const typename ELFT::Shdr *SymTab;
396 };
397 
398 // Returns the linked symbol table, symbols and associated string table for a
399 // given section.
400 template <class ELFT>
401 Expected<SymtabLink<ELFT>> getLinkAsSymtab(const ELFFile<ELFT> &Obj,
402                                            const typename ELFT::Shdr &Sec,
403                                            unsigned ExpectedType) {
404   Expected<const typename ELFT::Shdr *> SymtabOrErr =
405       Obj.getSection(Sec.sh_link);
406   if (!SymtabOrErr)
407     return createError("invalid section linked to " + describe(Obj, Sec) +
408                        ": " + toString(SymtabOrErr.takeError()));
409 
410   if ((*SymtabOrErr)->sh_type != ExpectedType)
411     return createError(
412         "invalid section linked to " + describe(Obj, Sec) + ": expected " +
413         object::getELFSectionTypeName(Obj.getHeader().e_machine, ExpectedType) +
414         ", but got " +
415         object::getELFSectionTypeName(Obj.getHeader().e_machine,
416                                       (*SymtabOrErr)->sh_type));
417 
418   Expected<StringRef> StrTabOrErr = Obj.getLinkAsStrtab(**SymtabOrErr);
419   if (!StrTabOrErr)
420     return createError(
421         "can't get a string table for the symbol table linked to " +
422         describe(Obj, Sec) + ": " + toString(StrTabOrErr.takeError()));
423 
424   Expected<typename ELFT::SymRange> SymsOrErr = Obj.symbols(*SymtabOrErr);
425   if (!SymsOrErr)
426     return createError("unable to read symbols from the " + describe(Obj, Sec) +
427                        ": " + toString(SymsOrErr.takeError()));
428 
429   return SymtabLink<ELFT>{*SymsOrErr, *StrTabOrErr, *SymtabOrErr};
430 }
431 
432 } // namespace
433 
434 template <class ELFT>
435 Expected<ArrayRef<typename ELFT::Versym>>
436 ELFDumper<ELFT>::getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
437                                  StringRef *StrTab,
438                                  const Elf_Shdr **SymTabSec) const {
439   assert((!SymTab && !StrTab && !SymTabSec) || (SymTab && StrTab && SymTabSec));
440   if (reinterpret_cast<uintptr_t>(Obj.base() + Sec.sh_offset) %
441           sizeof(uint16_t) !=
442       0)
443     return createError("the " + describe(Sec) + " is misaligned");
444 
445   Expected<ArrayRef<Elf_Versym>> VersionsOrErr =
446       Obj.template getSectionContentsAsArray<Elf_Versym>(Sec);
447   if (!VersionsOrErr)
448     return createError("cannot read content of " + describe(Sec) + ": " +
449                        toString(VersionsOrErr.takeError()));
450 
451   Expected<SymtabLink<ELFT>> SymTabOrErr =
452       getLinkAsSymtab(Obj, Sec, SHT_DYNSYM);
453   if (!SymTabOrErr) {
454     reportUniqueWarning(SymTabOrErr.takeError());
455     return *VersionsOrErr;
456   }
457 
458   if (SymTabOrErr->Symbols.size() != VersionsOrErr->size())
459     reportUniqueWarning(describe(Sec) + ": the number of entries (" +
460                         Twine(VersionsOrErr->size()) +
461                         ") does not match the number of symbols (" +
462                         Twine(SymTabOrErr->Symbols.size()) +
463                         ") in the symbol table with index " +
464                         Twine(Sec.sh_link));
465 
466   if (SymTab) {
467     *SymTab = SymTabOrErr->Symbols;
468     *StrTab = SymTabOrErr->StringTable;
469     *SymTabSec = SymTabOrErr->SymTab;
470   }
471   return *VersionsOrErr;
472 }
473 
474 template <class ELFT>
475 void ELFDumper<ELFT>::printSymbolsHelper(bool IsDynamic) const {
476   Optional<StringRef> StrTable;
477   size_t Entries = 0;
478   Elf_Sym_Range Syms(nullptr, nullptr);
479   const Elf_Shdr *SymtabSec = IsDynamic ? DotDynsymSec : DotSymtabSec;
480 
481   if (IsDynamic) {
482     StrTable = DynamicStringTable;
483     Syms = dynamic_symbols();
484     Entries = Syms.size();
485   } else if (DotSymtabSec) {
486     if (Expected<StringRef> StrTableOrErr =
487             Obj.getStringTableForSymtab(*DotSymtabSec))
488       StrTable = *StrTableOrErr;
489     else
490       reportUniqueWarning(
491           "unable to get the string table for the SHT_SYMTAB section: " +
492           toString(StrTableOrErr.takeError()));
493 
494     if (Expected<Elf_Sym_Range> SymsOrErr = Obj.symbols(DotSymtabSec))
495       Syms = *SymsOrErr;
496     else
497       reportUniqueWarning(
498           "unable to read symbols from the SHT_SYMTAB section: " +
499           toString(SymsOrErr.takeError()));
500     Entries = DotSymtabSec->getEntityCount();
501   }
502   if (Syms.empty())
503     return;
504 
505   // The st_other field has 2 logical parts. The first two bits hold the symbol
506   // visibility (STV_*) and the remainder hold other platform-specific values.
507   bool NonVisibilityBitsUsed =
508       llvm::any_of(Syms, [](const Elf_Sym &S) { return S.st_other & ~0x3; });
509 
510   DataRegion<Elf_Word> ShndxTable =
511       IsDynamic ? DataRegion<Elf_Word>(
512                       (const Elf_Word *)this->DynSymTabShndxRegion.Addr,
513                       this->getElfObject().getELFFile().end())
514                 : DataRegion<Elf_Word>(this->getShndxTable(SymtabSec));
515 
516   printSymtabMessage(SymtabSec, Entries, NonVisibilityBitsUsed);
517   for (const Elf_Sym &Sym : Syms)
518     printSymbol(Sym, &Sym - Syms.begin(), ShndxTable, StrTable, IsDynamic,
519                 NonVisibilityBitsUsed);
520 }
521 
522 template <typename ELFT> class GNUELFDumper : public ELFDumper<ELFT> {
523   formatted_raw_ostream &OS;
524 
525 public:
526   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
527 
528   GNUELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
529       : ELFDumper<ELFT>(ObjF, Writer),
530         OS(static_cast<formatted_raw_ostream &>(Writer.getOStream())) {
531     assert(&this->W.getOStream() == &llvm::fouts());
532   }
533 
534   void printFileHeaders() override;
535   void printGroupSections() override;
536   void printRelocations() override;
537   void printSectionHeaders() override;
538   void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols) override;
539   void printHashSymbols() override;
540   void printSectionDetails() override;
541   void printDependentLibs() override;
542   void printDynamicTable() override;
543   void printDynamicRelocations() override;
544   void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
545                           bool NonVisibilityBitsUsed) const override;
546   void printProgramHeaders(bool PrintProgramHeaders,
547                            cl::boolOrDefault PrintSectionMapping) override;
548   void printVersionSymbolSection(const Elf_Shdr *Sec) override;
549   void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
550   void printVersionDependencySection(const Elf_Shdr *Sec) override;
551   void printHashHistograms() override;
552   void printCGProfile() override;
553   void printAddrsig() override;
554   void printNotes() override;
555   void printELFLinkerOptions() override;
556   void printStackSizes() override;
557 
558 private:
559   void printHashHistogram(const Elf_Hash &HashTable);
560   void printGnuHashHistogram(const Elf_GnuHash &GnuHashTable);
561   void printHashTableSymbols(const Elf_Hash &HashTable);
562   void printGnuHashTableSymbols(const Elf_GnuHash &GnuHashTable);
563 
564   struct Field {
565     std::string Str;
566     unsigned Column;
567 
568     Field(StringRef S, unsigned Col) : Str(std::string(S)), Column(Col) {}
569     Field(unsigned Col) : Column(Col) {}
570   };
571 
572   template <typename T, typename TEnum>
573   std::string printEnum(T Value, ArrayRef<EnumEntry<TEnum>> EnumValues) const {
574     for (const EnumEntry<TEnum> &EnumItem : EnumValues)
575       if (EnumItem.Value == Value)
576         return std::string(EnumItem.AltName);
577     return to_hexString(Value, false);
578   }
579 
580   template <typename T, typename TEnum>
581   std::string printFlags(T Value, ArrayRef<EnumEntry<TEnum>> EnumValues,
582                          TEnum EnumMask1 = {}, TEnum EnumMask2 = {},
583                          TEnum EnumMask3 = {}) const {
584     std::string Str;
585     for (const EnumEntry<TEnum> &Flag : EnumValues) {
586       if (Flag.Value == 0)
587         continue;
588 
589       TEnum EnumMask{};
590       if (Flag.Value & EnumMask1)
591         EnumMask = EnumMask1;
592       else if (Flag.Value & EnumMask2)
593         EnumMask = EnumMask2;
594       else if (Flag.Value & EnumMask3)
595         EnumMask = EnumMask3;
596       bool IsEnum = (Flag.Value & EnumMask) != 0;
597       if ((!IsEnum && (Value & Flag.Value) == Flag.Value) ||
598           (IsEnum && (Value & EnumMask) == Flag.Value)) {
599         if (!Str.empty())
600           Str += ", ";
601         Str += Flag.AltName;
602       }
603     }
604     return Str;
605   }
606 
607   formatted_raw_ostream &printField(struct Field F) const {
608     if (F.Column != 0)
609       OS.PadToColumn(F.Column);
610     OS << F.Str;
611     OS.flush();
612     return OS;
613   }
614   void printHashedSymbol(const Elf_Sym *Sym, unsigned SymIndex,
615                          DataRegion<Elf_Word> ShndxTable, StringRef StrTable,
616                          uint32_t Bucket);
617   void printRelrReloc(const Elf_Relr &R) override;
618   void printRelRelaReloc(const Relocation<ELFT> &R,
619                          const RelSymbol<ELFT> &RelSym) override;
620   void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
621                    DataRegion<Elf_Word> ShndxTable,
622                    Optional<StringRef> StrTable, bool IsDynamic,
623                    bool NonVisibilityBitsUsed) const override;
624   void printDynamicRelocHeader(unsigned Type, StringRef Name,
625                                const DynRegionInfo &Reg) override;
626 
627   std::string getSymbolSectionNdx(const Elf_Sym &Symbol, unsigned SymIndex,
628                                   DataRegion<Elf_Word> ShndxTable) const;
629   void printProgramHeaders() override;
630   void printSectionMapping() override;
631   void printGNUVersionSectionProlog(const typename ELFT::Shdr &Sec,
632                                     const Twine &Label, unsigned EntriesNum);
633 
634   void printStackSizeEntry(uint64_t Size, StringRef FuncName) override;
635 
636   void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
637   void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
638   void printMipsABIFlags() override;
639 };
640 
641 template <typename ELFT> class LLVMELFDumper : public ELFDumper<ELFT> {
642 public:
643   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
644 
645   LLVMELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
646       : ELFDumper<ELFT>(ObjF, Writer), W(Writer) {}
647 
648   void printFileHeaders() override;
649   void printGroupSections() override;
650   void printRelocations() override;
651   void printSectionHeaders() override;
652   void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols) override;
653   void printDependentLibs() override;
654   void printDynamicTable() override;
655   void printDynamicRelocations() override;
656   void printProgramHeaders(bool PrintProgramHeaders,
657                            cl::boolOrDefault PrintSectionMapping) override;
658   void printVersionSymbolSection(const Elf_Shdr *Sec) override;
659   void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
660   void printVersionDependencySection(const Elf_Shdr *Sec) override;
661   void printHashHistograms() override;
662   void printCGProfile() override;
663   void printAddrsig() override;
664   void printNotes() override;
665   void printELFLinkerOptions() override;
666   void printStackSizes() override;
667 
668 private:
669   void printRelrReloc(const Elf_Relr &R) override;
670   void printRelRelaReloc(const Relocation<ELFT> &R,
671                          const RelSymbol<ELFT> &RelSym) override;
672 
673   void printSymbolSection(const Elf_Sym &Symbol, unsigned SymIndex,
674                           DataRegion<Elf_Word> ShndxTable) const;
675   void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
676                    DataRegion<Elf_Word> ShndxTable,
677                    Optional<StringRef> StrTable, bool IsDynamic,
678                    bool /*NonVisibilityBitsUsed*/) const override;
679   void printProgramHeaders() override;
680   void printSectionMapping() override {}
681   void printStackSizeEntry(uint64_t Size, StringRef FuncName) override;
682 
683   void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
684   void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
685   void printMipsABIFlags() override;
686 
687   ScopedPrinter &W;
688 };
689 
690 } // end anonymous namespace
691 
692 namespace llvm {
693 
694 template <class ELFT>
695 static std::unique_ptr<ObjDumper>
696 createELFDumper(const ELFObjectFile<ELFT> &Obj, ScopedPrinter &Writer) {
697   if (opts::Output == opts::GNU)
698     return std::make_unique<GNUELFDumper<ELFT>>(Obj, Writer);
699   return std::make_unique<LLVMELFDumper<ELFT>>(Obj, Writer);
700 }
701 
702 std::unique_ptr<ObjDumper> createELFDumper(const object::ELFObjectFileBase &Obj,
703                                            ScopedPrinter &Writer) {
704   // Little-endian 32-bit
705   if (const ELF32LEObjectFile *ELFObj = dyn_cast<ELF32LEObjectFile>(&Obj))
706     return createELFDumper(*ELFObj, Writer);
707 
708   // Big-endian 32-bit
709   if (const ELF32BEObjectFile *ELFObj = dyn_cast<ELF32BEObjectFile>(&Obj))
710     return createELFDumper(*ELFObj, Writer);
711 
712   // Little-endian 64-bit
713   if (const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(&Obj))
714     return createELFDumper(*ELFObj, Writer);
715 
716   // Big-endian 64-bit
717   return createELFDumper(*cast<ELF64BEObjectFile>(&Obj), Writer);
718 }
719 
720 } // end namespace llvm
721 
722 template <class ELFT>
723 Expected<SmallVector<Optional<VersionEntry>, 0> *>
724 ELFDumper<ELFT>::getVersionMap() const {
725   // If the VersionMap has already been loaded or if there is no dynamic symtab
726   // or version table, there is nothing to do.
727   if (!VersionMap.empty() || !DynSymRegion || !SymbolVersionSection)
728     return &VersionMap;
729 
730   Expected<SmallVector<Optional<VersionEntry>, 0>> MapOrErr =
731       Obj.loadVersionMap(SymbolVersionNeedSection, SymbolVersionDefSection);
732   if (MapOrErr)
733     VersionMap = *MapOrErr;
734   else
735     return MapOrErr.takeError();
736 
737   return &VersionMap;
738 }
739 
740 template <typename ELFT>
741 Expected<StringRef> ELFDumper<ELFT>::getSymbolVersion(const Elf_Sym &Sym,
742                                                       bool &IsDefault) const {
743   // This is a dynamic symbol. Look in the GNU symbol version table.
744   if (!SymbolVersionSection) {
745     // No version table.
746     IsDefault = false;
747     return "";
748   }
749 
750   assert(DynSymRegion && "DynSymRegion has not been initialised");
751   // Determine the position in the symbol table of this entry.
752   size_t EntryIndex = (reinterpret_cast<uintptr_t>(&Sym) -
753                        reinterpret_cast<uintptr_t>(DynSymRegion->Addr)) /
754                       sizeof(Elf_Sym);
755 
756   // Get the corresponding version index entry.
757   Expected<const Elf_Versym *> EntryOrErr =
758       Obj.template getEntry<Elf_Versym>(*SymbolVersionSection, EntryIndex);
759   if (!EntryOrErr)
760     return EntryOrErr.takeError();
761 
762   unsigned Version = (*EntryOrErr)->vs_index;
763   if (Version == VER_NDX_LOCAL || Version == VER_NDX_GLOBAL) {
764     IsDefault = false;
765     return "";
766   }
767 
768   Expected<SmallVector<Optional<VersionEntry>, 0> *> MapOrErr =
769       getVersionMap();
770   if (!MapOrErr)
771     return MapOrErr.takeError();
772 
773   return Obj.getSymbolVersionByIndex(Version, IsDefault, **MapOrErr,
774                                      Sym.st_shndx == ELF::SHN_UNDEF);
775 }
776 
777 template <typename ELFT>
778 Expected<RelSymbol<ELFT>>
779 ELFDumper<ELFT>::getRelocationTarget(const Relocation<ELFT> &R,
780                                      const Elf_Shdr *SymTab) const {
781   if (R.Symbol == 0)
782     return RelSymbol<ELFT>(nullptr, "");
783 
784   Expected<const Elf_Sym *> SymOrErr =
785       Obj.template getEntry<Elf_Sym>(*SymTab, R.Symbol);
786   if (!SymOrErr)
787     return createError("unable to read an entry with index " + Twine(R.Symbol) +
788                        " from " + describe(*SymTab) + ": " +
789                        toString(SymOrErr.takeError()));
790   const Elf_Sym *Sym = *SymOrErr;
791   if (!Sym)
792     return RelSymbol<ELFT>(nullptr, "");
793 
794   Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(*SymTab);
795   if (!StrTableOrErr)
796     return StrTableOrErr.takeError();
797 
798   const Elf_Sym *FirstSym =
799       cantFail(Obj.template getEntry<Elf_Sym>(*SymTab, 0));
800   std::string SymbolName =
801       getFullSymbolName(*Sym, Sym - FirstSym, getShndxTable(SymTab),
802                         *StrTableOrErr, SymTab->sh_type == SHT_DYNSYM);
803   return RelSymbol<ELFT>(Sym, SymbolName);
804 }
805 
806 template <typename ELFT>
807 ArrayRef<typename ELFT::Word>
808 ELFDumper<ELFT>::getShndxTable(const Elf_Shdr *Symtab) const {
809   if (Symtab) {
810     auto It = ShndxTables.find(Symtab);
811     if (It != ShndxTables.end())
812       return It->second;
813   }
814   return {};
815 }
816 
817 static std::string maybeDemangle(StringRef Name) {
818   return opts::Demangle ? demangle(std::string(Name)) : Name.str();
819 }
820 
821 template <typename ELFT>
822 std::string ELFDumper<ELFT>::getStaticSymbolName(uint32_t Index) const {
823   auto Warn = [&](Error E) -> std::string {
824     reportUniqueWarning("unable to read the name of symbol with index " +
825                         Twine(Index) + ": " + toString(std::move(E)));
826     return "<?>";
827   };
828 
829   Expected<const typename ELFT::Sym *> SymOrErr =
830       Obj.getSymbol(DotSymtabSec, Index);
831   if (!SymOrErr)
832     return Warn(SymOrErr.takeError());
833 
834   Expected<StringRef> StrTabOrErr = Obj.getStringTableForSymtab(*DotSymtabSec);
835   if (!StrTabOrErr)
836     return Warn(StrTabOrErr.takeError());
837 
838   Expected<StringRef> NameOrErr = (*SymOrErr)->getName(*StrTabOrErr);
839   if (!NameOrErr)
840     return Warn(NameOrErr.takeError());
841   return maybeDemangle(*NameOrErr);
842 }
843 
844 template <typename ELFT>
845 std::string ELFDumper<ELFT>::getFullSymbolName(const Elf_Sym &Symbol,
846                                                unsigned SymIndex,
847                                                DataRegion<Elf_Word> ShndxTable,
848                                                Optional<StringRef> StrTable,
849                                                bool IsDynamic) const {
850   if (!StrTable)
851     return "<?>";
852 
853   std::string SymbolName;
854   if (Expected<StringRef> NameOrErr = Symbol.getName(*StrTable)) {
855     SymbolName = maybeDemangle(*NameOrErr);
856   } else {
857     reportUniqueWarning(NameOrErr.takeError());
858     return "<?>";
859   }
860 
861   if (SymbolName.empty() && Symbol.getType() == ELF::STT_SECTION) {
862     Expected<unsigned> SectionIndex =
863         getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
864     if (!SectionIndex) {
865       reportUniqueWarning(SectionIndex.takeError());
866       return "<?>";
867     }
868     Expected<StringRef> NameOrErr = getSymbolSectionName(Symbol, *SectionIndex);
869     if (!NameOrErr) {
870       reportUniqueWarning(NameOrErr.takeError());
871       return ("<section " + Twine(*SectionIndex) + ">").str();
872     }
873     return std::string(*NameOrErr);
874   }
875 
876   if (!IsDynamic)
877     return SymbolName;
878 
879   bool IsDefault;
880   Expected<StringRef> VersionOrErr = getSymbolVersion(Symbol, IsDefault);
881   if (!VersionOrErr) {
882     reportUniqueWarning(VersionOrErr.takeError());
883     return SymbolName + "@<corrupt>";
884   }
885 
886   if (!VersionOrErr->empty()) {
887     SymbolName += (IsDefault ? "@@" : "@");
888     SymbolName += *VersionOrErr;
889   }
890   return SymbolName;
891 }
892 
893 template <typename ELFT>
894 Expected<unsigned>
895 ELFDumper<ELFT>::getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
896                                        DataRegion<Elf_Word> ShndxTable) const {
897   unsigned Ndx = Symbol.st_shndx;
898   if (Ndx == SHN_XINDEX)
899     return object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex,
900                                                      ShndxTable);
901   if (Ndx != SHN_UNDEF && Ndx < SHN_LORESERVE)
902     return Ndx;
903 
904   auto CreateErr = [&](const Twine &Name, Optional<unsigned> Offset = None) {
905     std::string Desc;
906     if (Offset)
907       Desc = (Name + "+0x" + Twine::utohexstr(*Offset)).str();
908     else
909       Desc = Name.str();
910     return createError(
911         "unable to get section index for symbol with st_shndx = 0x" +
912         Twine::utohexstr(Ndx) + " (" + Desc + ")");
913   };
914 
915   if (Ndx >= ELF::SHN_LOPROC && Ndx <= ELF::SHN_HIPROC)
916     return CreateErr("SHN_LOPROC", Ndx - ELF::SHN_LOPROC);
917   if (Ndx >= ELF::SHN_LOOS && Ndx <= ELF::SHN_HIOS)
918     return CreateErr("SHN_LOOS", Ndx - ELF::SHN_LOOS);
919   if (Ndx == ELF::SHN_UNDEF)
920     return CreateErr("SHN_UNDEF");
921   if (Ndx == ELF::SHN_ABS)
922     return CreateErr("SHN_ABS");
923   if (Ndx == ELF::SHN_COMMON)
924     return CreateErr("SHN_COMMON");
925   return CreateErr("SHN_LORESERVE", Ndx - SHN_LORESERVE);
926 }
927 
928 template <typename ELFT>
929 Expected<StringRef>
930 ELFDumper<ELFT>::getSymbolSectionName(const Elf_Sym &Symbol,
931                                       unsigned SectionIndex) const {
932   Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(SectionIndex);
933   if (!SecOrErr)
934     return SecOrErr.takeError();
935   return Obj.getSectionName(**SecOrErr);
936 }
937 
938 template <class ELFO>
939 static const typename ELFO::Elf_Shdr *
940 findNotEmptySectionByAddress(const ELFO &Obj, StringRef FileName,
941                              uint64_t Addr) {
942   for (const typename ELFO::Elf_Shdr &Shdr : cantFail(Obj.sections()))
943     if (Shdr.sh_addr == Addr && Shdr.sh_size > 0)
944       return &Shdr;
945   return nullptr;
946 }
947 
948 static const EnumEntry<unsigned> ElfClass[] = {
949   {"None",   "none",   ELF::ELFCLASSNONE},
950   {"32-bit", "ELF32",  ELF::ELFCLASS32},
951   {"64-bit", "ELF64",  ELF::ELFCLASS64},
952 };
953 
954 static const EnumEntry<unsigned> ElfDataEncoding[] = {
955   {"None",         "none",                          ELF::ELFDATANONE},
956   {"LittleEndian", "2's complement, little endian", ELF::ELFDATA2LSB},
957   {"BigEndian",    "2's complement, big endian",    ELF::ELFDATA2MSB},
958 };
959 
960 static const EnumEntry<unsigned> ElfObjectFileType[] = {
961   {"None",         "NONE (none)",              ELF::ET_NONE},
962   {"Relocatable",  "REL (Relocatable file)",   ELF::ET_REL},
963   {"Executable",   "EXEC (Executable file)",   ELF::ET_EXEC},
964   {"SharedObject", "DYN (Shared object file)", ELF::ET_DYN},
965   {"Core",         "CORE (Core file)",         ELF::ET_CORE},
966 };
967 
968 static const EnumEntry<unsigned> ElfOSABI[] = {
969   {"SystemV",      "UNIX - System V",      ELF::ELFOSABI_NONE},
970   {"HPUX",         "UNIX - HP-UX",         ELF::ELFOSABI_HPUX},
971   {"NetBSD",       "UNIX - NetBSD",        ELF::ELFOSABI_NETBSD},
972   {"GNU/Linux",    "UNIX - GNU",           ELF::ELFOSABI_LINUX},
973   {"GNU/Hurd",     "GNU/Hurd",             ELF::ELFOSABI_HURD},
974   {"Solaris",      "UNIX - Solaris",       ELF::ELFOSABI_SOLARIS},
975   {"AIX",          "UNIX - AIX",           ELF::ELFOSABI_AIX},
976   {"IRIX",         "UNIX - IRIX",          ELF::ELFOSABI_IRIX},
977   {"FreeBSD",      "UNIX - FreeBSD",       ELF::ELFOSABI_FREEBSD},
978   {"TRU64",        "UNIX - TRU64",         ELF::ELFOSABI_TRU64},
979   {"Modesto",      "Novell - Modesto",     ELF::ELFOSABI_MODESTO},
980   {"OpenBSD",      "UNIX - OpenBSD",       ELF::ELFOSABI_OPENBSD},
981   {"OpenVMS",      "VMS - OpenVMS",        ELF::ELFOSABI_OPENVMS},
982   {"NSK",          "HP - Non-Stop Kernel", ELF::ELFOSABI_NSK},
983   {"AROS",         "AROS",                 ELF::ELFOSABI_AROS},
984   {"FenixOS",      "FenixOS",              ELF::ELFOSABI_FENIXOS},
985   {"CloudABI",     "CloudABI",             ELF::ELFOSABI_CLOUDABI},
986   {"Standalone",   "Standalone App",       ELF::ELFOSABI_STANDALONE}
987 };
988 
989 static const EnumEntry<unsigned> AMDGPUElfOSABI[] = {
990   {"AMDGPU_HSA",    "AMDGPU - HSA",    ELF::ELFOSABI_AMDGPU_HSA},
991   {"AMDGPU_PAL",    "AMDGPU - PAL",    ELF::ELFOSABI_AMDGPU_PAL},
992   {"AMDGPU_MESA3D", "AMDGPU - MESA3D", ELF::ELFOSABI_AMDGPU_MESA3D}
993 };
994 
995 static const EnumEntry<unsigned> ARMElfOSABI[] = {
996   {"ARM", "ARM", ELF::ELFOSABI_ARM}
997 };
998 
999 static const EnumEntry<unsigned> C6000ElfOSABI[] = {
1000   {"C6000_ELFABI", "Bare-metal C6000", ELF::ELFOSABI_C6000_ELFABI},
1001   {"C6000_LINUX",  "Linux C6000",      ELF::ELFOSABI_C6000_LINUX}
1002 };
1003 
1004 static const EnumEntry<unsigned> ElfMachineType[] = {
1005   ENUM_ENT(EM_NONE,          "None"),
1006   ENUM_ENT(EM_M32,           "WE32100"),
1007   ENUM_ENT(EM_SPARC,         "Sparc"),
1008   ENUM_ENT(EM_386,           "Intel 80386"),
1009   ENUM_ENT(EM_68K,           "MC68000"),
1010   ENUM_ENT(EM_88K,           "MC88000"),
1011   ENUM_ENT(EM_IAMCU,         "EM_IAMCU"),
1012   ENUM_ENT(EM_860,           "Intel 80860"),
1013   ENUM_ENT(EM_MIPS,          "MIPS R3000"),
1014   ENUM_ENT(EM_S370,          "IBM System/370"),
1015   ENUM_ENT(EM_MIPS_RS3_LE,   "MIPS R3000 little-endian"),
1016   ENUM_ENT(EM_PARISC,        "HPPA"),
1017   ENUM_ENT(EM_VPP500,        "Fujitsu VPP500"),
1018   ENUM_ENT(EM_SPARC32PLUS,   "Sparc v8+"),
1019   ENUM_ENT(EM_960,           "Intel 80960"),
1020   ENUM_ENT(EM_PPC,           "PowerPC"),
1021   ENUM_ENT(EM_PPC64,         "PowerPC64"),
1022   ENUM_ENT(EM_S390,          "IBM S/390"),
1023   ENUM_ENT(EM_SPU,           "SPU"),
1024   ENUM_ENT(EM_V800,          "NEC V800 series"),
1025   ENUM_ENT(EM_FR20,          "Fujistsu FR20"),
1026   ENUM_ENT(EM_RH32,          "TRW RH-32"),
1027   ENUM_ENT(EM_RCE,           "Motorola RCE"),
1028   ENUM_ENT(EM_ARM,           "ARM"),
1029   ENUM_ENT(EM_ALPHA,         "EM_ALPHA"),
1030   ENUM_ENT(EM_SH,            "Hitachi SH"),
1031   ENUM_ENT(EM_SPARCV9,       "Sparc v9"),
1032   ENUM_ENT(EM_TRICORE,       "Siemens Tricore"),
1033   ENUM_ENT(EM_ARC,           "ARC"),
1034   ENUM_ENT(EM_H8_300,        "Hitachi H8/300"),
1035   ENUM_ENT(EM_H8_300H,       "Hitachi H8/300H"),
1036   ENUM_ENT(EM_H8S,           "Hitachi H8S"),
1037   ENUM_ENT(EM_H8_500,        "Hitachi H8/500"),
1038   ENUM_ENT(EM_IA_64,         "Intel IA-64"),
1039   ENUM_ENT(EM_MIPS_X,        "Stanford MIPS-X"),
1040   ENUM_ENT(EM_COLDFIRE,      "Motorola Coldfire"),
1041   ENUM_ENT(EM_68HC12,        "Motorola MC68HC12 Microcontroller"),
1042   ENUM_ENT(EM_MMA,           "Fujitsu Multimedia Accelerator"),
1043   ENUM_ENT(EM_PCP,           "Siemens PCP"),
1044   ENUM_ENT(EM_NCPU,          "Sony nCPU embedded RISC processor"),
1045   ENUM_ENT(EM_NDR1,          "Denso NDR1 microprocesspr"),
1046   ENUM_ENT(EM_STARCORE,      "Motorola Star*Core processor"),
1047   ENUM_ENT(EM_ME16,          "Toyota ME16 processor"),
1048   ENUM_ENT(EM_ST100,         "STMicroelectronics ST100 processor"),
1049   ENUM_ENT(EM_TINYJ,         "Advanced Logic Corp. TinyJ embedded processor"),
1050   ENUM_ENT(EM_X86_64,        "Advanced Micro Devices X86-64"),
1051   ENUM_ENT(EM_PDSP,          "Sony DSP processor"),
1052   ENUM_ENT(EM_PDP10,         "Digital Equipment Corp. PDP-10"),
1053   ENUM_ENT(EM_PDP11,         "Digital Equipment Corp. PDP-11"),
1054   ENUM_ENT(EM_FX66,          "Siemens FX66 microcontroller"),
1055   ENUM_ENT(EM_ST9PLUS,       "STMicroelectronics ST9+ 8/16 bit microcontroller"),
1056   ENUM_ENT(EM_ST7,           "STMicroelectronics ST7 8-bit microcontroller"),
1057   ENUM_ENT(EM_68HC16,        "Motorola MC68HC16 Microcontroller"),
1058   ENUM_ENT(EM_68HC11,        "Motorola MC68HC11 Microcontroller"),
1059   ENUM_ENT(EM_68HC08,        "Motorola MC68HC08 Microcontroller"),
1060   ENUM_ENT(EM_68HC05,        "Motorola MC68HC05 Microcontroller"),
1061   ENUM_ENT(EM_SVX,           "Silicon Graphics SVx"),
1062   ENUM_ENT(EM_ST19,          "STMicroelectronics ST19 8-bit microcontroller"),
1063   ENUM_ENT(EM_VAX,           "Digital VAX"),
1064   ENUM_ENT(EM_CRIS,          "Axis Communications 32-bit embedded processor"),
1065   ENUM_ENT(EM_JAVELIN,       "Infineon Technologies 32-bit embedded cpu"),
1066   ENUM_ENT(EM_FIREPATH,      "Element 14 64-bit DSP processor"),
1067   ENUM_ENT(EM_ZSP,           "LSI Logic's 16-bit DSP processor"),
1068   ENUM_ENT(EM_MMIX,          "Donald Knuth's educational 64-bit processor"),
1069   ENUM_ENT(EM_HUANY,         "Harvard Universitys's machine-independent object format"),
1070   ENUM_ENT(EM_PRISM,         "Vitesse Prism"),
1071   ENUM_ENT(EM_AVR,           "Atmel AVR 8-bit microcontroller"),
1072   ENUM_ENT(EM_FR30,          "Fujitsu FR30"),
1073   ENUM_ENT(EM_D10V,          "Mitsubishi D10V"),
1074   ENUM_ENT(EM_D30V,          "Mitsubishi D30V"),
1075   ENUM_ENT(EM_V850,          "NEC v850"),
1076   ENUM_ENT(EM_M32R,          "Renesas M32R (formerly Mitsubishi M32r)"),
1077   ENUM_ENT(EM_MN10300,       "Matsushita MN10300"),
1078   ENUM_ENT(EM_MN10200,       "Matsushita MN10200"),
1079   ENUM_ENT(EM_PJ,            "picoJava"),
1080   ENUM_ENT(EM_OPENRISC,      "OpenRISC 32-bit embedded processor"),
1081   ENUM_ENT(EM_ARC_COMPACT,   "EM_ARC_COMPACT"),
1082   ENUM_ENT(EM_XTENSA,        "Tensilica Xtensa Processor"),
1083   ENUM_ENT(EM_VIDEOCORE,     "Alphamosaic VideoCore processor"),
1084   ENUM_ENT(EM_TMM_GPP,       "Thompson Multimedia General Purpose Processor"),
1085   ENUM_ENT(EM_NS32K,         "National Semiconductor 32000 series"),
1086   ENUM_ENT(EM_TPC,           "Tenor Network TPC processor"),
1087   ENUM_ENT(EM_SNP1K,         "EM_SNP1K"),
1088   ENUM_ENT(EM_ST200,         "STMicroelectronics ST200 microcontroller"),
1089   ENUM_ENT(EM_IP2K,          "Ubicom IP2xxx 8-bit microcontrollers"),
1090   ENUM_ENT(EM_MAX,           "MAX Processor"),
1091   ENUM_ENT(EM_CR,            "National Semiconductor CompactRISC"),
1092   ENUM_ENT(EM_F2MC16,        "Fujitsu F2MC16"),
1093   ENUM_ENT(EM_MSP430,        "Texas Instruments msp430 microcontroller"),
1094   ENUM_ENT(EM_BLACKFIN,      "Analog Devices Blackfin"),
1095   ENUM_ENT(EM_SE_C33,        "S1C33 Family of Seiko Epson processors"),
1096   ENUM_ENT(EM_SEP,           "Sharp embedded microprocessor"),
1097   ENUM_ENT(EM_ARCA,          "Arca RISC microprocessor"),
1098   ENUM_ENT(EM_UNICORE,       "Unicore"),
1099   ENUM_ENT(EM_EXCESS,        "eXcess 16/32/64-bit configurable embedded CPU"),
1100   ENUM_ENT(EM_DXP,           "Icera Semiconductor Inc. Deep Execution Processor"),
1101   ENUM_ENT(EM_ALTERA_NIOS2,  "Altera Nios"),
1102   ENUM_ENT(EM_CRX,           "National Semiconductor CRX microprocessor"),
1103   ENUM_ENT(EM_XGATE,         "Motorola XGATE embedded processor"),
1104   ENUM_ENT(EM_C166,          "Infineon Technologies xc16x"),
1105   ENUM_ENT(EM_M16C,          "Renesas M16C"),
1106   ENUM_ENT(EM_DSPIC30F,      "Microchip Technology dsPIC30F Digital Signal Controller"),
1107   ENUM_ENT(EM_CE,            "Freescale Communication Engine RISC core"),
1108   ENUM_ENT(EM_M32C,          "Renesas M32C"),
1109   ENUM_ENT(EM_TSK3000,       "Altium TSK3000 core"),
1110   ENUM_ENT(EM_RS08,          "Freescale RS08 embedded processor"),
1111   ENUM_ENT(EM_SHARC,         "EM_SHARC"),
1112   ENUM_ENT(EM_ECOG2,         "Cyan Technology eCOG2 microprocessor"),
1113   ENUM_ENT(EM_SCORE7,        "SUNPLUS S+Core"),
1114   ENUM_ENT(EM_DSP24,         "New Japan Radio (NJR) 24-bit DSP Processor"),
1115   ENUM_ENT(EM_VIDEOCORE3,    "Broadcom VideoCore III processor"),
1116   ENUM_ENT(EM_LATTICEMICO32, "Lattice Mico32"),
1117   ENUM_ENT(EM_SE_C17,        "Seiko Epson C17 family"),
1118   ENUM_ENT(EM_TI_C6000,      "Texas Instruments TMS320C6000 DSP family"),
1119   ENUM_ENT(EM_TI_C2000,      "Texas Instruments TMS320C2000 DSP family"),
1120   ENUM_ENT(EM_TI_C5500,      "Texas Instruments TMS320C55x DSP family"),
1121   ENUM_ENT(EM_MMDSP_PLUS,    "STMicroelectronics 64bit VLIW Data Signal Processor"),
1122   ENUM_ENT(EM_CYPRESS_M8C,   "Cypress M8C microprocessor"),
1123   ENUM_ENT(EM_R32C,          "Renesas R32C series microprocessors"),
1124   ENUM_ENT(EM_TRIMEDIA,      "NXP Semiconductors TriMedia architecture family"),
1125   ENUM_ENT(EM_HEXAGON,       "Qualcomm Hexagon"),
1126   ENUM_ENT(EM_8051,          "Intel 8051 and variants"),
1127   ENUM_ENT(EM_STXP7X,        "STMicroelectronics STxP7x family"),
1128   ENUM_ENT(EM_NDS32,         "Andes Technology compact code size embedded RISC processor family"),
1129   ENUM_ENT(EM_ECOG1,         "Cyan Technology eCOG1 microprocessor"),
1130   // FIXME: Following EM_ECOG1X definitions is dead code since EM_ECOG1X has
1131   //        an identical number to EM_ECOG1.
1132   ENUM_ENT(EM_ECOG1X,        "Cyan Technology eCOG1X family"),
1133   ENUM_ENT(EM_MAXQ30,        "Dallas Semiconductor MAXQ30 Core microcontrollers"),
1134   ENUM_ENT(EM_XIMO16,        "New Japan Radio (NJR) 16-bit DSP Processor"),
1135   ENUM_ENT(EM_MANIK,         "M2000 Reconfigurable RISC Microprocessor"),
1136   ENUM_ENT(EM_CRAYNV2,       "Cray Inc. NV2 vector architecture"),
1137   ENUM_ENT(EM_RX,            "Renesas RX"),
1138   ENUM_ENT(EM_METAG,         "Imagination Technologies Meta processor architecture"),
1139   ENUM_ENT(EM_MCST_ELBRUS,   "MCST Elbrus general purpose hardware architecture"),
1140   ENUM_ENT(EM_ECOG16,        "Cyan Technology eCOG16 family"),
1141   ENUM_ENT(EM_CR16,          "Xilinx MicroBlaze"),
1142   ENUM_ENT(EM_ETPU,          "Freescale Extended Time Processing Unit"),
1143   ENUM_ENT(EM_SLE9X,         "Infineon Technologies SLE9X core"),
1144   ENUM_ENT(EM_L10M,          "EM_L10M"),
1145   ENUM_ENT(EM_K10M,          "EM_K10M"),
1146   ENUM_ENT(EM_AARCH64,       "AArch64"),
1147   ENUM_ENT(EM_AVR32,         "Atmel Corporation 32-bit microprocessor family"),
1148   ENUM_ENT(EM_STM8,          "STMicroeletronics STM8 8-bit microcontroller"),
1149   ENUM_ENT(EM_TILE64,        "Tilera TILE64 multicore architecture family"),
1150   ENUM_ENT(EM_TILEPRO,       "Tilera TILEPro multicore architecture family"),
1151   ENUM_ENT(EM_CUDA,          "NVIDIA CUDA architecture"),
1152   ENUM_ENT(EM_TILEGX,        "Tilera TILE-Gx multicore architecture family"),
1153   ENUM_ENT(EM_CLOUDSHIELD,   "EM_CLOUDSHIELD"),
1154   ENUM_ENT(EM_COREA_1ST,     "EM_COREA_1ST"),
1155   ENUM_ENT(EM_COREA_2ND,     "EM_COREA_2ND"),
1156   ENUM_ENT(EM_ARC_COMPACT2,  "EM_ARC_COMPACT2"),
1157   ENUM_ENT(EM_OPEN8,         "EM_OPEN8"),
1158   ENUM_ENT(EM_RL78,          "Renesas RL78"),
1159   ENUM_ENT(EM_VIDEOCORE5,    "Broadcom VideoCore V processor"),
1160   ENUM_ENT(EM_78KOR,         "EM_78KOR"),
1161   ENUM_ENT(EM_56800EX,       "EM_56800EX"),
1162   ENUM_ENT(EM_AMDGPU,        "EM_AMDGPU"),
1163   ENUM_ENT(EM_RISCV,         "RISC-V"),
1164   ENUM_ENT(EM_LANAI,         "EM_LANAI"),
1165   ENUM_ENT(EM_BPF,           "EM_BPF"),
1166   ENUM_ENT(EM_VE,            "NEC SX-Aurora Vector Engine"),
1167 };
1168 
1169 static const EnumEntry<unsigned> ElfSymbolBindings[] = {
1170     {"Local",  "LOCAL",  ELF::STB_LOCAL},
1171     {"Global", "GLOBAL", ELF::STB_GLOBAL},
1172     {"Weak",   "WEAK",   ELF::STB_WEAK},
1173     {"Unique", "UNIQUE", ELF::STB_GNU_UNIQUE}};
1174 
1175 static const EnumEntry<unsigned> ElfSymbolVisibilities[] = {
1176     {"DEFAULT",   "DEFAULT",   ELF::STV_DEFAULT},
1177     {"INTERNAL",  "INTERNAL",  ELF::STV_INTERNAL},
1178     {"HIDDEN",    "HIDDEN",    ELF::STV_HIDDEN},
1179     {"PROTECTED", "PROTECTED", ELF::STV_PROTECTED}};
1180 
1181 static const EnumEntry<unsigned> AMDGPUSymbolTypes[] = {
1182   { "AMDGPU_HSA_KERNEL",            ELF::STT_AMDGPU_HSA_KERNEL }
1183 };
1184 
1185 static const char *getGroupType(uint32_t Flag) {
1186   if (Flag & ELF::GRP_COMDAT)
1187     return "COMDAT";
1188   else
1189     return "(unknown)";
1190 }
1191 
1192 static const EnumEntry<unsigned> ElfSectionFlags[] = {
1193   ENUM_ENT(SHF_WRITE,            "W"),
1194   ENUM_ENT(SHF_ALLOC,            "A"),
1195   ENUM_ENT(SHF_EXECINSTR,        "X"),
1196   ENUM_ENT(SHF_MERGE,            "M"),
1197   ENUM_ENT(SHF_STRINGS,          "S"),
1198   ENUM_ENT(SHF_INFO_LINK,        "I"),
1199   ENUM_ENT(SHF_LINK_ORDER,       "L"),
1200   ENUM_ENT(SHF_OS_NONCONFORMING, "O"),
1201   ENUM_ENT(SHF_GROUP,            "G"),
1202   ENUM_ENT(SHF_TLS,              "T"),
1203   ENUM_ENT(SHF_COMPRESSED,       "C"),
1204   ENUM_ENT(SHF_EXCLUDE,          "E"),
1205 };
1206 
1207 static const EnumEntry<unsigned> ElfXCoreSectionFlags[] = {
1208   ENUM_ENT(XCORE_SHF_CP_SECTION, ""),
1209   ENUM_ENT(XCORE_SHF_DP_SECTION, "")
1210 };
1211 
1212 static const EnumEntry<unsigned> ElfARMSectionFlags[] = {
1213   ENUM_ENT(SHF_ARM_PURECODE, "y")
1214 };
1215 
1216 static const EnumEntry<unsigned> ElfHexagonSectionFlags[] = {
1217   ENUM_ENT(SHF_HEX_GPREL, "")
1218 };
1219 
1220 static const EnumEntry<unsigned> ElfMipsSectionFlags[] = {
1221   ENUM_ENT(SHF_MIPS_NODUPES, ""),
1222   ENUM_ENT(SHF_MIPS_NAMES,   ""),
1223   ENUM_ENT(SHF_MIPS_LOCAL,   ""),
1224   ENUM_ENT(SHF_MIPS_NOSTRIP, ""),
1225   ENUM_ENT(SHF_MIPS_GPREL,   ""),
1226   ENUM_ENT(SHF_MIPS_MERGE,   ""),
1227   ENUM_ENT(SHF_MIPS_ADDR,    ""),
1228   ENUM_ENT(SHF_MIPS_STRING,  "")
1229 };
1230 
1231 static const EnumEntry<unsigned> ElfX86_64SectionFlags[] = {
1232   ENUM_ENT(SHF_X86_64_LARGE, "l")
1233 };
1234 
1235 static std::vector<EnumEntry<unsigned>>
1236 getSectionFlagsForTarget(unsigned EMachine) {
1237   std::vector<EnumEntry<unsigned>> Ret(std::begin(ElfSectionFlags),
1238                                        std::end(ElfSectionFlags));
1239   switch (EMachine) {
1240   case EM_ARM:
1241     Ret.insert(Ret.end(), std::begin(ElfARMSectionFlags),
1242                std::end(ElfARMSectionFlags));
1243     break;
1244   case EM_HEXAGON:
1245     Ret.insert(Ret.end(), std::begin(ElfHexagonSectionFlags),
1246                std::end(ElfHexagonSectionFlags));
1247     break;
1248   case EM_MIPS:
1249     Ret.insert(Ret.end(), std::begin(ElfMipsSectionFlags),
1250                std::end(ElfMipsSectionFlags));
1251     break;
1252   case EM_X86_64:
1253     Ret.insert(Ret.end(), std::begin(ElfX86_64SectionFlags),
1254                std::end(ElfX86_64SectionFlags));
1255     break;
1256   case EM_XCORE:
1257     Ret.insert(Ret.end(), std::begin(ElfXCoreSectionFlags),
1258                std::end(ElfXCoreSectionFlags));
1259     break;
1260   default:
1261     break;
1262   }
1263   return Ret;
1264 }
1265 
1266 static std::string getGNUFlags(unsigned EMachine, uint64_t Flags) {
1267   // Here we are trying to build the flags string in the same way as GNU does.
1268   // It is not that straightforward. Imagine we have sh_flags == 0x90000000.
1269   // SHF_EXCLUDE ("E") has a value of 0x80000000 and SHF_MASKPROC is 0xf0000000.
1270   // GNU readelf will not print "E" or "Ep" in this case, but will print just
1271   // "p". It only will print "E" when no other processor flag is set.
1272   std::string Str;
1273   bool HasUnknownFlag = false;
1274   bool HasOSFlag = false;
1275   bool HasProcFlag = false;
1276   std::vector<EnumEntry<unsigned>> FlagsList =
1277       getSectionFlagsForTarget(EMachine);
1278   while (Flags) {
1279     // Take the least significant bit as a flag.
1280     uint64_t Flag = Flags & -Flags;
1281     Flags -= Flag;
1282 
1283     // Find the flag in the known flags list.
1284     auto I = llvm::find_if(FlagsList, [=](const EnumEntry<unsigned> &E) {
1285       // Flags with empty names are not printed in GNU style output.
1286       return E.Value == Flag && !E.AltName.empty();
1287     });
1288     if (I != FlagsList.end()) {
1289       Str += I->AltName;
1290       continue;
1291     }
1292 
1293     // If we did not find a matching regular flag, then we deal with an OS
1294     // specific flag, processor specific flag or an unknown flag.
1295     if (Flag & ELF::SHF_MASKOS) {
1296       HasOSFlag = true;
1297       Flags &= ~ELF::SHF_MASKOS;
1298     } else if (Flag & ELF::SHF_MASKPROC) {
1299       HasProcFlag = true;
1300       // Mask off all the processor-specific bits. This removes the SHF_EXCLUDE
1301       // bit if set so that it doesn't also get printed.
1302       Flags &= ~ELF::SHF_MASKPROC;
1303     } else {
1304       HasUnknownFlag = true;
1305     }
1306   }
1307 
1308   // "o", "p" and "x" are printed last.
1309   if (HasOSFlag)
1310     Str += "o";
1311   if (HasProcFlag)
1312     Str += "p";
1313   if (HasUnknownFlag)
1314     Str += "x";
1315   return Str;
1316 }
1317 
1318 static StringRef segmentTypeToString(unsigned Arch, unsigned Type) {
1319   // Check potentially overlapped processor-specific program header type.
1320   switch (Arch) {
1321   case ELF::EM_ARM:
1322     switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_ARM_EXIDX); }
1323     break;
1324   case ELF::EM_MIPS:
1325   case ELF::EM_MIPS_RS3_LE:
1326     switch (Type) {
1327       LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_REGINFO);
1328       LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_RTPROC);
1329       LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_OPTIONS);
1330       LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_ABIFLAGS);
1331     }
1332     break;
1333   }
1334 
1335   switch (Type) {
1336     LLVM_READOBJ_ENUM_CASE(ELF, PT_NULL);
1337     LLVM_READOBJ_ENUM_CASE(ELF, PT_LOAD);
1338     LLVM_READOBJ_ENUM_CASE(ELF, PT_DYNAMIC);
1339     LLVM_READOBJ_ENUM_CASE(ELF, PT_INTERP);
1340     LLVM_READOBJ_ENUM_CASE(ELF, PT_NOTE);
1341     LLVM_READOBJ_ENUM_CASE(ELF, PT_SHLIB);
1342     LLVM_READOBJ_ENUM_CASE(ELF, PT_PHDR);
1343     LLVM_READOBJ_ENUM_CASE(ELF, PT_TLS);
1344 
1345     LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_EH_FRAME);
1346     LLVM_READOBJ_ENUM_CASE(ELF, PT_SUNW_UNWIND);
1347 
1348     LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_STACK);
1349     LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_RELRO);
1350     LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_PROPERTY);
1351 
1352     LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_RANDOMIZE);
1353     LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_WXNEEDED);
1354     LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_BOOTDATA);
1355   default:
1356     return "";
1357   }
1358 }
1359 
1360 static std::string getGNUPtType(unsigned Arch, unsigned Type) {
1361   StringRef Seg = segmentTypeToString(Arch, Type);
1362   if (Seg.empty())
1363     return std::string("<unknown>: ") + to_string(format_hex(Type, 1));
1364 
1365   // E.g. "PT_ARM_EXIDX" -> "EXIDX".
1366   if (Seg.startswith("PT_ARM_"))
1367     return Seg.drop_front(7).str();
1368 
1369   // E.g. "PT_MIPS_REGINFO" -> "REGINFO".
1370   if (Seg.startswith("PT_MIPS_"))
1371     return Seg.drop_front(8).str();
1372 
1373   // E.g. "PT_LOAD" -> "LOAD".
1374   assert(Seg.startswith("PT_"));
1375   return Seg.drop_front(3).str();
1376 }
1377 
1378 static const EnumEntry<unsigned> ElfSegmentFlags[] = {
1379   LLVM_READOBJ_ENUM_ENT(ELF, PF_X),
1380   LLVM_READOBJ_ENUM_ENT(ELF, PF_W),
1381   LLVM_READOBJ_ENUM_ENT(ELF, PF_R)
1382 };
1383 
1384 static const EnumEntry<unsigned> ElfHeaderMipsFlags[] = {
1385   ENUM_ENT(EF_MIPS_NOREORDER, "noreorder"),
1386   ENUM_ENT(EF_MIPS_PIC, "pic"),
1387   ENUM_ENT(EF_MIPS_CPIC, "cpic"),
1388   ENUM_ENT(EF_MIPS_ABI2, "abi2"),
1389   ENUM_ENT(EF_MIPS_32BITMODE, "32bitmode"),
1390   ENUM_ENT(EF_MIPS_FP64, "fp64"),
1391   ENUM_ENT(EF_MIPS_NAN2008, "nan2008"),
1392   ENUM_ENT(EF_MIPS_ABI_O32, "o32"),
1393   ENUM_ENT(EF_MIPS_ABI_O64, "o64"),
1394   ENUM_ENT(EF_MIPS_ABI_EABI32, "eabi32"),
1395   ENUM_ENT(EF_MIPS_ABI_EABI64, "eabi64"),
1396   ENUM_ENT(EF_MIPS_MACH_3900, "3900"),
1397   ENUM_ENT(EF_MIPS_MACH_4010, "4010"),
1398   ENUM_ENT(EF_MIPS_MACH_4100, "4100"),
1399   ENUM_ENT(EF_MIPS_MACH_4650, "4650"),
1400   ENUM_ENT(EF_MIPS_MACH_4120, "4120"),
1401   ENUM_ENT(EF_MIPS_MACH_4111, "4111"),
1402   ENUM_ENT(EF_MIPS_MACH_SB1, "sb1"),
1403   ENUM_ENT(EF_MIPS_MACH_OCTEON, "octeon"),
1404   ENUM_ENT(EF_MIPS_MACH_XLR, "xlr"),
1405   ENUM_ENT(EF_MIPS_MACH_OCTEON2, "octeon2"),
1406   ENUM_ENT(EF_MIPS_MACH_OCTEON3, "octeon3"),
1407   ENUM_ENT(EF_MIPS_MACH_5400, "5400"),
1408   ENUM_ENT(EF_MIPS_MACH_5900, "5900"),
1409   ENUM_ENT(EF_MIPS_MACH_5500, "5500"),
1410   ENUM_ENT(EF_MIPS_MACH_9000, "9000"),
1411   ENUM_ENT(EF_MIPS_MACH_LS2E, "loongson-2e"),
1412   ENUM_ENT(EF_MIPS_MACH_LS2F, "loongson-2f"),
1413   ENUM_ENT(EF_MIPS_MACH_LS3A, "loongson-3a"),
1414   ENUM_ENT(EF_MIPS_MICROMIPS, "micromips"),
1415   ENUM_ENT(EF_MIPS_ARCH_ASE_M16, "mips16"),
1416   ENUM_ENT(EF_MIPS_ARCH_ASE_MDMX, "mdmx"),
1417   ENUM_ENT(EF_MIPS_ARCH_1, "mips1"),
1418   ENUM_ENT(EF_MIPS_ARCH_2, "mips2"),
1419   ENUM_ENT(EF_MIPS_ARCH_3, "mips3"),
1420   ENUM_ENT(EF_MIPS_ARCH_4, "mips4"),
1421   ENUM_ENT(EF_MIPS_ARCH_5, "mips5"),
1422   ENUM_ENT(EF_MIPS_ARCH_32, "mips32"),
1423   ENUM_ENT(EF_MIPS_ARCH_64, "mips64"),
1424   ENUM_ENT(EF_MIPS_ARCH_32R2, "mips32r2"),
1425   ENUM_ENT(EF_MIPS_ARCH_64R2, "mips64r2"),
1426   ENUM_ENT(EF_MIPS_ARCH_32R6, "mips32r6"),
1427   ENUM_ENT(EF_MIPS_ARCH_64R6, "mips64r6")
1428 };
1429 
1430 static const EnumEntry<unsigned> ElfHeaderAMDGPUFlags[] = {
1431   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_NONE),
1432   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R600),
1433   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R630),
1434   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RS880),
1435   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV670),
1436   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV710),
1437   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV730),
1438   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV770),
1439   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CEDAR),
1440   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CYPRESS),
1441   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_JUNIPER),
1442   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_REDWOOD),
1443   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_SUMO),
1444   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_BARTS),
1445   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAICOS),
1446   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAYMAN),
1447   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_TURKS),
1448   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX600),
1449   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX601),
1450   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX602),
1451   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX700),
1452   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX701),
1453   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX702),
1454   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX703),
1455   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX704),
1456   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX705),
1457   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX801),
1458   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX802),
1459   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX803),
1460   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX805),
1461   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX810),
1462   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX900),
1463   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX902),
1464   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX904),
1465   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX906),
1466   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX908),
1467   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX909),
1468   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX90C),
1469   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1010),
1470   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1011),
1471   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1012),
1472   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1030),
1473   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1031),
1474   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1032),
1475   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1033),
1476   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_XNACK),
1477   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_SRAM_ECC)
1478 };
1479 
1480 static const EnumEntry<unsigned> ElfHeaderRISCVFlags[] = {
1481   ENUM_ENT(EF_RISCV_RVC, "RVC"),
1482   ENUM_ENT(EF_RISCV_FLOAT_ABI_SINGLE, "single-float ABI"),
1483   ENUM_ENT(EF_RISCV_FLOAT_ABI_DOUBLE, "double-float ABI"),
1484   ENUM_ENT(EF_RISCV_FLOAT_ABI_QUAD, "quad-float ABI"),
1485   ENUM_ENT(EF_RISCV_RVE, "RVE")
1486 };
1487 
1488 static const EnumEntry<unsigned> ElfSymOtherFlags[] = {
1489   LLVM_READOBJ_ENUM_ENT(ELF, STV_INTERNAL),
1490   LLVM_READOBJ_ENUM_ENT(ELF, STV_HIDDEN),
1491   LLVM_READOBJ_ENUM_ENT(ELF, STV_PROTECTED)
1492 };
1493 
1494 static const EnumEntry<unsigned> ElfMipsSymOtherFlags[] = {
1495   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL),
1496   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT),
1497   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PIC),
1498   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MICROMIPS)
1499 };
1500 
1501 static const EnumEntry<unsigned> ElfAArch64SymOtherFlags[] = {
1502   LLVM_READOBJ_ENUM_ENT(ELF, STO_AARCH64_VARIANT_PCS)
1503 };
1504 
1505 static const EnumEntry<unsigned> ElfMips16SymOtherFlags[] = {
1506   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL),
1507   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT),
1508   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MIPS16)
1509 };
1510 
1511 static const char *getElfMipsOptionsOdkType(unsigned Odk) {
1512   switch (Odk) {
1513   LLVM_READOBJ_ENUM_CASE(ELF, ODK_NULL);
1514   LLVM_READOBJ_ENUM_CASE(ELF, ODK_REGINFO);
1515   LLVM_READOBJ_ENUM_CASE(ELF, ODK_EXCEPTIONS);
1516   LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAD);
1517   LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWPATCH);
1518   LLVM_READOBJ_ENUM_CASE(ELF, ODK_FILL);
1519   LLVM_READOBJ_ENUM_CASE(ELF, ODK_TAGS);
1520   LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWAND);
1521   LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWOR);
1522   LLVM_READOBJ_ENUM_CASE(ELF, ODK_GP_GROUP);
1523   LLVM_READOBJ_ENUM_CASE(ELF, ODK_IDENT);
1524   LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAGESIZE);
1525   default:
1526     return "Unknown";
1527   }
1528 }
1529 
1530 template <typename ELFT>
1531 std::pair<const typename ELFT::Phdr *, const typename ELFT::Shdr *>
1532 ELFDumper<ELFT>::findDynamic() {
1533   // Try to locate the PT_DYNAMIC header.
1534   const Elf_Phdr *DynamicPhdr = nullptr;
1535   if (Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = Obj.program_headers()) {
1536     for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
1537       if (Phdr.p_type != ELF::PT_DYNAMIC)
1538         continue;
1539       DynamicPhdr = &Phdr;
1540       break;
1541     }
1542   } else {
1543     reportUniqueWarning(
1544         "unable to read program headers to locate the PT_DYNAMIC segment: " +
1545         toString(PhdrsOrErr.takeError()));
1546   }
1547 
1548   // Try to locate the .dynamic section in the sections header table.
1549   const Elf_Shdr *DynamicSec = nullptr;
1550   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
1551     if (Sec.sh_type != ELF::SHT_DYNAMIC)
1552       continue;
1553     DynamicSec = &Sec;
1554     break;
1555   }
1556 
1557   if (DynamicPhdr && ((DynamicPhdr->p_offset + DynamicPhdr->p_filesz >
1558                        ObjF.getMemoryBufferRef().getBufferSize()) ||
1559                       (DynamicPhdr->p_offset + DynamicPhdr->p_filesz <
1560                        DynamicPhdr->p_offset))) {
1561     reportUniqueWarning(
1562         "PT_DYNAMIC segment offset (0x" +
1563         Twine::utohexstr(DynamicPhdr->p_offset) + ") + file size (0x" +
1564         Twine::utohexstr(DynamicPhdr->p_filesz) +
1565         ") exceeds the size of the file (0x" +
1566         Twine::utohexstr(ObjF.getMemoryBufferRef().getBufferSize()) + ")");
1567     // Don't use the broken dynamic header.
1568     DynamicPhdr = nullptr;
1569   }
1570 
1571   if (DynamicPhdr && DynamicSec) {
1572     if (DynamicSec->sh_addr + DynamicSec->sh_size >
1573             DynamicPhdr->p_vaddr + DynamicPhdr->p_memsz ||
1574         DynamicSec->sh_addr < DynamicPhdr->p_vaddr)
1575       reportUniqueWarning(describe(*DynamicSec) +
1576                           " is not contained within the "
1577                           "PT_DYNAMIC segment");
1578 
1579     if (DynamicSec->sh_addr != DynamicPhdr->p_vaddr)
1580       reportUniqueWarning(describe(*DynamicSec) + " is not at the start of "
1581                                                   "PT_DYNAMIC segment");
1582   }
1583 
1584   return std::make_pair(DynamicPhdr, DynamicSec);
1585 }
1586 
1587 template <typename ELFT>
1588 void ELFDumper<ELFT>::loadDynamicTable() {
1589   const Elf_Phdr *DynamicPhdr;
1590   const Elf_Shdr *DynamicSec;
1591   std::tie(DynamicPhdr, DynamicSec) = findDynamic();
1592   if (!DynamicPhdr && !DynamicSec)
1593     return;
1594 
1595   DynRegionInfo FromPhdr(ObjF, *this);
1596   bool IsPhdrTableValid = false;
1597   if (DynamicPhdr) {
1598     // Use cantFail(), because p_offset/p_filesz fields of a PT_DYNAMIC are
1599     // validated in findDynamic() and so createDRI() is not expected to fail.
1600     FromPhdr = cantFail(createDRI(DynamicPhdr->p_offset, DynamicPhdr->p_filesz,
1601                                   sizeof(Elf_Dyn)));
1602     FromPhdr.SizePrintName = "PT_DYNAMIC size";
1603     FromPhdr.EntSizePrintName = "";
1604     IsPhdrTableValid = !FromPhdr.template getAsArrayRef<Elf_Dyn>().empty();
1605   }
1606 
1607   // Locate the dynamic table described in a section header.
1608   // Ignore sh_entsize and use the expected value for entry size explicitly.
1609   // This allows us to dump dynamic sections with a broken sh_entsize
1610   // field.
1611   DynRegionInfo FromSec(ObjF, *this);
1612   bool IsSecTableValid = false;
1613   if (DynamicSec) {
1614     Expected<DynRegionInfo> RegOrErr =
1615         createDRI(DynamicSec->sh_offset, DynamicSec->sh_size, sizeof(Elf_Dyn));
1616     if (RegOrErr) {
1617       FromSec = *RegOrErr;
1618       FromSec.Context = describe(*DynamicSec);
1619       FromSec.EntSizePrintName = "";
1620       IsSecTableValid = !FromSec.template getAsArrayRef<Elf_Dyn>().empty();
1621     } else {
1622       reportUniqueWarning("unable to read the dynamic table from " +
1623                           describe(*DynamicSec) + ": " +
1624                           toString(RegOrErr.takeError()));
1625     }
1626   }
1627 
1628   // When we only have information from one of the SHT_DYNAMIC section header or
1629   // PT_DYNAMIC program header, just use that.
1630   if (!DynamicPhdr || !DynamicSec) {
1631     if ((DynamicPhdr && IsPhdrTableValid) || (DynamicSec && IsSecTableValid)) {
1632       DynamicTable = DynamicPhdr ? FromPhdr : FromSec;
1633       parseDynamicTable();
1634     } else {
1635       reportUniqueWarning("no valid dynamic table was found");
1636     }
1637     return;
1638   }
1639 
1640   // At this point we have tables found from the section header and from the
1641   // dynamic segment. Usually they match, but we have to do sanity checks to
1642   // verify that.
1643 
1644   if (FromPhdr.Addr != FromSec.Addr)
1645     reportUniqueWarning("SHT_DYNAMIC section header and PT_DYNAMIC "
1646                         "program header disagree about "
1647                         "the location of the dynamic table");
1648 
1649   if (!IsPhdrTableValid && !IsSecTableValid) {
1650     reportUniqueWarning("no valid dynamic table was found");
1651     return;
1652   }
1653 
1654   // Information in the PT_DYNAMIC program header has priority over the
1655   // information in a section header.
1656   if (IsPhdrTableValid) {
1657     if (!IsSecTableValid)
1658       reportUniqueWarning(
1659           "SHT_DYNAMIC dynamic table is invalid: PT_DYNAMIC will be used");
1660     DynamicTable = FromPhdr;
1661   } else {
1662     reportUniqueWarning(
1663         "PT_DYNAMIC dynamic table is invalid: SHT_DYNAMIC will be used");
1664     DynamicTable = FromSec;
1665   }
1666 
1667   parseDynamicTable();
1668 }
1669 
1670 template <typename ELFT>
1671 ELFDumper<ELFT>::ELFDumper(const object::ELFObjectFile<ELFT> &O,
1672                            ScopedPrinter &Writer)
1673     : ObjDumper(Writer, O.getFileName()), ObjF(O), Obj(O.getELFFile()),
1674       FileName(O.getFileName()), DynRelRegion(O, *this),
1675       DynRelaRegion(O, *this), DynRelrRegion(O, *this),
1676       DynPLTRelRegion(O, *this), DynSymTabShndxRegion(O, *this),
1677       DynamicTable(O, *this) {
1678   if (!O.IsContentValid())
1679     return;
1680 
1681   typename ELFT::ShdrRange Sections = cantFail(Obj.sections());
1682   for (const Elf_Shdr &Sec : Sections) {
1683     switch (Sec.sh_type) {
1684     case ELF::SHT_SYMTAB:
1685       if (!DotSymtabSec)
1686         DotSymtabSec = &Sec;
1687       break;
1688     case ELF::SHT_DYNSYM:
1689       if (!DotDynsymSec)
1690         DotDynsymSec = &Sec;
1691 
1692       if (!DynSymRegion) {
1693         Expected<DynRegionInfo> RegOrErr =
1694             createDRI(Sec.sh_offset, Sec.sh_size, Sec.sh_entsize);
1695         if (RegOrErr) {
1696           DynSymRegion = *RegOrErr;
1697           DynSymRegion->Context = describe(Sec);
1698 
1699           if (Expected<StringRef> E = Obj.getStringTableForSymtab(Sec))
1700             DynamicStringTable = *E;
1701           else
1702             reportUniqueWarning("unable to get the string table for the " +
1703                                 describe(Sec) + ": " + toString(E.takeError()));
1704         } else {
1705           reportUniqueWarning("unable to read dynamic symbols from " +
1706                               describe(Sec) + ": " +
1707                               toString(RegOrErr.takeError()));
1708         }
1709       }
1710       break;
1711     case ELF::SHT_SYMTAB_SHNDX: {
1712       uint32_t SymtabNdx = Sec.sh_link;
1713       if (SymtabNdx >= Sections.size()) {
1714         reportUniqueWarning(
1715             "unable to get the associated symbol table for " + describe(Sec) +
1716             ": sh_link (" + Twine(SymtabNdx) +
1717             ") is greater than or equal to the total number of sections (" +
1718             Twine(Sections.size()) + ")");
1719         continue;
1720       }
1721 
1722       if (Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
1723               Obj.getSHNDXTable(Sec)) {
1724         if (!ShndxTables.insert({&Sections[SymtabNdx], *ShndxTableOrErr})
1725                  .second)
1726           reportUniqueWarning(
1727               "multiple SHT_SYMTAB_SHNDX sections are linked to " +
1728               describe(Sec));
1729       } else {
1730         reportUniqueWarning(ShndxTableOrErr.takeError());
1731       }
1732       break;
1733     }
1734     case ELF::SHT_GNU_versym:
1735       if (!SymbolVersionSection)
1736         SymbolVersionSection = &Sec;
1737       break;
1738     case ELF::SHT_GNU_verdef:
1739       if (!SymbolVersionDefSection)
1740         SymbolVersionDefSection = &Sec;
1741       break;
1742     case ELF::SHT_GNU_verneed:
1743       if (!SymbolVersionNeedSection)
1744         SymbolVersionNeedSection = &Sec;
1745       break;
1746     case ELF::SHT_LLVM_CALL_GRAPH_PROFILE:
1747       if (!DotCGProfileSec)
1748         DotCGProfileSec = &Sec;
1749       break;
1750     case ELF::SHT_LLVM_ADDRSIG:
1751       if (!DotAddrsigSec)
1752         DotAddrsigSec = &Sec;
1753       break;
1754     }
1755   }
1756 
1757   loadDynamicTable();
1758 }
1759 
1760 template <typename ELFT> void ELFDumper<ELFT>::parseDynamicTable() {
1761   auto toMappedAddr = [&](uint64_t Tag, uint64_t VAddr) -> const uint8_t * {
1762     auto MappedAddrOrError = Obj.toMappedAddr(VAddr, [&](const Twine &Msg) {
1763       this->reportUniqueWarning(Msg);
1764       return Error::success();
1765     });
1766     if (!MappedAddrOrError) {
1767       this->reportUniqueWarning("unable to parse DT_" +
1768                                 Obj.getDynamicTagAsString(Tag) + ": " +
1769                                 llvm::toString(MappedAddrOrError.takeError()));
1770       return nullptr;
1771     }
1772     return MappedAddrOrError.get();
1773   };
1774 
1775   const char *StringTableBegin = nullptr;
1776   uint64_t StringTableSize = 0;
1777   Optional<DynRegionInfo> DynSymFromTable;
1778   for (const Elf_Dyn &Dyn : dynamic_table()) {
1779     switch (Dyn.d_tag) {
1780     case ELF::DT_HASH:
1781       HashTable = reinterpret_cast<const Elf_Hash *>(
1782           toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
1783       break;
1784     case ELF::DT_GNU_HASH:
1785       GnuHashTable = reinterpret_cast<const Elf_GnuHash *>(
1786           toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
1787       break;
1788     case ELF::DT_STRTAB:
1789       StringTableBegin = reinterpret_cast<const char *>(
1790           toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
1791       break;
1792     case ELF::DT_STRSZ:
1793       StringTableSize = Dyn.getVal();
1794       break;
1795     case ELF::DT_SYMTAB: {
1796       // If we can't map the DT_SYMTAB value to an address (e.g. when there are
1797       // no program headers), we ignore its value.
1798       if (const uint8_t *VA = toMappedAddr(Dyn.getTag(), Dyn.getPtr())) {
1799         DynSymFromTable.emplace(ObjF, *this);
1800         DynSymFromTable->Addr = VA;
1801         DynSymFromTable->EntSize = sizeof(Elf_Sym);
1802         DynSymFromTable->EntSizePrintName = "";
1803       }
1804       break;
1805     }
1806     case ELF::DT_SYMENT: {
1807       uint64_t Val = Dyn.getVal();
1808       if (Val != sizeof(Elf_Sym))
1809         this->reportUniqueWarning("DT_SYMENT value of 0x" +
1810                                   Twine::utohexstr(Val) +
1811                                   " is not the size of a symbol (0x" +
1812                                   Twine::utohexstr(sizeof(Elf_Sym)) + ")");
1813       break;
1814     }
1815     case ELF::DT_RELA:
1816       DynRelaRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
1817       break;
1818     case ELF::DT_RELASZ:
1819       DynRelaRegion.Size = Dyn.getVal();
1820       DynRelaRegion.SizePrintName = "DT_RELASZ value";
1821       break;
1822     case ELF::DT_RELAENT:
1823       DynRelaRegion.EntSize = Dyn.getVal();
1824       DynRelaRegion.EntSizePrintName = "DT_RELAENT value";
1825       break;
1826     case ELF::DT_SONAME:
1827       SONameOffset = Dyn.getVal();
1828       break;
1829     case ELF::DT_REL:
1830       DynRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
1831       break;
1832     case ELF::DT_RELSZ:
1833       DynRelRegion.Size = Dyn.getVal();
1834       DynRelRegion.SizePrintName = "DT_RELSZ value";
1835       break;
1836     case ELF::DT_RELENT:
1837       DynRelRegion.EntSize = Dyn.getVal();
1838       DynRelRegion.EntSizePrintName = "DT_RELENT value";
1839       break;
1840     case ELF::DT_RELR:
1841     case ELF::DT_ANDROID_RELR:
1842       DynRelrRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
1843       break;
1844     case ELF::DT_RELRSZ:
1845     case ELF::DT_ANDROID_RELRSZ:
1846       DynRelrRegion.Size = Dyn.getVal();
1847       DynRelrRegion.SizePrintName = Dyn.d_tag == ELF::DT_RELRSZ
1848                                         ? "DT_RELRSZ value"
1849                                         : "DT_ANDROID_RELRSZ value";
1850       break;
1851     case ELF::DT_RELRENT:
1852     case ELF::DT_ANDROID_RELRENT:
1853       DynRelrRegion.EntSize = Dyn.getVal();
1854       DynRelrRegion.EntSizePrintName = Dyn.d_tag == ELF::DT_RELRENT
1855                                            ? "DT_RELRENT value"
1856                                            : "DT_ANDROID_RELRENT value";
1857       break;
1858     case ELF::DT_PLTREL:
1859       if (Dyn.getVal() == DT_REL)
1860         DynPLTRelRegion.EntSize = sizeof(Elf_Rel);
1861       else if (Dyn.getVal() == DT_RELA)
1862         DynPLTRelRegion.EntSize = sizeof(Elf_Rela);
1863       else
1864         reportUniqueWarning(Twine("unknown DT_PLTREL value of ") +
1865                             Twine((uint64_t)Dyn.getVal()));
1866       DynPLTRelRegion.EntSizePrintName = "PLTREL entry size";
1867       break;
1868     case ELF::DT_JMPREL:
1869       DynPLTRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
1870       break;
1871     case ELF::DT_PLTRELSZ:
1872       DynPLTRelRegion.Size = Dyn.getVal();
1873       DynPLTRelRegion.SizePrintName = "DT_PLTRELSZ value";
1874       break;
1875     case ELF::DT_SYMTAB_SHNDX:
1876       DynSymTabShndxRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
1877       DynSymTabShndxRegion.EntSize = sizeof(Elf_Word);
1878       break;
1879     }
1880   }
1881 
1882   if (StringTableBegin) {
1883     const uint64_t FileSize = Obj.getBufSize();
1884     const uint64_t Offset = (const uint8_t *)StringTableBegin - Obj.base();
1885     if (StringTableSize > FileSize - Offset)
1886       reportUniqueWarning(
1887           "the dynamic string table at 0x" + Twine::utohexstr(Offset) +
1888           " goes past the end of the file (0x" + Twine::utohexstr(FileSize) +
1889           ") with DT_STRSZ = 0x" + Twine::utohexstr(StringTableSize));
1890     else
1891       DynamicStringTable = StringRef(StringTableBegin, StringTableSize);
1892   }
1893 
1894   const bool IsHashTableSupported = getHashTableEntSize() == 4;
1895   if (DynSymRegion) {
1896     // Often we find the information about the dynamic symbol table
1897     // location in the SHT_DYNSYM section header. However, the value in
1898     // DT_SYMTAB has priority, because it is used by dynamic loaders to
1899     // locate .dynsym at runtime. The location we find in the section header
1900     // and the location we find here should match.
1901     if (DynSymFromTable && DynSymFromTable->Addr != DynSymRegion->Addr)
1902       reportUniqueWarning(
1903           createError("SHT_DYNSYM section header and DT_SYMTAB disagree about "
1904                       "the location of the dynamic symbol table"));
1905 
1906     // According to the ELF gABI: "The number of symbol table entries should
1907     // equal nchain". Check to see if the DT_HASH hash table nchain value
1908     // conflicts with the number of symbols in the dynamic symbol table
1909     // according to the section header.
1910     if (HashTable && IsHashTableSupported) {
1911       if (DynSymRegion->EntSize == 0)
1912         reportUniqueWarning("SHT_DYNSYM section has sh_entsize == 0");
1913       else if (HashTable->nchain != DynSymRegion->Size / DynSymRegion->EntSize)
1914         reportUniqueWarning(
1915             "hash table nchain (" + Twine(HashTable->nchain) +
1916             ") differs from symbol count derived from SHT_DYNSYM section "
1917             "header (" +
1918             Twine(DynSymRegion->Size / DynSymRegion->EntSize) + ")");
1919     }
1920   }
1921 
1922   // Delay the creation of the actual dynamic symbol table until now, so that
1923   // checks can always be made against the section header-based properties,
1924   // without worrying about tag order.
1925   if (DynSymFromTable) {
1926     if (!DynSymRegion) {
1927       DynSymRegion = DynSymFromTable;
1928     } else {
1929       DynSymRegion->Addr = DynSymFromTable->Addr;
1930       DynSymRegion->EntSize = DynSymFromTable->EntSize;
1931       DynSymRegion->EntSizePrintName = DynSymFromTable->EntSizePrintName;
1932     }
1933   }
1934 
1935   // Derive the dynamic symbol table size from the DT_HASH hash table, if
1936   // present.
1937   if (HashTable && IsHashTableSupported && DynSymRegion) {
1938     const uint64_t FileSize = Obj.getBufSize();
1939     const uint64_t DerivedSize =
1940         (uint64_t)HashTable->nchain * DynSymRegion->EntSize;
1941     const uint64_t Offset = (const uint8_t *)DynSymRegion->Addr - Obj.base();
1942     if (DerivedSize > FileSize - Offset)
1943       reportUniqueWarning(
1944           "the size (0x" + Twine::utohexstr(DerivedSize) +
1945           ") of the dynamic symbol table at 0x" + Twine::utohexstr(Offset) +
1946           ", derived from the hash table, goes past the end of the file (0x" +
1947           Twine::utohexstr(FileSize) + ") and will be ignored");
1948     else
1949       DynSymRegion->Size = HashTable->nchain * DynSymRegion->EntSize;
1950   }
1951 }
1952 
1953 template <typename ELFT> void ELFDumper<ELFT>::printVersionInfo() {
1954   // Dump version symbol section.
1955   printVersionSymbolSection(SymbolVersionSection);
1956 
1957   // Dump version definition section.
1958   printVersionDefinitionSection(SymbolVersionDefSection);
1959 
1960   // Dump version dependency section.
1961   printVersionDependencySection(SymbolVersionNeedSection);
1962 }
1963 
1964 #define LLVM_READOBJ_DT_FLAG_ENT(prefix, enum)                                 \
1965   { #enum, prefix##_##enum }
1966 
1967 static const EnumEntry<unsigned> ElfDynamicDTFlags[] = {
1968   LLVM_READOBJ_DT_FLAG_ENT(DF, ORIGIN),
1969   LLVM_READOBJ_DT_FLAG_ENT(DF, SYMBOLIC),
1970   LLVM_READOBJ_DT_FLAG_ENT(DF, TEXTREL),
1971   LLVM_READOBJ_DT_FLAG_ENT(DF, BIND_NOW),
1972   LLVM_READOBJ_DT_FLAG_ENT(DF, STATIC_TLS)
1973 };
1974 
1975 static const EnumEntry<unsigned> ElfDynamicDTFlags1[] = {
1976   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOW),
1977   LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAL),
1978   LLVM_READOBJ_DT_FLAG_ENT(DF_1, GROUP),
1979   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODELETE),
1980   LLVM_READOBJ_DT_FLAG_ENT(DF_1, LOADFLTR),
1981   LLVM_READOBJ_DT_FLAG_ENT(DF_1, INITFIRST),
1982   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOOPEN),
1983   LLVM_READOBJ_DT_FLAG_ENT(DF_1, ORIGIN),
1984   LLVM_READOBJ_DT_FLAG_ENT(DF_1, DIRECT),
1985   LLVM_READOBJ_DT_FLAG_ENT(DF_1, TRANS),
1986   LLVM_READOBJ_DT_FLAG_ENT(DF_1, INTERPOSE),
1987   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODEFLIB),
1988   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODUMP),
1989   LLVM_READOBJ_DT_FLAG_ENT(DF_1, CONFALT),
1990   LLVM_READOBJ_DT_FLAG_ENT(DF_1, ENDFILTEE),
1991   LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELDNE),
1992   LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELPND),
1993   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODIRECT),
1994   LLVM_READOBJ_DT_FLAG_ENT(DF_1, IGNMULDEF),
1995   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOKSYMS),
1996   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOHDR),
1997   LLVM_READOBJ_DT_FLAG_ENT(DF_1, EDITED),
1998   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NORELOC),
1999   LLVM_READOBJ_DT_FLAG_ENT(DF_1, SYMINTPOSE),
2000   LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAUDIT),
2001   LLVM_READOBJ_DT_FLAG_ENT(DF_1, SINGLETON),
2002   LLVM_READOBJ_DT_FLAG_ENT(DF_1, PIE),
2003 };
2004 
2005 static const EnumEntry<unsigned> ElfDynamicDTMipsFlags[] = {
2006   LLVM_READOBJ_DT_FLAG_ENT(RHF, NONE),
2007   LLVM_READOBJ_DT_FLAG_ENT(RHF, QUICKSTART),
2008   LLVM_READOBJ_DT_FLAG_ENT(RHF, NOTPOT),
2009   LLVM_READOBJ_DT_FLAG_ENT(RHS, NO_LIBRARY_REPLACEMENT),
2010   LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_MOVE),
2011   LLVM_READOBJ_DT_FLAG_ENT(RHF, SGI_ONLY),
2012   LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_INIT),
2013   LLVM_READOBJ_DT_FLAG_ENT(RHF, DELTA_C_PLUS_PLUS),
2014   LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_START_INIT),
2015   LLVM_READOBJ_DT_FLAG_ENT(RHF, PIXIE),
2016   LLVM_READOBJ_DT_FLAG_ENT(RHF, DEFAULT_DELAY_LOAD),
2017   LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTART),
2018   LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTARTED),
2019   LLVM_READOBJ_DT_FLAG_ENT(RHF, CORD),
2020   LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_UNRES_UNDEF),
2021   LLVM_READOBJ_DT_FLAG_ENT(RHF, RLD_ORDER_SAFE)
2022 };
2023 
2024 #undef LLVM_READOBJ_DT_FLAG_ENT
2025 
2026 template <typename T, typename TFlag>
2027 void printFlags(T Value, ArrayRef<EnumEntry<TFlag>> Flags, raw_ostream &OS) {
2028   SmallVector<EnumEntry<TFlag>, 10> SetFlags;
2029   for (const EnumEntry<TFlag> &Flag : Flags)
2030     if (Flag.Value != 0 && (Value & Flag.Value) == Flag.Value)
2031       SetFlags.push_back(Flag);
2032 
2033   for (const EnumEntry<TFlag> &Flag : SetFlags)
2034     OS << Flag.Name << " ";
2035 }
2036 
2037 template <class ELFT>
2038 const typename ELFT::Shdr *
2039 ELFDumper<ELFT>::findSectionByName(StringRef Name) const {
2040   for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
2041     if (Expected<StringRef> NameOrErr = Obj.getSectionName(Shdr)) {
2042       if (*NameOrErr == Name)
2043         return &Shdr;
2044     } else {
2045       reportUniqueWarning("unable to read the name of " + describe(Shdr) +
2046                           ": " + toString(NameOrErr.takeError()));
2047     }
2048   }
2049   return nullptr;
2050 }
2051 
2052 template <class ELFT>
2053 std::string ELFDumper<ELFT>::getDynamicEntry(uint64_t Type,
2054                                              uint64_t Value) const {
2055   auto FormatHexValue = [](uint64_t V) {
2056     std::string Str;
2057     raw_string_ostream OS(Str);
2058     const char *ConvChar =
2059         (opts::Output == opts::GNU) ? "0x%" PRIx64 : "0x%" PRIX64;
2060     OS << format(ConvChar, V);
2061     return OS.str();
2062   };
2063 
2064   auto FormatFlags = [](uint64_t V,
2065                         llvm::ArrayRef<llvm::EnumEntry<unsigned int>> Array) {
2066     std::string Str;
2067     raw_string_ostream OS(Str);
2068     printFlags(V, Array, OS);
2069     return OS.str();
2070   };
2071 
2072   // Handle custom printing of architecture specific tags
2073   switch (Obj.getHeader().e_machine) {
2074   case EM_AARCH64:
2075     switch (Type) {
2076     case DT_AARCH64_BTI_PLT:
2077     case DT_AARCH64_PAC_PLT:
2078     case DT_AARCH64_VARIANT_PCS:
2079       return std::to_string(Value);
2080     default:
2081       break;
2082     }
2083     break;
2084   case EM_HEXAGON:
2085     switch (Type) {
2086     case DT_HEXAGON_VER:
2087       return std::to_string(Value);
2088     case DT_HEXAGON_SYMSZ:
2089     case DT_HEXAGON_PLT:
2090       return FormatHexValue(Value);
2091     default:
2092       break;
2093     }
2094     break;
2095   case EM_MIPS:
2096     switch (Type) {
2097     case DT_MIPS_RLD_VERSION:
2098     case DT_MIPS_LOCAL_GOTNO:
2099     case DT_MIPS_SYMTABNO:
2100     case DT_MIPS_UNREFEXTNO:
2101       return std::to_string(Value);
2102     case DT_MIPS_TIME_STAMP:
2103     case DT_MIPS_ICHECKSUM:
2104     case DT_MIPS_IVERSION:
2105     case DT_MIPS_BASE_ADDRESS:
2106     case DT_MIPS_MSYM:
2107     case DT_MIPS_CONFLICT:
2108     case DT_MIPS_LIBLIST:
2109     case DT_MIPS_CONFLICTNO:
2110     case DT_MIPS_LIBLISTNO:
2111     case DT_MIPS_GOTSYM:
2112     case DT_MIPS_HIPAGENO:
2113     case DT_MIPS_RLD_MAP:
2114     case DT_MIPS_DELTA_CLASS:
2115     case DT_MIPS_DELTA_CLASS_NO:
2116     case DT_MIPS_DELTA_INSTANCE:
2117     case DT_MIPS_DELTA_RELOC:
2118     case DT_MIPS_DELTA_RELOC_NO:
2119     case DT_MIPS_DELTA_SYM:
2120     case DT_MIPS_DELTA_SYM_NO:
2121     case DT_MIPS_DELTA_CLASSSYM:
2122     case DT_MIPS_DELTA_CLASSSYM_NO:
2123     case DT_MIPS_CXX_FLAGS:
2124     case DT_MIPS_PIXIE_INIT:
2125     case DT_MIPS_SYMBOL_LIB:
2126     case DT_MIPS_LOCALPAGE_GOTIDX:
2127     case DT_MIPS_LOCAL_GOTIDX:
2128     case DT_MIPS_HIDDEN_GOTIDX:
2129     case DT_MIPS_PROTECTED_GOTIDX:
2130     case DT_MIPS_OPTIONS:
2131     case DT_MIPS_INTERFACE:
2132     case DT_MIPS_DYNSTR_ALIGN:
2133     case DT_MIPS_INTERFACE_SIZE:
2134     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
2135     case DT_MIPS_PERF_SUFFIX:
2136     case DT_MIPS_COMPACT_SIZE:
2137     case DT_MIPS_GP_VALUE:
2138     case DT_MIPS_AUX_DYNAMIC:
2139     case DT_MIPS_PLTGOT:
2140     case DT_MIPS_RWPLT:
2141     case DT_MIPS_RLD_MAP_REL:
2142       return FormatHexValue(Value);
2143     case DT_MIPS_FLAGS:
2144       return FormatFlags(Value, makeArrayRef(ElfDynamicDTMipsFlags));
2145     default:
2146       break;
2147     }
2148     break;
2149   default:
2150     break;
2151   }
2152 
2153   switch (Type) {
2154   case DT_PLTREL:
2155     if (Value == DT_REL)
2156       return "REL";
2157     if (Value == DT_RELA)
2158       return "RELA";
2159     LLVM_FALLTHROUGH;
2160   case DT_PLTGOT:
2161   case DT_HASH:
2162   case DT_STRTAB:
2163   case DT_SYMTAB:
2164   case DT_RELA:
2165   case DT_INIT:
2166   case DT_FINI:
2167   case DT_REL:
2168   case DT_JMPREL:
2169   case DT_INIT_ARRAY:
2170   case DT_FINI_ARRAY:
2171   case DT_PREINIT_ARRAY:
2172   case DT_DEBUG:
2173   case DT_VERDEF:
2174   case DT_VERNEED:
2175   case DT_VERSYM:
2176   case DT_GNU_HASH:
2177   case DT_NULL:
2178     return FormatHexValue(Value);
2179   case DT_RELACOUNT:
2180   case DT_RELCOUNT:
2181   case DT_VERDEFNUM:
2182   case DT_VERNEEDNUM:
2183     return std::to_string(Value);
2184   case DT_PLTRELSZ:
2185   case DT_RELASZ:
2186   case DT_RELAENT:
2187   case DT_STRSZ:
2188   case DT_SYMENT:
2189   case DT_RELSZ:
2190   case DT_RELENT:
2191   case DT_INIT_ARRAYSZ:
2192   case DT_FINI_ARRAYSZ:
2193   case DT_PREINIT_ARRAYSZ:
2194   case DT_ANDROID_RELSZ:
2195   case DT_ANDROID_RELASZ:
2196     return std::to_string(Value) + " (bytes)";
2197   case DT_NEEDED:
2198   case DT_SONAME:
2199   case DT_AUXILIARY:
2200   case DT_USED:
2201   case DT_FILTER:
2202   case DT_RPATH:
2203   case DT_RUNPATH: {
2204     const std::map<uint64_t, const char *> TagNames = {
2205         {DT_NEEDED, "Shared library"},       {DT_SONAME, "Library soname"},
2206         {DT_AUXILIARY, "Auxiliary library"}, {DT_USED, "Not needed object"},
2207         {DT_FILTER, "Filter library"},       {DT_RPATH, "Library rpath"},
2208         {DT_RUNPATH, "Library runpath"},
2209     };
2210 
2211     return (Twine(TagNames.at(Type)) + ": [" + getDynamicString(Value) + "]")
2212         .str();
2213   }
2214   case DT_FLAGS:
2215     return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags));
2216   case DT_FLAGS_1:
2217     return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags1));
2218   default:
2219     return FormatHexValue(Value);
2220   }
2221 }
2222 
2223 template <class ELFT>
2224 StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const {
2225   if (DynamicStringTable.empty() && !DynamicStringTable.data()) {
2226     reportUniqueWarning("string table was not found");
2227     return "<?>";
2228   }
2229 
2230   auto WarnAndReturn = [this](const Twine &Msg, uint64_t Offset) {
2231     reportUniqueWarning("string table at offset 0x" + Twine::utohexstr(Offset) +
2232                         Msg);
2233     return "<?>";
2234   };
2235 
2236   const uint64_t FileSize = Obj.getBufSize();
2237   const uint64_t Offset =
2238       (const uint8_t *)DynamicStringTable.data() - Obj.base();
2239   if (DynamicStringTable.size() > FileSize - Offset)
2240     return WarnAndReturn(" with size 0x" +
2241                              Twine::utohexstr(DynamicStringTable.size()) +
2242                              " goes past the end of the file (0x" +
2243                              Twine::utohexstr(FileSize) + ")",
2244                          Offset);
2245 
2246   if (Value >= DynamicStringTable.size())
2247     return WarnAndReturn(
2248         ": unable to read the string at 0x" + Twine::utohexstr(Offset + Value) +
2249             ": it goes past the end of the table (0x" +
2250             Twine::utohexstr(Offset + DynamicStringTable.size()) + ")",
2251         Offset);
2252 
2253   if (DynamicStringTable.back() != '\0')
2254     return WarnAndReturn(": unable to read the string at 0x" +
2255                              Twine::utohexstr(Offset + Value) +
2256                              ": the string table is not null-terminated",
2257                          Offset);
2258 
2259   return DynamicStringTable.data() + Value;
2260 }
2261 
2262 template <class ELFT> void ELFDumper<ELFT>::printUnwindInfo() {
2263   DwarfCFIEH::PrinterContext<ELFT> Ctx(W, ObjF);
2264   Ctx.printUnwindInformation();
2265 }
2266 
2267 // The namespace is needed to fix the compilation with GCC older than 7.0+.
2268 namespace {
2269 template <> void ELFDumper<ELF32LE>::printUnwindInfo() {
2270   if (Obj.getHeader().e_machine == EM_ARM) {
2271     ARM::EHABI::PrinterContext<ELF32LE> Ctx(W, Obj, ObjF.getFileName(),
2272                                             DotSymtabSec);
2273     Ctx.PrintUnwindInformation();
2274   }
2275   DwarfCFIEH::PrinterContext<ELF32LE> Ctx(W, ObjF);
2276   Ctx.printUnwindInformation();
2277 }
2278 } // namespace
2279 
2280 template <class ELFT> void ELFDumper<ELFT>::printNeededLibraries() {
2281   ListScope D(W, "NeededLibraries");
2282 
2283   std::vector<StringRef> Libs;
2284   for (const auto &Entry : dynamic_table())
2285     if (Entry.d_tag == ELF::DT_NEEDED)
2286       Libs.push_back(getDynamicString(Entry.d_un.d_val));
2287 
2288   llvm::sort(Libs);
2289 
2290   for (StringRef L : Libs)
2291     W.startLine() << L << "\n";
2292 }
2293 
2294 template <class ELFT>
2295 static Error checkHashTable(const ELFDumper<ELFT> &Dumper,
2296                             const typename ELFT::Hash *H,
2297                             bool *IsHeaderValid = nullptr) {
2298   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
2299   const uint64_t SecOffset = (const uint8_t *)H - Obj.base();
2300   if (Dumper.getHashTableEntSize() == 8) {
2301     auto It = llvm::find_if(ElfMachineType, [&](const EnumEntry<unsigned> &E) {
2302       return E.Value == Obj.getHeader().e_machine;
2303     });
2304     if (IsHeaderValid)
2305       *IsHeaderValid = false;
2306     return createError("the hash table at 0x" + Twine::utohexstr(SecOffset) +
2307                        " is not supported: it contains non-standard 8 "
2308                        "byte entries on " +
2309                        It->AltName + " platform");
2310   }
2311 
2312   auto MakeError = [&](const Twine &Msg = "") {
2313     return createError("the hash table at offset 0x" +
2314                        Twine::utohexstr(SecOffset) +
2315                        " goes past the end of the file (0x" +
2316                        Twine::utohexstr(Obj.getBufSize()) + ")" + Msg);
2317   };
2318 
2319   // Each SHT_HASH section starts from two 32-bit fields: nbucket and nchain.
2320   const unsigned HeaderSize = 2 * sizeof(typename ELFT::Word);
2321 
2322   if (IsHeaderValid)
2323     *IsHeaderValid = Obj.getBufSize() - SecOffset >= HeaderSize;
2324 
2325   if (Obj.getBufSize() - SecOffset < HeaderSize)
2326     return MakeError();
2327 
2328   if (Obj.getBufSize() - SecOffset - HeaderSize <
2329       ((uint64_t)H->nbucket + H->nchain) * sizeof(typename ELFT::Word))
2330     return MakeError(", nbucket = " + Twine(H->nbucket) +
2331                      ", nchain = " + Twine(H->nchain));
2332   return Error::success();
2333 }
2334 
2335 template <class ELFT>
2336 static Error checkGNUHashTable(const ELFFile<ELFT> &Obj,
2337                                const typename ELFT::GnuHash *GnuHashTable,
2338                                bool *IsHeaderValid = nullptr) {
2339   const uint8_t *TableData = reinterpret_cast<const uint8_t *>(GnuHashTable);
2340   assert(TableData >= Obj.base() && TableData < Obj.base() + Obj.getBufSize() &&
2341          "GnuHashTable must always point to a location inside the file");
2342 
2343   uint64_t TableOffset = TableData - Obj.base();
2344   if (IsHeaderValid)
2345     *IsHeaderValid = TableOffset + /*Header size:*/ 16 < Obj.getBufSize();
2346   if (TableOffset + 16 + (uint64_t)GnuHashTable->nbuckets * 4 +
2347           (uint64_t)GnuHashTable->maskwords * sizeof(typename ELFT::Off) >=
2348       Obj.getBufSize())
2349     return createError("unable to dump the SHT_GNU_HASH "
2350                        "section at 0x" +
2351                        Twine::utohexstr(TableOffset) +
2352                        ": it goes past the end of the file");
2353   return Error::success();
2354 }
2355 
2356 template <typename ELFT> void ELFDumper<ELFT>::printHashTable() {
2357   DictScope D(W, "HashTable");
2358   if (!HashTable)
2359     return;
2360 
2361   bool IsHeaderValid;
2362   Error Err = checkHashTable(*this, HashTable, &IsHeaderValid);
2363   if (IsHeaderValid) {
2364     W.printNumber("Num Buckets", HashTable->nbucket);
2365     W.printNumber("Num Chains", HashTable->nchain);
2366   }
2367 
2368   if (Err) {
2369     reportUniqueWarning(std::move(Err));
2370     return;
2371   }
2372 
2373   W.printList("Buckets", HashTable->buckets());
2374   W.printList("Chains", HashTable->chains());
2375 }
2376 
2377 template <class ELFT>
2378 static Expected<ArrayRef<typename ELFT::Word>>
2379 getGnuHashTableChains(Optional<DynRegionInfo> DynSymRegion,
2380                       const typename ELFT::GnuHash *GnuHashTable) {
2381   if (!DynSymRegion)
2382     return createError("no dynamic symbol table found");
2383 
2384   ArrayRef<typename ELFT::Sym> DynSymTable =
2385       DynSymRegion->template getAsArrayRef<typename ELFT::Sym>();
2386   size_t NumSyms = DynSymTable.size();
2387   if (!NumSyms)
2388     return createError("the dynamic symbol table is empty");
2389 
2390   if (GnuHashTable->symndx < NumSyms)
2391     return GnuHashTable->values(NumSyms);
2392 
2393   // A normal empty GNU hash table section produced by linker might have
2394   // symndx set to the number of dynamic symbols + 1 (for the zero symbol)
2395   // and have dummy null values in the Bloom filter and in the buckets
2396   // vector (or no values at all). It happens because the value of symndx is not
2397   // important for dynamic loaders when the GNU hash table is empty. They just
2398   // skip the whole object during symbol lookup. In such cases, the symndx value
2399   // is irrelevant and we should not report a warning.
2400   ArrayRef<typename ELFT::Word> Buckets = GnuHashTable->buckets();
2401   if (!llvm::all_of(Buckets, [](typename ELFT::Word V) { return V == 0; }))
2402     return createError(
2403         "the first hashed symbol index (" + Twine(GnuHashTable->symndx) +
2404         ") is greater than or equal to the number of dynamic symbols (" +
2405         Twine(NumSyms) + ")");
2406   // There is no way to represent an array of (dynamic symbols count - symndx)
2407   // length.
2408   return ArrayRef<typename ELFT::Word>();
2409 }
2410 
2411 template <typename ELFT>
2412 void ELFDumper<ELFT>::printGnuHashTable() {
2413   DictScope D(W, "GnuHashTable");
2414   if (!GnuHashTable)
2415     return;
2416 
2417   bool IsHeaderValid;
2418   Error Err = checkGNUHashTable<ELFT>(Obj, GnuHashTable, &IsHeaderValid);
2419   if (IsHeaderValid) {
2420     W.printNumber("Num Buckets", GnuHashTable->nbuckets);
2421     W.printNumber("First Hashed Symbol Index", GnuHashTable->symndx);
2422     W.printNumber("Num Mask Words", GnuHashTable->maskwords);
2423     W.printNumber("Shift Count", GnuHashTable->shift2);
2424   }
2425 
2426   if (Err) {
2427     reportUniqueWarning(std::move(Err));
2428     return;
2429   }
2430 
2431   ArrayRef<typename ELFT::Off> BloomFilter = GnuHashTable->filter();
2432   W.printHexList("Bloom Filter", BloomFilter);
2433 
2434   ArrayRef<Elf_Word> Buckets = GnuHashTable->buckets();
2435   W.printList("Buckets", Buckets);
2436 
2437   Expected<ArrayRef<Elf_Word>> Chains =
2438       getGnuHashTableChains<ELFT>(DynSymRegion, GnuHashTable);
2439   if (!Chains) {
2440     reportUniqueWarning("unable to dump 'Values' for the SHT_GNU_HASH "
2441                         "section: " +
2442                         toString(Chains.takeError()));
2443     return;
2444   }
2445 
2446   W.printHexList("Values", *Chains);
2447 }
2448 
2449 template <typename ELFT> void ELFDumper<ELFT>::printLoadName() {
2450   StringRef SOName = "<Not found>";
2451   if (SONameOffset)
2452     SOName = getDynamicString(*SONameOffset);
2453   W.printString("LoadName", SOName);
2454 }
2455 
2456 template <class ELFT> void ELFDumper<ELFT>::printArchSpecificInfo() {
2457   switch (Obj.getHeader().e_machine) {
2458   case EM_ARM:
2459   case EM_RISCV:
2460     printAttributes();
2461     break;
2462   case EM_MIPS: {
2463     printMipsABIFlags();
2464     printMipsOptions();
2465     printMipsReginfo();
2466     MipsGOTParser<ELFT> Parser(*this);
2467     if (Error E = Parser.findGOT(dynamic_table(), dynamic_symbols()))
2468       reportUniqueWarning(std::move(E));
2469     else if (!Parser.isGotEmpty())
2470       printMipsGOT(Parser);
2471 
2472     if (Error E = Parser.findPLT(dynamic_table()))
2473       reportUniqueWarning(std::move(E));
2474     else if (!Parser.isPltEmpty())
2475       printMipsPLT(Parser);
2476     break;
2477   }
2478   default:
2479     break;
2480   }
2481 }
2482 
2483 template <class ELFT> void ELFDumper<ELFT>::printAttributes() {
2484   if (!Obj.isLE()) {
2485     W.startLine() << "Attributes not implemented.\n";
2486     return;
2487   }
2488 
2489   const unsigned Machine = Obj.getHeader().e_machine;
2490   assert((Machine == EM_ARM || Machine == EM_RISCV) &&
2491          "Attributes not implemented.");
2492 
2493   DictScope BA(W, "BuildAttributes");
2494   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
2495     if (Sec.sh_type != ELF::SHT_ARM_ATTRIBUTES &&
2496         Sec.sh_type != ELF::SHT_RISCV_ATTRIBUTES)
2497       continue;
2498 
2499     ArrayRef<uint8_t> Contents;
2500     if (Expected<ArrayRef<uint8_t>> ContentOrErr =
2501             Obj.getSectionContents(Sec)) {
2502       Contents = *ContentOrErr;
2503       if (Contents.empty()) {
2504         reportUniqueWarning("the " + describe(Sec) + " is empty");
2505         continue;
2506       }
2507     } else {
2508       reportUniqueWarning("unable to read the content of the " + describe(Sec) +
2509                           ": " + toString(ContentOrErr.takeError()));
2510       continue;
2511     }
2512 
2513     W.printHex("FormatVersion", Contents[0]);
2514 
2515     auto ParseAttrubutes = [&]() {
2516       if (Machine == EM_ARM)
2517         return ARMAttributeParser(&W).parse(Contents, support::little);
2518       return RISCVAttributeParser(&W).parse(Contents, support::little);
2519     };
2520 
2521     if (Error E = ParseAttrubutes())
2522       reportUniqueWarning("unable to dump attributes from the " +
2523                           describe(Sec) + ": " + toString(std::move(E)));
2524   }
2525 }
2526 
2527 namespace {
2528 
2529 template <class ELFT> class MipsGOTParser {
2530 public:
2531   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
2532   using Entry = typename ELFT::Addr;
2533   using Entries = ArrayRef<Entry>;
2534 
2535   const bool IsStatic;
2536   const ELFFile<ELFT> &Obj;
2537   const ELFDumper<ELFT> &Dumper;
2538 
2539   MipsGOTParser(const ELFDumper<ELFT> &D);
2540   Error findGOT(Elf_Dyn_Range DynTable, Elf_Sym_Range DynSyms);
2541   Error findPLT(Elf_Dyn_Range DynTable);
2542 
2543   bool isGotEmpty() const { return GotEntries.empty(); }
2544   bool isPltEmpty() const { return PltEntries.empty(); }
2545 
2546   uint64_t getGp() const;
2547 
2548   const Entry *getGotLazyResolver() const;
2549   const Entry *getGotModulePointer() const;
2550   const Entry *getPltLazyResolver() const;
2551   const Entry *getPltModulePointer() const;
2552 
2553   Entries getLocalEntries() const;
2554   Entries getGlobalEntries() const;
2555   Entries getOtherEntries() const;
2556   Entries getPltEntries() const;
2557 
2558   uint64_t getGotAddress(const Entry * E) const;
2559   int64_t getGotOffset(const Entry * E) const;
2560   const Elf_Sym *getGotSym(const Entry *E) const;
2561 
2562   uint64_t getPltAddress(const Entry * E) const;
2563   const Elf_Sym *getPltSym(const Entry *E) const;
2564 
2565   StringRef getPltStrTable() const { return PltStrTable; }
2566   const Elf_Shdr *getPltSymTable() const { return PltSymTable; }
2567 
2568 private:
2569   const Elf_Shdr *GotSec;
2570   size_t LocalNum;
2571   size_t GlobalNum;
2572 
2573   const Elf_Shdr *PltSec;
2574   const Elf_Shdr *PltRelSec;
2575   const Elf_Shdr *PltSymTable;
2576   StringRef FileName;
2577 
2578   Elf_Sym_Range GotDynSyms;
2579   StringRef PltStrTable;
2580 
2581   Entries GotEntries;
2582   Entries PltEntries;
2583 };
2584 
2585 } // end anonymous namespace
2586 
2587 template <class ELFT>
2588 MipsGOTParser<ELFT>::MipsGOTParser(const ELFDumper<ELFT> &D)
2589     : IsStatic(D.dynamic_table().empty()), Obj(D.getElfObject().getELFFile()),
2590       Dumper(D), GotSec(nullptr), LocalNum(0), GlobalNum(0), PltSec(nullptr),
2591       PltRelSec(nullptr), PltSymTable(nullptr),
2592       FileName(D.getElfObject().getFileName()) {}
2593 
2594 template <class ELFT>
2595 Error MipsGOTParser<ELFT>::findGOT(Elf_Dyn_Range DynTable,
2596                                    Elf_Sym_Range DynSyms) {
2597   // See "Global Offset Table" in Chapter 5 in the following document
2598   // for detailed GOT description.
2599   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
2600 
2601   // Find static GOT secton.
2602   if (IsStatic) {
2603     GotSec = Dumper.findSectionByName(".got");
2604     if (!GotSec)
2605       return Error::success();
2606 
2607     ArrayRef<uint8_t> Content =
2608         unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
2609     GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
2610                          Content.size() / sizeof(Entry));
2611     LocalNum = GotEntries.size();
2612     return Error::success();
2613   }
2614 
2615   // Lookup dynamic table tags which define the GOT layout.
2616   Optional<uint64_t> DtPltGot;
2617   Optional<uint64_t> DtLocalGotNum;
2618   Optional<uint64_t> DtGotSym;
2619   for (const auto &Entry : DynTable) {
2620     switch (Entry.getTag()) {
2621     case ELF::DT_PLTGOT:
2622       DtPltGot = Entry.getVal();
2623       break;
2624     case ELF::DT_MIPS_LOCAL_GOTNO:
2625       DtLocalGotNum = Entry.getVal();
2626       break;
2627     case ELF::DT_MIPS_GOTSYM:
2628       DtGotSym = Entry.getVal();
2629       break;
2630     }
2631   }
2632 
2633   if (!DtPltGot && !DtLocalGotNum && !DtGotSym)
2634     return Error::success();
2635 
2636   if (!DtPltGot)
2637     return createError("cannot find PLTGOT dynamic tag");
2638   if (!DtLocalGotNum)
2639     return createError("cannot find MIPS_LOCAL_GOTNO dynamic tag");
2640   if (!DtGotSym)
2641     return createError("cannot find MIPS_GOTSYM dynamic tag");
2642 
2643   size_t DynSymTotal = DynSyms.size();
2644   if (*DtGotSym > DynSymTotal)
2645     return createError("DT_MIPS_GOTSYM value (" + Twine(*DtGotSym) +
2646                        ") exceeds the number of dynamic symbols (" +
2647                        Twine(DynSymTotal) + ")");
2648 
2649   GotSec = findNotEmptySectionByAddress(Obj, FileName, *DtPltGot);
2650   if (!GotSec)
2651     return createError("there is no non-empty GOT section at 0x" +
2652                        Twine::utohexstr(*DtPltGot));
2653 
2654   LocalNum = *DtLocalGotNum;
2655   GlobalNum = DynSymTotal - *DtGotSym;
2656 
2657   ArrayRef<uint8_t> Content =
2658       unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
2659   GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
2660                        Content.size() / sizeof(Entry));
2661   GotDynSyms = DynSyms.drop_front(*DtGotSym);
2662 
2663   return Error::success();
2664 }
2665 
2666 template <class ELFT>
2667 Error MipsGOTParser<ELFT>::findPLT(Elf_Dyn_Range DynTable) {
2668   // Lookup dynamic table tags which define the PLT layout.
2669   Optional<uint64_t> DtMipsPltGot;
2670   Optional<uint64_t> DtJmpRel;
2671   for (const auto &Entry : DynTable) {
2672     switch (Entry.getTag()) {
2673     case ELF::DT_MIPS_PLTGOT:
2674       DtMipsPltGot = Entry.getVal();
2675       break;
2676     case ELF::DT_JMPREL:
2677       DtJmpRel = Entry.getVal();
2678       break;
2679     }
2680   }
2681 
2682   if (!DtMipsPltGot && !DtJmpRel)
2683     return Error::success();
2684 
2685   // Find PLT section.
2686   if (!DtMipsPltGot)
2687     return createError("cannot find MIPS_PLTGOT dynamic tag");
2688   if (!DtJmpRel)
2689     return createError("cannot find JMPREL dynamic tag");
2690 
2691   PltSec = findNotEmptySectionByAddress(Obj, FileName, *DtMipsPltGot);
2692   if (!PltSec)
2693     return createError("there is no non-empty PLTGOT section at 0x" +
2694                        Twine::utohexstr(*DtMipsPltGot));
2695 
2696   PltRelSec = findNotEmptySectionByAddress(Obj, FileName, *DtJmpRel);
2697   if (!PltRelSec)
2698     return createError("there is no non-empty RELPLT section at 0x" +
2699                        Twine::utohexstr(*DtJmpRel));
2700 
2701   if (Expected<ArrayRef<uint8_t>> PltContentOrErr =
2702           Obj.getSectionContents(*PltSec))
2703     PltEntries =
2704         Entries(reinterpret_cast<const Entry *>(PltContentOrErr->data()),
2705                 PltContentOrErr->size() / sizeof(Entry));
2706   else
2707     return createError("unable to read PLTGOT section content: " +
2708                        toString(PltContentOrErr.takeError()));
2709 
2710   if (Expected<const Elf_Shdr *> PltSymTableOrErr =
2711           Obj.getSection(PltRelSec->sh_link))
2712     PltSymTable = *PltSymTableOrErr;
2713   else
2714     return createError("unable to get a symbol table linked to the " +
2715                        describe(Obj, *PltRelSec) + ": " +
2716                        toString(PltSymTableOrErr.takeError()));
2717 
2718   if (Expected<StringRef> StrTabOrErr =
2719           Obj.getStringTableForSymtab(*PltSymTable))
2720     PltStrTable = *StrTabOrErr;
2721   else
2722     return createError("unable to get a string table for the " +
2723                        describe(Obj, *PltSymTable) + ": " +
2724                        toString(StrTabOrErr.takeError()));
2725 
2726   return Error::success();
2727 }
2728 
2729 template <class ELFT> uint64_t MipsGOTParser<ELFT>::getGp() const {
2730   return GotSec->sh_addr + 0x7ff0;
2731 }
2732 
2733 template <class ELFT>
2734 const typename MipsGOTParser<ELFT>::Entry *
2735 MipsGOTParser<ELFT>::getGotLazyResolver() const {
2736   return LocalNum > 0 ? &GotEntries[0] : nullptr;
2737 }
2738 
2739 template <class ELFT>
2740 const typename MipsGOTParser<ELFT>::Entry *
2741 MipsGOTParser<ELFT>::getGotModulePointer() const {
2742   if (LocalNum < 2)
2743     return nullptr;
2744   const Entry &E = GotEntries[1];
2745   if ((E >> (sizeof(Entry) * 8 - 1)) == 0)
2746     return nullptr;
2747   return &E;
2748 }
2749 
2750 template <class ELFT>
2751 typename MipsGOTParser<ELFT>::Entries
2752 MipsGOTParser<ELFT>::getLocalEntries() const {
2753   size_t Skip = getGotModulePointer() ? 2 : 1;
2754   if (LocalNum - Skip <= 0)
2755     return Entries();
2756   return GotEntries.slice(Skip, LocalNum - Skip);
2757 }
2758 
2759 template <class ELFT>
2760 typename MipsGOTParser<ELFT>::Entries
2761 MipsGOTParser<ELFT>::getGlobalEntries() const {
2762   if (GlobalNum == 0)
2763     return Entries();
2764   return GotEntries.slice(LocalNum, GlobalNum);
2765 }
2766 
2767 template <class ELFT>
2768 typename MipsGOTParser<ELFT>::Entries
2769 MipsGOTParser<ELFT>::getOtherEntries() const {
2770   size_t OtherNum = GotEntries.size() - LocalNum - GlobalNum;
2771   if (OtherNum == 0)
2772     return Entries();
2773   return GotEntries.slice(LocalNum + GlobalNum, OtherNum);
2774 }
2775 
2776 template <class ELFT>
2777 uint64_t MipsGOTParser<ELFT>::getGotAddress(const Entry *E) const {
2778   int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
2779   return GotSec->sh_addr + Offset;
2780 }
2781 
2782 template <class ELFT>
2783 int64_t MipsGOTParser<ELFT>::getGotOffset(const Entry *E) const {
2784   int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
2785   return Offset - 0x7ff0;
2786 }
2787 
2788 template <class ELFT>
2789 const typename MipsGOTParser<ELFT>::Elf_Sym *
2790 MipsGOTParser<ELFT>::getGotSym(const Entry *E) const {
2791   int64_t Offset = std::distance(GotEntries.data(), E);
2792   return &GotDynSyms[Offset - LocalNum];
2793 }
2794 
2795 template <class ELFT>
2796 const typename MipsGOTParser<ELFT>::Entry *
2797 MipsGOTParser<ELFT>::getPltLazyResolver() const {
2798   return PltEntries.empty() ? nullptr : &PltEntries[0];
2799 }
2800 
2801 template <class ELFT>
2802 const typename MipsGOTParser<ELFT>::Entry *
2803 MipsGOTParser<ELFT>::getPltModulePointer() const {
2804   return PltEntries.size() < 2 ? nullptr : &PltEntries[1];
2805 }
2806 
2807 template <class ELFT>
2808 typename MipsGOTParser<ELFT>::Entries
2809 MipsGOTParser<ELFT>::getPltEntries() const {
2810   if (PltEntries.size() <= 2)
2811     return Entries();
2812   return PltEntries.slice(2, PltEntries.size() - 2);
2813 }
2814 
2815 template <class ELFT>
2816 uint64_t MipsGOTParser<ELFT>::getPltAddress(const Entry *E) const {
2817   int64_t Offset = std::distance(PltEntries.data(), E) * sizeof(Entry);
2818   return PltSec->sh_addr + Offset;
2819 }
2820 
2821 template <class ELFT>
2822 const typename MipsGOTParser<ELFT>::Elf_Sym *
2823 MipsGOTParser<ELFT>::getPltSym(const Entry *E) const {
2824   int64_t Offset = std::distance(getPltEntries().data(), E);
2825   if (PltRelSec->sh_type == ELF::SHT_REL) {
2826     Elf_Rel_Range Rels = unwrapOrError(FileName, Obj.rels(*PltRelSec));
2827     return unwrapOrError(FileName,
2828                          Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
2829   } else {
2830     Elf_Rela_Range Rels = unwrapOrError(FileName, Obj.relas(*PltRelSec));
2831     return unwrapOrError(FileName,
2832                          Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
2833   }
2834 }
2835 
2836 static const EnumEntry<unsigned> ElfMipsISAExtType[] = {
2837   {"None",                    Mips::AFL_EXT_NONE},
2838   {"Broadcom SB-1",           Mips::AFL_EXT_SB1},
2839   {"Cavium Networks Octeon",  Mips::AFL_EXT_OCTEON},
2840   {"Cavium Networks Octeon2", Mips::AFL_EXT_OCTEON2},
2841   {"Cavium Networks OcteonP", Mips::AFL_EXT_OCTEONP},
2842   {"Cavium Networks Octeon3", Mips::AFL_EXT_OCTEON3},
2843   {"LSI R4010",               Mips::AFL_EXT_4010},
2844   {"Loongson 2E",             Mips::AFL_EXT_LOONGSON_2E},
2845   {"Loongson 2F",             Mips::AFL_EXT_LOONGSON_2F},
2846   {"Loongson 3A",             Mips::AFL_EXT_LOONGSON_3A},
2847   {"MIPS R4650",              Mips::AFL_EXT_4650},
2848   {"MIPS R5900",              Mips::AFL_EXT_5900},
2849   {"MIPS R10000",             Mips::AFL_EXT_10000},
2850   {"NEC VR4100",              Mips::AFL_EXT_4100},
2851   {"NEC VR4111/VR4181",       Mips::AFL_EXT_4111},
2852   {"NEC VR4120",              Mips::AFL_EXT_4120},
2853   {"NEC VR5400",              Mips::AFL_EXT_5400},
2854   {"NEC VR5500",              Mips::AFL_EXT_5500},
2855   {"RMI Xlr",                 Mips::AFL_EXT_XLR},
2856   {"Toshiba R3900",           Mips::AFL_EXT_3900}
2857 };
2858 
2859 static const EnumEntry<unsigned> ElfMipsASEFlags[] = {
2860   {"DSP",                Mips::AFL_ASE_DSP},
2861   {"DSPR2",              Mips::AFL_ASE_DSPR2},
2862   {"Enhanced VA Scheme", Mips::AFL_ASE_EVA},
2863   {"MCU",                Mips::AFL_ASE_MCU},
2864   {"MDMX",               Mips::AFL_ASE_MDMX},
2865   {"MIPS-3D",            Mips::AFL_ASE_MIPS3D},
2866   {"MT",                 Mips::AFL_ASE_MT},
2867   {"SmartMIPS",          Mips::AFL_ASE_SMARTMIPS},
2868   {"VZ",                 Mips::AFL_ASE_VIRT},
2869   {"MSA",                Mips::AFL_ASE_MSA},
2870   {"MIPS16",             Mips::AFL_ASE_MIPS16},
2871   {"microMIPS",          Mips::AFL_ASE_MICROMIPS},
2872   {"XPA",                Mips::AFL_ASE_XPA},
2873   {"CRC",                Mips::AFL_ASE_CRC},
2874   {"GINV",               Mips::AFL_ASE_GINV},
2875 };
2876 
2877 static const EnumEntry<unsigned> ElfMipsFpABIType[] = {
2878   {"Hard or soft float",                  Mips::Val_GNU_MIPS_ABI_FP_ANY},
2879   {"Hard float (double precision)",       Mips::Val_GNU_MIPS_ABI_FP_DOUBLE},
2880   {"Hard float (single precision)",       Mips::Val_GNU_MIPS_ABI_FP_SINGLE},
2881   {"Soft float",                          Mips::Val_GNU_MIPS_ABI_FP_SOFT},
2882   {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)",
2883    Mips::Val_GNU_MIPS_ABI_FP_OLD_64},
2884   {"Hard float (32-bit CPU, Any FPU)",    Mips::Val_GNU_MIPS_ABI_FP_XX},
2885   {"Hard float (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64},
2886   {"Hard float compat (32-bit CPU, 64-bit FPU)",
2887    Mips::Val_GNU_MIPS_ABI_FP_64A}
2888 };
2889 
2890 static const EnumEntry<unsigned> ElfMipsFlags1[] {
2891   {"ODDSPREG", Mips::AFL_FLAGS1_ODDSPREG},
2892 };
2893 
2894 static int getMipsRegisterSize(uint8_t Flag) {
2895   switch (Flag) {
2896   case Mips::AFL_REG_NONE:
2897     return 0;
2898   case Mips::AFL_REG_32:
2899     return 32;
2900   case Mips::AFL_REG_64:
2901     return 64;
2902   case Mips::AFL_REG_128:
2903     return 128;
2904   default:
2905     return -1;
2906   }
2907 }
2908 
2909 template <class ELFT>
2910 static void printMipsReginfoData(ScopedPrinter &W,
2911                                  const Elf_Mips_RegInfo<ELFT> &Reginfo) {
2912   W.printHex("GP", Reginfo.ri_gp_value);
2913   W.printHex("General Mask", Reginfo.ri_gprmask);
2914   W.printHex("Co-Proc Mask0", Reginfo.ri_cprmask[0]);
2915   W.printHex("Co-Proc Mask1", Reginfo.ri_cprmask[1]);
2916   W.printHex("Co-Proc Mask2", Reginfo.ri_cprmask[2]);
2917   W.printHex("Co-Proc Mask3", Reginfo.ri_cprmask[3]);
2918 }
2919 
2920 template <class ELFT> void ELFDumper<ELFT>::printMipsReginfo() {
2921   const Elf_Shdr *RegInfoSec = findSectionByName(".reginfo");
2922   if (!RegInfoSec) {
2923     W.startLine() << "There is no .reginfo section in the file.\n";
2924     return;
2925   }
2926 
2927   Expected<ArrayRef<uint8_t>> ContentsOrErr =
2928       Obj.getSectionContents(*RegInfoSec);
2929   if (!ContentsOrErr) {
2930     this->reportUniqueWarning(
2931         "unable to read the content of the .reginfo section (" +
2932         describe(*RegInfoSec) + "): " + toString(ContentsOrErr.takeError()));
2933     return;
2934   }
2935 
2936   if (ContentsOrErr->size() < sizeof(Elf_Mips_RegInfo<ELFT>)) {
2937     this->reportUniqueWarning("the .reginfo section has an invalid size (0x" +
2938                               Twine::utohexstr(ContentsOrErr->size()) + ")");
2939     return;
2940   }
2941 
2942   DictScope GS(W, "MIPS RegInfo");
2943   printMipsReginfoData(W, *reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(
2944                               ContentsOrErr->data()));
2945 }
2946 
2947 template <class ELFT>
2948 static Expected<const Elf_Mips_Options<ELFT> *>
2949 readMipsOptions(const uint8_t *SecBegin, ArrayRef<uint8_t> &SecData,
2950                 bool &IsSupported) {
2951   if (SecData.size() < sizeof(Elf_Mips_Options<ELFT>))
2952     return createError("the .MIPS.options section has an invalid size (0x" +
2953                        Twine::utohexstr(SecData.size()) + ")");
2954 
2955   const Elf_Mips_Options<ELFT> *O =
2956       reinterpret_cast<const Elf_Mips_Options<ELFT> *>(SecData.data());
2957   const uint8_t Size = O->size;
2958   if (Size > SecData.size()) {
2959     const uint64_t Offset = SecData.data() - SecBegin;
2960     const uint64_t SecSize = Offset + SecData.size();
2961     return createError("a descriptor of size 0x" + Twine::utohexstr(Size) +
2962                        " at offset 0x" + Twine::utohexstr(Offset) +
2963                        " goes past the end of the .MIPS.options "
2964                        "section of size 0x" +
2965                        Twine::utohexstr(SecSize));
2966   }
2967 
2968   IsSupported = O->kind == ODK_REGINFO;
2969   const size_t ExpectedSize =
2970       sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>);
2971 
2972   if (IsSupported)
2973     if (Size < ExpectedSize)
2974       return createError(
2975           "a .MIPS.options entry of kind " +
2976           Twine(getElfMipsOptionsOdkType(O->kind)) +
2977           " has an invalid size (0x" + Twine::utohexstr(Size) +
2978           "), the expected size is 0x" + Twine::utohexstr(ExpectedSize));
2979 
2980   SecData = SecData.drop_front(Size);
2981   return O;
2982 }
2983 
2984 template <class ELFT> void ELFDumper<ELFT>::printMipsOptions() {
2985   const Elf_Shdr *MipsOpts = findSectionByName(".MIPS.options");
2986   if (!MipsOpts) {
2987     W.startLine() << "There is no .MIPS.options section in the file.\n";
2988     return;
2989   }
2990 
2991   DictScope GS(W, "MIPS Options");
2992 
2993   ArrayRef<uint8_t> Data =
2994       unwrapOrError(ObjF.getFileName(), Obj.getSectionContents(*MipsOpts));
2995   const uint8_t *const SecBegin = Data.begin();
2996   while (!Data.empty()) {
2997     bool IsSupported;
2998     Expected<const Elf_Mips_Options<ELFT> *> OptsOrErr =
2999         readMipsOptions<ELFT>(SecBegin, Data, IsSupported);
3000     if (!OptsOrErr) {
3001       reportUniqueWarning(OptsOrErr.takeError());
3002       break;
3003     }
3004 
3005     unsigned Kind = (*OptsOrErr)->kind;
3006     const char *Type = getElfMipsOptionsOdkType(Kind);
3007     if (!IsSupported) {
3008       W.startLine() << "Unsupported MIPS options tag: " << Type << " (" << Kind
3009                     << ")\n";
3010       continue;
3011     }
3012 
3013     DictScope GS(W, Type);
3014     if (Kind == ODK_REGINFO)
3015       printMipsReginfoData(W, (*OptsOrErr)->getRegInfo());
3016     else
3017       llvm_unreachable("unexpected .MIPS.options section descriptor kind");
3018   }
3019 }
3020 
3021 template <class ELFT> void ELFDumper<ELFT>::printStackMap() const {
3022   const Elf_Shdr *StackMapSection = findSectionByName(".llvm_stackmaps");
3023   if (!StackMapSection)
3024     return;
3025 
3026   auto Warn = [&](Error &&E) {
3027     this->reportUniqueWarning("unable to read the stack map from " +
3028                               describe(*StackMapSection) + ": " +
3029                               toString(std::move(E)));
3030   };
3031 
3032   Expected<ArrayRef<uint8_t>> ContentOrErr =
3033       Obj.getSectionContents(*StackMapSection);
3034   if (!ContentOrErr) {
3035     Warn(ContentOrErr.takeError());
3036     return;
3037   }
3038 
3039   if (Error E = StackMapParser<ELFT::TargetEndianness>::validateHeader(
3040           *ContentOrErr)) {
3041     Warn(std::move(E));
3042     return;
3043   }
3044 
3045   prettyPrintStackMap(W, StackMapParser<ELFT::TargetEndianness>(*ContentOrErr));
3046 }
3047 
3048 template <class ELFT>
3049 void ELFDumper<ELFT>::printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
3050                                  const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
3051   Expected<RelSymbol<ELFT>> Target = getRelocationTarget(R, SymTab);
3052   if (!Target)
3053     reportUniqueWarning("unable to print relocation " + Twine(RelIndex) +
3054                         " in " + describe(Sec) + ": " +
3055                         toString(Target.takeError()));
3056   else
3057     printRelRelaReloc(R, *Target);
3058 }
3059 
3060 static inline void printFields(formatted_raw_ostream &OS, StringRef Str1,
3061                                StringRef Str2) {
3062   OS.PadToColumn(2u);
3063   OS << Str1;
3064   OS.PadToColumn(37u);
3065   OS << Str2 << "\n";
3066   OS.flush();
3067 }
3068 
3069 template <class ELFT>
3070 static std::string getSectionHeadersNumString(const ELFFile<ELFT> &Obj,
3071                                               StringRef FileName) {
3072   const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3073   if (ElfHeader.e_shnum != 0)
3074     return to_string(ElfHeader.e_shnum);
3075 
3076   Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3077   if (!ArrOrErr) {
3078     // In this case we can ignore an error, because we have already reported a
3079     // warning about the broken section header table earlier.
3080     consumeError(ArrOrErr.takeError());
3081     return "<?>";
3082   }
3083 
3084   if (ArrOrErr->empty())
3085     return "0";
3086   return "0 (" + to_string((*ArrOrErr)[0].sh_size) + ")";
3087 }
3088 
3089 template <class ELFT>
3090 static std::string getSectionHeaderTableIndexString(const ELFFile<ELFT> &Obj,
3091                                                     StringRef FileName) {
3092   const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3093   if (ElfHeader.e_shstrndx != SHN_XINDEX)
3094     return to_string(ElfHeader.e_shstrndx);
3095 
3096   Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3097   if (!ArrOrErr) {
3098     // In this case we can ignore an error, because we have already reported a
3099     // warning about the broken section header table earlier.
3100     consumeError(ArrOrErr.takeError());
3101     return "<?>";
3102   }
3103 
3104   if (ArrOrErr->empty())
3105     return "65535 (corrupt: out of range)";
3106   return to_string(ElfHeader.e_shstrndx) + " (" +
3107          to_string((*ArrOrErr)[0].sh_link) + ")";
3108 }
3109 
3110 static const EnumEntry<unsigned> *getObjectFileEnumEntry(unsigned Type) {
3111   auto It = llvm::find_if(ElfObjectFileType, [&](const EnumEntry<unsigned> &E) {
3112     return E.Value == Type;
3113   });
3114   if (It != makeArrayRef(ElfObjectFileType).end())
3115     return It;
3116   return nullptr;
3117 }
3118 
3119 template <class ELFT> void GNUELFDumper<ELFT>::printFileHeaders() {
3120   const Elf_Ehdr &e = this->Obj.getHeader();
3121   OS << "ELF Header:\n";
3122   OS << "  Magic:  ";
3123   std::string Str;
3124   for (int i = 0; i < ELF::EI_NIDENT; i++)
3125     OS << format(" %02x", static_cast<int>(e.e_ident[i]));
3126   OS << "\n";
3127   Str = printEnum(e.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass));
3128   printFields(OS, "Class:", Str);
3129   Str = printEnum(e.e_ident[ELF::EI_DATA], makeArrayRef(ElfDataEncoding));
3130   printFields(OS, "Data:", Str);
3131   OS.PadToColumn(2u);
3132   OS << "Version:";
3133   OS.PadToColumn(37u);
3134   OS << to_hexString(e.e_ident[ELF::EI_VERSION]);
3135   if (e.e_version == ELF::EV_CURRENT)
3136     OS << " (current)";
3137   OS << "\n";
3138   Str = printEnum(e.e_ident[ELF::EI_OSABI], makeArrayRef(ElfOSABI));
3139   printFields(OS, "OS/ABI:", Str);
3140   printFields(OS,
3141               "ABI Version:", std::to_string(e.e_ident[ELF::EI_ABIVERSION]));
3142 
3143   if (const EnumEntry<unsigned> *E = getObjectFileEnumEntry(e.e_type)) {
3144     Str = E->AltName.str();
3145   } else {
3146     if (e.e_type >= ET_LOPROC)
3147       Str = "Processor Specific: (" + to_hexString(e.e_type, false) + ")";
3148     else if (e.e_type >= ET_LOOS)
3149       Str = "OS Specific: (" + to_hexString(e.e_type, false) + ")";
3150     else
3151       Str = "<unknown>: " + to_hexString(e.e_type, false);
3152   }
3153   printFields(OS, "Type:", Str);
3154 
3155   Str = printEnum(e.e_machine, makeArrayRef(ElfMachineType));
3156   printFields(OS, "Machine:", Str);
3157   Str = "0x" + to_hexString(e.e_version);
3158   printFields(OS, "Version:", Str);
3159   Str = "0x" + to_hexString(e.e_entry);
3160   printFields(OS, "Entry point address:", Str);
3161   Str = to_string(e.e_phoff) + " (bytes into file)";
3162   printFields(OS, "Start of program headers:", Str);
3163   Str = to_string(e.e_shoff) + " (bytes into file)";
3164   printFields(OS, "Start of section headers:", Str);
3165   std::string ElfFlags;
3166   if (e.e_machine == EM_MIPS)
3167     ElfFlags =
3168         printFlags(e.e_flags, makeArrayRef(ElfHeaderMipsFlags),
3169                    unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
3170                    unsigned(ELF::EF_MIPS_MACH));
3171   else if (e.e_machine == EM_RISCV)
3172     ElfFlags = printFlags(e.e_flags, makeArrayRef(ElfHeaderRISCVFlags));
3173   Str = "0x" + to_hexString(e.e_flags);
3174   if (!ElfFlags.empty())
3175     Str = Str + ", " + ElfFlags;
3176   printFields(OS, "Flags:", Str);
3177   Str = to_string(e.e_ehsize) + " (bytes)";
3178   printFields(OS, "Size of this header:", Str);
3179   Str = to_string(e.e_phentsize) + " (bytes)";
3180   printFields(OS, "Size of program headers:", Str);
3181   Str = to_string(e.e_phnum);
3182   printFields(OS, "Number of program headers:", Str);
3183   Str = to_string(e.e_shentsize) + " (bytes)";
3184   printFields(OS, "Size of section headers:", Str);
3185   Str = getSectionHeadersNumString(this->Obj, this->FileName);
3186   printFields(OS, "Number of section headers:", Str);
3187   Str = getSectionHeaderTableIndexString(this->Obj, this->FileName);
3188   printFields(OS, "Section header string table index:", Str);
3189 }
3190 
3191 template <class ELFT> std::vector<GroupSection> ELFDumper<ELFT>::getGroups() {
3192   auto GetSignature = [&](const Elf_Sym &Sym, unsigned SymNdx,
3193                           const Elf_Shdr &Symtab) -> StringRef {
3194     Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(Symtab);
3195     if (!StrTableOrErr) {
3196       reportUniqueWarning("unable to get the string table for " +
3197                           describe(Symtab) + ": " +
3198                           toString(StrTableOrErr.takeError()));
3199       return "<?>";
3200     }
3201 
3202     StringRef Strings = *StrTableOrErr;
3203     if (Sym.st_name >= Strings.size()) {
3204       reportUniqueWarning("unable to get the name of the symbol with index " +
3205                           Twine(SymNdx) + ": st_name (0x" +
3206                           Twine::utohexstr(Sym.st_name) +
3207                           ") is past the end of the string table of size 0x" +
3208                           Twine::utohexstr(Strings.size()));
3209       return "<?>";
3210     }
3211 
3212     return StrTableOrErr->data() + Sym.st_name;
3213   };
3214 
3215   std::vector<GroupSection> Ret;
3216   uint64_t I = 0;
3217   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
3218     ++I;
3219     if (Sec.sh_type != ELF::SHT_GROUP)
3220       continue;
3221 
3222     StringRef Signature = "<?>";
3223     if (Expected<const Elf_Shdr *> SymtabOrErr = Obj.getSection(Sec.sh_link)) {
3224       if (Expected<const Elf_Sym *> SymOrErr =
3225               Obj.template getEntry<Elf_Sym>(**SymtabOrErr, Sec.sh_info))
3226         Signature = GetSignature(**SymOrErr, Sec.sh_info, **SymtabOrErr);
3227       else
3228         reportUniqueWarning("unable to get the signature symbol for " +
3229                             describe(Sec) + ": " +
3230                             toString(SymOrErr.takeError()));
3231     } else {
3232       reportUniqueWarning("unable to get the symbol table for " +
3233                           describe(Sec) + ": " +
3234                           toString(SymtabOrErr.takeError()));
3235     }
3236 
3237     ArrayRef<Elf_Word> Data;
3238     if (Expected<ArrayRef<Elf_Word>> ContentsOrErr =
3239             Obj.template getSectionContentsAsArray<Elf_Word>(Sec)) {
3240       if (ContentsOrErr->empty())
3241         reportUniqueWarning("unable to read the section group flag from the " +
3242                             describe(Sec) + ": the section is empty");
3243       else
3244         Data = *ContentsOrErr;
3245     } else {
3246       reportUniqueWarning("unable to get the content of the " + describe(Sec) +
3247                           ": " + toString(ContentsOrErr.takeError()));
3248     }
3249 
3250     Ret.push_back({getPrintableSectionName(Sec),
3251                    maybeDemangle(Signature),
3252                    Sec.sh_name,
3253                    I - 1,
3254                    Sec.sh_link,
3255                    Sec.sh_info,
3256                    Data.empty() ? Elf_Word(0) : Data[0],
3257                    {}});
3258 
3259     if (Data.empty())
3260       continue;
3261 
3262     std::vector<GroupMember> &GM = Ret.back().Members;
3263     for (uint32_t Ndx : Data.slice(1)) {
3264       if (Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(Ndx)) {
3265         GM.push_back({getPrintableSectionName(**SecOrErr), Ndx});
3266       } else {
3267         reportUniqueWarning("unable to get the section with index " +
3268                             Twine(Ndx) + " when dumping the " + describe(Sec) +
3269                             ": " + toString(SecOrErr.takeError()));
3270         GM.push_back({"<?>", Ndx});
3271       }
3272     }
3273   }
3274   return Ret;
3275 }
3276 
3277 static DenseMap<uint64_t, const GroupSection *>
3278 mapSectionsToGroups(ArrayRef<GroupSection> Groups) {
3279   DenseMap<uint64_t, const GroupSection *> Ret;
3280   for (const GroupSection &G : Groups)
3281     for (const GroupMember &GM : G.Members)
3282       Ret.insert({GM.Index, &G});
3283   return Ret;
3284 }
3285 
3286 template <class ELFT> void GNUELFDumper<ELFT>::printGroupSections() {
3287   std::vector<GroupSection> V = this->getGroups();
3288   DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
3289   for (const GroupSection &G : V) {
3290     OS << "\n"
3291        << getGroupType(G.Type) << " group section ["
3292        << format_decimal(G.Index, 5) << "] `" << G.Name << "' [" << G.Signature
3293        << "] contains " << G.Members.size() << " sections:\n"
3294        << "   [Index]    Name\n";
3295     for (const GroupMember &GM : G.Members) {
3296       const GroupSection *MainGroup = Map[GM.Index];
3297       if (MainGroup != &G)
3298         this->reportUniqueWarning(
3299             "section with index " + Twine(GM.Index) +
3300             ", included in the group section with index " +
3301             Twine(MainGroup->Index) +
3302             ", was also found in the group section with index " +
3303             Twine(G.Index));
3304       OS << "   [" << format_decimal(GM.Index, 5) << "]   " << GM.Name << "\n";
3305     }
3306   }
3307 
3308   if (V.empty())
3309     OS << "There are no section groups in this file.\n";
3310 }
3311 
3312 template <class ELFT>
3313 void GNUELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
3314   OS << to_string(format_hex_no_prefix(R, ELFT::Is64Bits ? 16 : 8)) << "\n";
3315 }
3316 
3317 template <class ELFT>
3318 void GNUELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
3319                                            const RelSymbol<ELFT> &RelSym) {
3320   // First two fields are bit width dependent. The rest of them are fixed width.
3321   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3322   Field Fields[5] = {0, 10 + Bias, 19 + 2 * Bias, 42 + 2 * Bias, 53 + 2 * Bias};
3323   unsigned Width = ELFT::Is64Bits ? 16 : 8;
3324 
3325   Fields[0].Str = to_string(format_hex_no_prefix(R.Offset, Width));
3326   Fields[1].Str = to_string(format_hex_no_prefix(R.Info, Width));
3327 
3328   SmallString<32> RelocName;
3329   this->Obj.getRelocationTypeName(R.Type, RelocName);
3330   Fields[2].Str = RelocName.c_str();
3331 
3332   if (RelSym.Sym)
3333     Fields[3].Str =
3334         to_string(format_hex_no_prefix(RelSym.Sym->getValue(), Width));
3335 
3336   Fields[4].Str = std::string(RelSym.Name);
3337   for (const Field &F : Fields)
3338     printField(F);
3339 
3340   std::string Addend;
3341   if (Optional<int64_t> A = R.Addend) {
3342     int64_t RelAddend = *A;
3343     if (!RelSym.Name.empty()) {
3344       if (RelAddend < 0) {
3345         Addend = " - ";
3346         RelAddend = std::abs(RelAddend);
3347       } else {
3348         Addend = " + ";
3349       }
3350     }
3351     Addend += to_hexString(RelAddend, false);
3352   }
3353   OS << Addend << "\n";
3354 }
3355 
3356 template <class ELFT>
3357 static void printRelocHeaderFields(formatted_raw_ostream &OS, unsigned SType) {
3358   bool IsRela = SType == ELF::SHT_RELA || SType == ELF::SHT_ANDROID_RELA;
3359   bool IsRelr = SType == ELF::SHT_RELR || SType == ELF::SHT_ANDROID_RELR;
3360   if (ELFT::Is64Bits)
3361     OS << "    ";
3362   else
3363     OS << " ";
3364   if (IsRelr && opts::RawRelr)
3365     OS << "Data  ";
3366   else
3367     OS << "Offset";
3368   if (ELFT::Is64Bits)
3369     OS << "             Info             Type"
3370        << "               Symbol's Value  Symbol's Name";
3371   else
3372     OS << "     Info    Type                Sym. Value  Symbol's Name";
3373   if (IsRela)
3374     OS << " + Addend";
3375   OS << "\n";
3376 }
3377 
3378 template <class ELFT>
3379 void GNUELFDumper<ELFT>::printDynamicRelocHeader(unsigned Type, StringRef Name,
3380                                                  const DynRegionInfo &Reg) {
3381   uint64_t Offset = Reg.Addr - this->Obj.base();
3382   OS << "\n'" << Name.str().c_str() << "' relocation section at offset 0x"
3383      << to_hexString(Offset, false) << " contains " << Reg.Size << " bytes:\n";
3384   printRelocHeaderFields<ELFT>(OS, Type);
3385 }
3386 
3387 template <class ELFT>
3388 static bool isRelocationSec(const typename ELFT::Shdr &Sec) {
3389   return Sec.sh_type == ELF::SHT_REL || Sec.sh_type == ELF::SHT_RELA ||
3390          Sec.sh_type == ELF::SHT_RELR || Sec.sh_type == ELF::SHT_ANDROID_REL ||
3391          Sec.sh_type == ELF::SHT_ANDROID_RELA ||
3392          Sec.sh_type == ELF::SHT_ANDROID_RELR;
3393 }
3394 
3395 template <class ELFT> void GNUELFDumper<ELFT>::printRelocations() {
3396   auto GetEntriesNum = [&](const Elf_Shdr &Sec) -> Expected<size_t> {
3397     // Android's packed relocation section needs to be unpacked first
3398     // to get the actual number of entries.
3399     if (Sec.sh_type == ELF::SHT_ANDROID_REL ||
3400         Sec.sh_type == ELF::SHT_ANDROID_RELA) {
3401       Expected<std::vector<typename ELFT::Rela>> RelasOrErr =
3402           this->Obj.android_relas(Sec);
3403       if (!RelasOrErr)
3404         return RelasOrErr.takeError();
3405       return RelasOrErr->size();
3406     }
3407 
3408     if (!opts::RawRelr && (Sec.sh_type == ELF::SHT_RELR ||
3409                            Sec.sh_type == ELF::SHT_ANDROID_RELR)) {
3410       Expected<Elf_Relr_Range> RelrsOrErr = this->Obj.relrs(Sec);
3411       if (!RelrsOrErr)
3412         return RelrsOrErr.takeError();
3413       return this->Obj.decode_relrs(*RelrsOrErr).size();
3414     }
3415 
3416     return Sec.getEntityCount();
3417   };
3418 
3419   bool HasRelocSections = false;
3420   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
3421     if (!isRelocationSec<ELFT>(Sec))
3422       continue;
3423     HasRelocSections = true;
3424 
3425     std::string EntriesNum = "<?>";
3426     if (Expected<size_t> NumOrErr = GetEntriesNum(Sec))
3427       EntriesNum = std::to_string(*NumOrErr);
3428     else
3429       this->reportUniqueWarning("unable to get the number of relocations in " +
3430                                 this->describe(Sec) + ": " +
3431                                 toString(NumOrErr.takeError()));
3432 
3433     uintX_t Offset = Sec.sh_offset;
3434     StringRef Name = this->getPrintableSectionName(Sec);
3435     OS << "\nRelocation section '" << Name << "' at offset 0x"
3436        << to_hexString(Offset, false) << " contains " << EntriesNum
3437        << " entries:\n";
3438     printRelocHeaderFields<ELFT>(OS, Sec.sh_type);
3439     this->printRelocationsHelper(Sec);
3440   }
3441   if (!HasRelocSections)
3442     OS << "\nThere are no relocations in this file.\n";
3443 }
3444 
3445 // Print the offset of a particular section from anyone of the ranges:
3446 // [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER].
3447 // If 'Type' does not fall within any of those ranges, then a string is
3448 // returned as '<unknown>' followed by the type value.
3449 static std::string getSectionTypeOffsetString(unsigned Type) {
3450   if (Type >= SHT_LOOS && Type <= SHT_HIOS)
3451     return "LOOS+0x" + to_hexString(Type - SHT_LOOS);
3452   else if (Type >= SHT_LOPROC && Type <= SHT_HIPROC)
3453     return "LOPROC+0x" + to_hexString(Type - SHT_LOPROC);
3454   else if (Type >= SHT_LOUSER && Type <= SHT_HIUSER)
3455     return "LOUSER+0x" + to_hexString(Type - SHT_LOUSER);
3456   return "0x" + to_hexString(Type) + ": <unknown>";
3457 }
3458 
3459 static std::string getSectionTypeString(unsigned Machine, unsigned Type) {
3460   StringRef Name = getELFSectionTypeName(Machine, Type);
3461 
3462   // Handle SHT_GNU_* type names.
3463   if (Name.startswith("SHT_GNU_")) {
3464     if (Name == "SHT_GNU_HASH")
3465       return "GNU_HASH";
3466     // E.g. SHT_GNU_verneed -> VERNEED.
3467     return Name.drop_front(8).upper();
3468   }
3469 
3470   if (Name == "SHT_SYMTAB_SHNDX")
3471     return "SYMTAB SECTION INDICES";
3472 
3473   if (Name.startswith("SHT_"))
3474     return Name.drop_front(4).str();
3475   return getSectionTypeOffsetString(Type);
3476 }
3477 
3478 static void printSectionDescription(formatted_raw_ostream &OS,
3479                                     unsigned EMachine) {
3480   OS << "Key to Flags:\n";
3481   OS << "  W (write), A (alloc), X (execute), M (merge), S (strings), I "
3482         "(info),\n";
3483   OS << "  L (link order), O (extra OS processing required), G (group), T "
3484         "(TLS),\n";
3485   OS << "  C (compressed), x (unknown), o (OS specific), E (exclude),\n";
3486 
3487   if (EMachine == EM_X86_64)
3488     OS << "  l (large), ";
3489   else if (EMachine == EM_ARM)
3490     OS << "  y (purecode), ";
3491   else
3492     OS << "  ";
3493 
3494   OS << "p (processor specific)\n";
3495 }
3496 
3497 template <class ELFT> void GNUELFDumper<ELFT>::printSectionHeaders() {
3498   unsigned Bias = ELFT::Is64Bits ? 0 : 8;
3499   ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
3500   OS << "There are " << to_string(Sections.size())
3501      << " section headers, starting at offset "
3502      << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n";
3503   OS << "Section Headers:\n";
3504   Field Fields[11] = {
3505       {"[Nr]", 2},        {"Name", 7},        {"Type", 25},
3506       {"Address", 41},    {"Off", 58 - Bias}, {"Size", 65 - Bias},
3507       {"ES", 72 - Bias},  {"Flg", 75 - Bias}, {"Lk", 79 - Bias},
3508       {"Inf", 82 - Bias}, {"Al", 86 - Bias}};
3509   for (const Field &F : Fields)
3510     printField(F);
3511   OS << "\n";
3512 
3513   StringRef SecStrTable;
3514   if (Expected<StringRef> SecStrTableOrErr =
3515           this->Obj.getSectionStringTable(Sections, this->WarningHandler))
3516     SecStrTable = *SecStrTableOrErr;
3517   else
3518     this->reportUniqueWarning(SecStrTableOrErr.takeError());
3519 
3520   size_t SectionIndex = 0;
3521   for (const Elf_Shdr &Sec : Sections) {
3522     Fields[0].Str = to_string(SectionIndex);
3523     if (SecStrTable.empty())
3524       Fields[1].Str = "<no-strings>";
3525     else
3526       Fields[1].Str = std::string(unwrapOrError<StringRef>(
3527           this->FileName, this->Obj.getSectionName(Sec, SecStrTable)));
3528     Fields[2].Str =
3529         getSectionTypeString(this->Obj.getHeader().e_machine, Sec.sh_type);
3530     Fields[3].Str =
3531         to_string(format_hex_no_prefix(Sec.sh_addr, ELFT::Is64Bits ? 16 : 8));
3532     Fields[4].Str = to_string(format_hex_no_prefix(Sec.sh_offset, 6));
3533     Fields[5].Str = to_string(format_hex_no_prefix(Sec.sh_size, 6));
3534     Fields[6].Str = to_string(format_hex_no_prefix(Sec.sh_entsize, 2));
3535     Fields[7].Str = getGNUFlags(this->Obj.getHeader().e_machine, Sec.sh_flags);
3536     Fields[8].Str = to_string(Sec.sh_link);
3537     Fields[9].Str = to_string(Sec.sh_info);
3538     Fields[10].Str = to_string(Sec.sh_addralign);
3539 
3540     OS.PadToColumn(Fields[0].Column);
3541     OS << "[" << right_justify(Fields[0].Str, 2) << "]";
3542     for (int i = 1; i < 7; i++)
3543       printField(Fields[i]);
3544     OS.PadToColumn(Fields[7].Column);
3545     OS << right_justify(Fields[7].Str, 3);
3546     OS.PadToColumn(Fields[8].Column);
3547     OS << right_justify(Fields[8].Str, 2);
3548     OS.PadToColumn(Fields[9].Column);
3549     OS << right_justify(Fields[9].Str, 3);
3550     OS.PadToColumn(Fields[10].Column);
3551     OS << right_justify(Fields[10].Str, 2);
3552     OS << "\n";
3553     ++SectionIndex;
3554   }
3555   printSectionDescription(OS, this->Obj.getHeader().e_machine);
3556 }
3557 
3558 template <class ELFT>
3559 void GNUELFDumper<ELFT>::printSymtabMessage(const Elf_Shdr *Symtab,
3560                                             size_t Entries,
3561                                             bool NonVisibilityBitsUsed) const {
3562   StringRef Name;
3563   if (Symtab)
3564     Name = this->getPrintableSectionName(*Symtab);
3565   if (!Name.empty())
3566     OS << "\nSymbol table '" << Name << "'";
3567   else
3568     OS << "\nSymbol table for image";
3569   OS << " contains " << Entries << " entries:\n";
3570 
3571   if (ELFT::Is64Bits)
3572     OS << "   Num:    Value          Size Type    Bind   Vis";
3573   else
3574     OS << "   Num:    Value  Size Type    Bind   Vis";
3575 
3576   if (NonVisibilityBitsUsed)
3577     OS << "             ";
3578   OS << "       Ndx Name\n";
3579 }
3580 
3581 template <class ELFT>
3582 std::string
3583 GNUELFDumper<ELFT>::getSymbolSectionNdx(const Elf_Sym &Symbol,
3584                                         unsigned SymIndex,
3585                                         DataRegion<Elf_Word> ShndxTable) const {
3586   unsigned SectionIndex = Symbol.st_shndx;
3587   switch (SectionIndex) {
3588   case ELF::SHN_UNDEF:
3589     return "UND";
3590   case ELF::SHN_ABS:
3591     return "ABS";
3592   case ELF::SHN_COMMON:
3593     return "COM";
3594   case ELF::SHN_XINDEX: {
3595     Expected<uint32_t> IndexOrErr =
3596         object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, ShndxTable);
3597     if (!IndexOrErr) {
3598       assert(Symbol.st_shndx == SHN_XINDEX &&
3599              "getExtendedSymbolTableIndex should only fail due to an invalid "
3600              "SHT_SYMTAB_SHNDX table/reference");
3601       this->reportUniqueWarning(IndexOrErr.takeError());
3602       return "RSV[0xffff]";
3603     }
3604     return to_string(format_decimal(*IndexOrErr, 3));
3605   }
3606   default:
3607     // Find if:
3608     // Processor specific
3609     if (SectionIndex >= ELF::SHN_LOPROC && SectionIndex <= ELF::SHN_HIPROC)
3610       return std::string("PRC[0x") +
3611              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3612     // OS specific
3613     if (SectionIndex >= ELF::SHN_LOOS && SectionIndex <= ELF::SHN_HIOS)
3614       return std::string("OS[0x") +
3615              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3616     // Architecture reserved:
3617     if (SectionIndex >= ELF::SHN_LORESERVE &&
3618         SectionIndex <= ELF::SHN_HIRESERVE)
3619       return std::string("RSV[0x") +
3620              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3621     // A normal section with an index
3622     return to_string(format_decimal(SectionIndex, 3));
3623   }
3624 }
3625 
3626 template <class ELFT>
3627 void GNUELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
3628                                      DataRegion<Elf_Word> ShndxTable,
3629                                      Optional<StringRef> StrTable,
3630                                      bool IsDynamic,
3631                                      bool NonVisibilityBitsUsed) const {
3632   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3633   Field Fields[8] = {0,         8,         17 + Bias, 23 + Bias,
3634                      31 + Bias, 38 + Bias, 48 + Bias, 51 + Bias};
3635   Fields[0].Str = to_string(format_decimal(SymIndex, 6)) + ":";
3636   Fields[1].Str =
3637       to_string(format_hex_no_prefix(Symbol.st_value, ELFT::Is64Bits ? 16 : 8));
3638   Fields[2].Str = to_string(format_decimal(Symbol.st_size, 5));
3639 
3640   unsigned char SymbolType = Symbol.getType();
3641   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
3642       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
3643     Fields[3].Str = printEnum(SymbolType, makeArrayRef(AMDGPUSymbolTypes));
3644   else
3645     Fields[3].Str = printEnum(SymbolType, makeArrayRef(ElfSymbolTypes));
3646 
3647   Fields[4].Str =
3648       printEnum(Symbol.getBinding(), makeArrayRef(ElfSymbolBindings));
3649   Fields[5].Str =
3650       printEnum(Symbol.getVisibility(), makeArrayRef(ElfSymbolVisibilities));
3651 
3652   if (Symbol.st_other & ~0x3) {
3653     if (this->Obj.getHeader().e_machine == ELF::EM_AARCH64) {
3654       uint8_t Other = Symbol.st_other & ~0x3;
3655       if (Other & STO_AARCH64_VARIANT_PCS) {
3656         Other &= ~STO_AARCH64_VARIANT_PCS;
3657         Fields[5].Str += " [VARIANT_PCS";
3658         if (Other != 0)
3659           Fields[5].Str.append(" | " + to_hexString(Other, false));
3660         Fields[5].Str.append("]");
3661       }
3662     } else {
3663       Fields[5].Str +=
3664           " [<other: " + to_string(format_hex(Symbol.st_other, 2)) + ">]";
3665     }
3666   }
3667 
3668   Fields[6].Column += NonVisibilityBitsUsed ? 13 : 0;
3669   Fields[6].Str = getSymbolSectionNdx(Symbol, SymIndex, ShndxTable);
3670 
3671   Fields[7].Str = this->getFullSymbolName(Symbol, SymIndex, ShndxTable,
3672                                           StrTable, IsDynamic);
3673   for (const Field &Entry : Fields)
3674     printField(Entry);
3675   OS << "\n";
3676 }
3677 
3678 template <class ELFT>
3679 void GNUELFDumper<ELFT>::printHashedSymbol(const Elf_Sym *Symbol,
3680                                            unsigned SymIndex,
3681                                            DataRegion<Elf_Word> ShndxTable,
3682                                            StringRef StrTable,
3683                                            uint32_t Bucket) {
3684   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3685   Field Fields[9] = {0,         6,         11,        20 + Bias, 25 + Bias,
3686                      34 + Bias, 41 + Bias, 49 + Bias, 53 + Bias};
3687   Fields[0].Str = to_string(format_decimal(SymIndex, 5));
3688   Fields[1].Str = to_string(format_decimal(Bucket, 3)) + ":";
3689 
3690   Fields[2].Str = to_string(
3691       format_hex_no_prefix(Symbol->st_value, ELFT::Is64Bits ? 16 : 8));
3692   Fields[3].Str = to_string(format_decimal(Symbol->st_size, 5));
3693 
3694   unsigned char SymbolType = Symbol->getType();
3695   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
3696       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
3697     Fields[4].Str = printEnum(SymbolType, makeArrayRef(AMDGPUSymbolTypes));
3698   else
3699     Fields[4].Str = printEnum(SymbolType, makeArrayRef(ElfSymbolTypes));
3700 
3701   Fields[5].Str =
3702       printEnum(Symbol->getBinding(), makeArrayRef(ElfSymbolBindings));
3703   Fields[6].Str =
3704       printEnum(Symbol->getVisibility(), makeArrayRef(ElfSymbolVisibilities));
3705   Fields[7].Str = getSymbolSectionNdx(*Symbol, SymIndex, ShndxTable);
3706   Fields[8].Str =
3707       this->getFullSymbolName(*Symbol, SymIndex, ShndxTable, StrTable, true);
3708 
3709   for (const Field &Entry : Fields)
3710     printField(Entry);
3711   OS << "\n";
3712 }
3713 
3714 template <class ELFT>
3715 void GNUELFDumper<ELFT>::printSymbols(bool PrintSymbols,
3716                                       bool PrintDynamicSymbols) {
3717   if (!PrintSymbols && !PrintDynamicSymbols)
3718     return;
3719   // GNU readelf prints both the .dynsym and .symtab with --symbols.
3720   this->printSymbolsHelper(true);
3721   if (PrintSymbols)
3722     this->printSymbolsHelper(false);
3723 }
3724 
3725 template <class ELFT>
3726 void GNUELFDumper<ELFT>::printHashTableSymbols(const Elf_Hash &SysVHash) {
3727   if (this->DynamicStringTable.empty())
3728     return;
3729 
3730   if (ELFT::Is64Bits)
3731     OS << "  Num Buc:    Value          Size   Type   Bind Vis      Ndx Name";
3732   else
3733     OS << "  Num Buc:    Value  Size   Type   Bind Vis      Ndx Name";
3734   OS << "\n";
3735 
3736   Elf_Sym_Range DynSyms = this->dynamic_symbols();
3737   const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
3738   if (!FirstSym) {
3739     this->reportUniqueWarning(
3740         Twine("unable to print symbols for the .hash table: the "
3741               "dynamic symbol table ") +
3742         (this->DynSymRegion ? "is empty" : "was not found"));
3743     return;
3744   }
3745 
3746   DataRegion<Elf_Word> ShndxTable(
3747       (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
3748   auto Buckets = SysVHash.buckets();
3749   auto Chains = SysVHash.chains();
3750   for (uint32_t Buc = 0; Buc < SysVHash.nbucket; Buc++) {
3751     if (Buckets[Buc] == ELF::STN_UNDEF)
3752       continue;
3753     std::vector<bool> Visited(SysVHash.nchain);
3754     for (uint32_t Ch = Buckets[Buc]; Ch < SysVHash.nchain; Ch = Chains[Ch]) {
3755       if (Ch == ELF::STN_UNDEF)
3756         break;
3757 
3758       if (Visited[Ch]) {
3759         this->reportUniqueWarning(".hash section is invalid: bucket " +
3760                                   Twine(Ch) +
3761                                   ": a cycle was detected in the linked chain");
3762         break;
3763       }
3764 
3765       printHashedSymbol(FirstSym + Ch, Ch, ShndxTable, this->DynamicStringTable,
3766                         Buc);
3767       Visited[Ch] = true;
3768     }
3769   }
3770 }
3771 
3772 template <class ELFT>
3773 void GNUELFDumper<ELFT>::printGnuHashTableSymbols(const Elf_GnuHash &GnuHash) {
3774   if (this->DynamicStringTable.empty())
3775     return;
3776 
3777   Elf_Sym_Range DynSyms = this->dynamic_symbols();
3778   const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
3779   if (!FirstSym) {
3780     this->reportUniqueWarning(
3781         Twine("unable to print symbols for the .gnu.hash table: the "
3782               "dynamic symbol table ") +
3783         (this->DynSymRegion ? "is empty" : "was not found"));
3784     return;
3785   }
3786 
3787   auto GetSymbol = [&](uint64_t SymIndex,
3788                        uint64_t SymsTotal) -> const Elf_Sym * {
3789     if (SymIndex >= SymsTotal) {
3790       this->reportUniqueWarning(
3791           "unable to print hashed symbol with index " + Twine(SymIndex) +
3792           ", which is greater than or equal to the number of dynamic symbols "
3793           "(" +
3794           Twine::utohexstr(SymsTotal) + ")");
3795       return nullptr;
3796     }
3797     return FirstSym + SymIndex;
3798   };
3799 
3800   Expected<ArrayRef<Elf_Word>> ValuesOrErr =
3801       getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHash);
3802   ArrayRef<Elf_Word> Values;
3803   if (!ValuesOrErr)
3804     this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH "
3805                               "section: " +
3806                               toString(ValuesOrErr.takeError()));
3807   else
3808     Values = *ValuesOrErr;
3809 
3810   DataRegion<Elf_Word> ShndxTable(
3811       (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
3812   ArrayRef<Elf_Word> Buckets = GnuHash.buckets();
3813   for (uint32_t Buc = 0; Buc < GnuHash.nbuckets; Buc++) {
3814     if (Buckets[Buc] == ELF::STN_UNDEF)
3815       continue;
3816     uint32_t Index = Buckets[Buc];
3817     // Print whole chain.
3818     while (true) {
3819       uint32_t SymIndex = Index++;
3820       if (const Elf_Sym *Sym = GetSymbol(SymIndex, DynSyms.size()))
3821         printHashedSymbol(Sym, SymIndex, ShndxTable, this->DynamicStringTable,
3822                           Buc);
3823       else
3824         break;
3825 
3826       if (SymIndex < GnuHash.symndx) {
3827         this->reportUniqueWarning(
3828             "unable to read the hash value for symbol with index " +
3829             Twine(SymIndex) +
3830             ", which is less than the index of the first hashed symbol (" +
3831             Twine(GnuHash.symndx) + ")");
3832         break;
3833       }
3834 
3835        // Chain ends at symbol with stopper bit.
3836       if ((Values[SymIndex - GnuHash.symndx] & 1) == 1)
3837         break;
3838     }
3839   }
3840 }
3841 
3842 template <class ELFT> void GNUELFDumper<ELFT>::printHashSymbols() {
3843   if (this->HashTable) {
3844     OS << "\n Symbol table of .hash for image:\n";
3845     if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
3846       this->reportUniqueWarning(std::move(E));
3847     else
3848       printHashTableSymbols(*this->HashTable);
3849   }
3850 
3851   // Try printing the .gnu.hash table.
3852   if (this->GnuHashTable) {
3853     OS << "\n Symbol table of .gnu.hash for image:\n";
3854     if (ELFT::Is64Bits)
3855       OS << "  Num Buc:    Value          Size   Type   Bind Vis      Ndx Name";
3856     else
3857       OS << "  Num Buc:    Value  Size   Type   Bind Vis      Ndx Name";
3858     OS << "\n";
3859 
3860     if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
3861       this->reportUniqueWarning(std::move(E));
3862     else
3863       printGnuHashTableSymbols(*this->GnuHashTable);
3864   }
3865 }
3866 
3867 template <class ELFT> void GNUELFDumper<ELFT>::printSectionDetails() {
3868   ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
3869   OS << "There are " << to_string(Sections.size())
3870      << " section headers, starting at offset "
3871      << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n";
3872 
3873   OS << "Section Headers:\n";
3874 
3875   auto PrintFields = [&](ArrayRef<Field> V) {
3876     for (const Field &F : V)
3877       printField(F);
3878     OS << "\n";
3879   };
3880 
3881   PrintFields({{"[Nr]", 2}, {"Name", 7}});
3882 
3883   constexpr bool Is64 = ELFT::Is64Bits;
3884   PrintFields({{"Type", 7},
3885                {Is64 ? "Address" : "Addr", 23},
3886                {"Off", Is64 ? 40 : 32},
3887                {"Size", Is64 ? 47 : 39},
3888                {"ES", Is64 ? 54 : 46},
3889                {"Lk", Is64 ? 59 : 51},
3890                {"Inf", Is64 ? 62 : 54},
3891                {"Al", Is64 ? 66 : 57}});
3892   PrintFields({{"Flags", 7}});
3893 
3894   StringRef SecStrTable;
3895   if (Expected<StringRef> SecStrTableOrErr =
3896           this->Obj.getSectionStringTable(Sections, this->WarningHandler))
3897     SecStrTable = *SecStrTableOrErr;
3898   else
3899     this->reportUniqueWarning(SecStrTableOrErr.takeError());
3900 
3901   size_t SectionIndex = 0;
3902   const unsigned AddrSize = Is64 ? 16 : 8;
3903   for (const Elf_Shdr &S : Sections) {
3904     StringRef Name = "<?>";
3905     if (Expected<StringRef> NameOrErr =
3906             this->Obj.getSectionName(S, SecStrTable))
3907       Name = *NameOrErr;
3908     else
3909       this->reportUniqueWarning(NameOrErr.takeError());
3910 
3911     OS.PadToColumn(2);
3912     OS << "[" << right_justify(to_string(SectionIndex), 2) << "]";
3913     PrintFields({{Name, 7}});
3914     PrintFields(
3915         {{getSectionTypeString(this->Obj.getHeader().e_machine, S.sh_type), 7},
3916          {to_string(format_hex_no_prefix(S.sh_addr, AddrSize)), 23},
3917          {to_string(format_hex_no_prefix(S.sh_offset, 6)), Is64 ? 39 : 32},
3918          {to_string(format_hex_no_prefix(S.sh_size, 6)), Is64 ? 47 : 39},
3919          {to_string(format_hex_no_prefix(S.sh_entsize, 2)), Is64 ? 54 : 46},
3920          {to_string(S.sh_link), Is64 ? 59 : 51},
3921          {to_string(S.sh_info), Is64 ? 63 : 55},
3922          {to_string(S.sh_addralign), Is64 ? 66 : 58}});
3923 
3924     OS.PadToColumn(7);
3925     OS << "[" << to_string(format_hex_no_prefix(S.sh_flags, AddrSize)) << "]: ";
3926 
3927     DenseMap<unsigned, StringRef> FlagToName = {
3928         {SHF_WRITE, "WRITE"},           {SHF_ALLOC, "ALLOC"},
3929         {SHF_EXECINSTR, "EXEC"},        {SHF_MERGE, "MERGE"},
3930         {SHF_STRINGS, "STRINGS"},       {SHF_INFO_LINK, "INFO LINK"},
3931         {SHF_LINK_ORDER, "LINK ORDER"}, {SHF_OS_NONCONFORMING, "OS NONCONF"},
3932         {SHF_GROUP, "GROUP"},           {SHF_TLS, "TLS"},
3933         {SHF_COMPRESSED, "COMPRESSED"}, {SHF_EXCLUDE, "EXCLUDE"}};
3934 
3935     uint64_t Flags = S.sh_flags;
3936     uint64_t UnknownFlags = 0;
3937     bool NeedsComma = false;
3938     while (Flags) {
3939       // Take the least significant bit as a flag.
3940       uint64_t Flag = Flags & -Flags;
3941       Flags -= Flag;
3942 
3943       auto It = FlagToName.find(Flag);
3944       if (It != FlagToName.end()) {
3945         if (NeedsComma)
3946           OS << ", ";
3947         NeedsComma = true;
3948         OS << It->second;
3949       } else {
3950         UnknownFlags |= Flag;
3951       }
3952     }
3953 
3954     auto PrintUnknownFlags = [&](uint64_t Mask, StringRef Name) {
3955       uint64_t FlagsToPrint = UnknownFlags & Mask;
3956       if (!FlagsToPrint)
3957         return;
3958 
3959       if (NeedsComma)
3960         OS << ", ";
3961       OS << Name << " ("
3962          << to_string(format_hex_no_prefix(FlagsToPrint, AddrSize)) << ")";
3963       UnknownFlags &= ~Mask;
3964       NeedsComma = true;
3965     };
3966 
3967     PrintUnknownFlags(SHF_MASKOS, "OS");
3968     PrintUnknownFlags(SHF_MASKPROC, "PROC");
3969     PrintUnknownFlags(uint64_t(-1), "UNKNOWN");
3970 
3971     OS << "\n";
3972     ++SectionIndex;
3973   }
3974 }
3975 
3976 static inline std::string printPhdrFlags(unsigned Flag) {
3977   std::string Str;
3978   Str = (Flag & PF_R) ? "R" : " ";
3979   Str += (Flag & PF_W) ? "W" : " ";
3980   Str += (Flag & PF_X) ? "E" : " ";
3981   return Str;
3982 }
3983 
3984 template <class ELFT>
3985 static bool checkTLSSections(const typename ELFT::Phdr &Phdr,
3986                              const typename ELFT::Shdr &Sec) {
3987   if (Sec.sh_flags & ELF::SHF_TLS) {
3988     // .tbss must only be shown in the PT_TLS segment.
3989     if (Sec.sh_type == ELF::SHT_NOBITS)
3990       return Phdr.p_type == ELF::PT_TLS;
3991 
3992     // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO
3993     // segments.
3994     return (Phdr.p_type == ELF::PT_TLS) || (Phdr.p_type == ELF::PT_LOAD) ||
3995            (Phdr.p_type == ELF::PT_GNU_RELRO);
3996   }
3997 
3998   // PT_TLS must only have SHF_TLS sections.
3999   return Phdr.p_type != ELF::PT_TLS;
4000 }
4001 
4002 template <class ELFT>
4003 static bool checkOffsets(const typename ELFT::Phdr &Phdr,
4004                          const typename ELFT::Shdr &Sec) {
4005   // SHT_NOBITS sections don't need to have an offset inside the segment.
4006   if (Sec.sh_type == ELF::SHT_NOBITS)
4007     return true;
4008 
4009   if (Sec.sh_offset < Phdr.p_offset)
4010     return false;
4011 
4012   // Only non-empty sections can be at the end of a segment.
4013   if (Sec.sh_size == 0)
4014     return (Sec.sh_offset + 1 <= Phdr.p_offset + Phdr.p_filesz);
4015   return Sec.sh_offset + Sec.sh_size <= Phdr.p_offset + Phdr.p_filesz;
4016 }
4017 
4018 // Check that an allocatable section belongs to a virtual address
4019 // space of a segment.
4020 template <class ELFT>
4021 static bool checkVMA(const typename ELFT::Phdr &Phdr,
4022                      const typename ELFT::Shdr &Sec) {
4023   if (!(Sec.sh_flags & ELF::SHF_ALLOC))
4024     return true;
4025 
4026   if (Sec.sh_addr < Phdr.p_vaddr)
4027     return false;
4028 
4029   bool IsTbss =
4030       (Sec.sh_type == ELF::SHT_NOBITS) && ((Sec.sh_flags & ELF::SHF_TLS) != 0);
4031   // .tbss is special, it only has memory in PT_TLS and has NOBITS properties.
4032   bool IsTbssInNonTLS = IsTbss && Phdr.p_type != ELF::PT_TLS;
4033   // Only non-empty sections can be at the end of a segment.
4034   if (Sec.sh_size == 0 || IsTbssInNonTLS)
4035     return Sec.sh_addr + 1 <= Phdr.p_vaddr + Phdr.p_memsz;
4036   return Sec.sh_addr + Sec.sh_size <= Phdr.p_vaddr + Phdr.p_memsz;
4037 }
4038 
4039 template <class ELFT>
4040 static bool checkPTDynamic(const typename ELFT::Phdr &Phdr,
4041                            const typename ELFT::Shdr &Sec) {
4042   if (Phdr.p_type != ELF::PT_DYNAMIC || Phdr.p_memsz == 0 || Sec.sh_size != 0)
4043     return true;
4044 
4045   // We get here when we have an empty section. Only non-empty sections can be
4046   // at the start or at the end of PT_DYNAMIC.
4047   // Is section within the phdr both based on offset and VMA?
4048   bool CheckOffset = (Sec.sh_type == ELF::SHT_NOBITS) ||
4049                      (Sec.sh_offset > Phdr.p_offset &&
4050                       Sec.sh_offset < Phdr.p_offset + Phdr.p_filesz);
4051   bool CheckVA = !(Sec.sh_flags & ELF::SHF_ALLOC) ||
4052                  (Sec.sh_addr > Phdr.p_vaddr && Sec.sh_addr < Phdr.p_memsz);
4053   return CheckOffset && CheckVA;
4054 }
4055 
4056 template <class ELFT>
4057 void GNUELFDumper<ELFT>::printProgramHeaders(
4058     bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
4059   if (PrintProgramHeaders)
4060     printProgramHeaders();
4061 
4062   // Display the section mapping along with the program headers, unless
4063   // -section-mapping is explicitly set to false.
4064   if (PrintSectionMapping != cl::BOU_FALSE)
4065     printSectionMapping();
4066 }
4067 
4068 template <class ELFT> void GNUELFDumper<ELFT>::printProgramHeaders() {
4069   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4070   const Elf_Ehdr &Header = this->Obj.getHeader();
4071   Field Fields[8] = {2,         17,        26,        37 + Bias,
4072                      48 + Bias, 56 + Bias, 64 + Bias, 68 + Bias};
4073   OS << "\nElf file type is "
4074      << printEnum(Header.e_type, makeArrayRef(ElfObjectFileType)) << "\n"
4075      << "Entry point " << format_hex(Header.e_entry, 3) << "\n"
4076      << "There are " << Header.e_phnum << " program headers,"
4077      << " starting at offset " << Header.e_phoff << "\n\n"
4078      << "Program Headers:\n";
4079   if (ELFT::Is64Bits)
4080     OS << "  Type           Offset   VirtAddr           PhysAddr         "
4081        << "  FileSiz  MemSiz   Flg Align\n";
4082   else
4083     OS << "  Type           Offset   VirtAddr   PhysAddr   FileSiz "
4084        << "MemSiz  Flg Align\n";
4085 
4086   unsigned Width = ELFT::Is64Bits ? 18 : 10;
4087   unsigned SizeWidth = ELFT::Is64Bits ? 8 : 7;
4088 
4089   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4090   if (!PhdrsOrErr) {
4091     this->reportUniqueWarning("unable to dump program headers: " +
4092                               toString(PhdrsOrErr.takeError()));
4093     return;
4094   }
4095 
4096   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4097     Fields[0].Str = getGNUPtType(Header.e_machine, Phdr.p_type);
4098     Fields[1].Str = to_string(format_hex(Phdr.p_offset, 8));
4099     Fields[2].Str = to_string(format_hex(Phdr.p_vaddr, Width));
4100     Fields[3].Str = to_string(format_hex(Phdr.p_paddr, Width));
4101     Fields[4].Str = to_string(format_hex(Phdr.p_filesz, SizeWidth));
4102     Fields[5].Str = to_string(format_hex(Phdr.p_memsz, SizeWidth));
4103     Fields[6].Str = printPhdrFlags(Phdr.p_flags);
4104     Fields[7].Str = to_string(format_hex(Phdr.p_align, 1));
4105     for (const Field &F : Fields)
4106       printField(F);
4107     if (Phdr.p_type == ELF::PT_INTERP) {
4108       OS << "\n";
4109       auto ReportBadInterp = [&](const Twine &Msg) {
4110         this->reportUniqueWarning(
4111             "unable to read program interpreter name at offset 0x" +
4112             Twine::utohexstr(Phdr.p_offset) + ": " + Msg);
4113       };
4114 
4115       if (Phdr.p_offset >= this->Obj.getBufSize()) {
4116         ReportBadInterp("it goes past the end of the file (0x" +
4117                         Twine::utohexstr(this->Obj.getBufSize()) + ")");
4118         continue;
4119       }
4120 
4121       const char *Data =
4122           reinterpret_cast<const char *>(this->Obj.base()) + Phdr.p_offset;
4123       size_t MaxSize = this->Obj.getBufSize() - Phdr.p_offset;
4124       size_t Len = strnlen(Data, MaxSize);
4125       if (Len == MaxSize) {
4126         ReportBadInterp("it is not null-terminated");
4127         continue;
4128       }
4129 
4130       OS << "      [Requesting program interpreter: ";
4131       OS << StringRef(Data, Len) << "]";
4132     }
4133     OS << "\n";
4134   }
4135 }
4136 
4137 template <class ELFT> void GNUELFDumper<ELFT>::printSectionMapping() {
4138   OS << "\n Section to Segment mapping:\n  Segment Sections...\n";
4139   DenseSet<const Elf_Shdr *> BelongsToSegment;
4140   int Phnum = 0;
4141 
4142   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4143   if (!PhdrsOrErr) {
4144     this->reportUniqueWarning(
4145         "can't read program headers to build section to segment mapping: " +
4146         toString(PhdrsOrErr.takeError()));
4147     return;
4148   }
4149 
4150   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4151     std::string Sections;
4152     OS << format("   %2.2d     ", Phnum++);
4153     // Check if each section is in a segment and then print mapping.
4154     for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4155       if (Sec.sh_type == ELF::SHT_NULL)
4156         continue;
4157 
4158       // readelf additionally makes sure it does not print zero sized sections
4159       // at end of segments and for PT_DYNAMIC both start and end of section
4160       // .tbss must only be shown in PT_TLS section.
4161       if (checkTLSSections<ELFT>(Phdr, Sec) && checkOffsets<ELFT>(Phdr, Sec) &&
4162           checkVMA<ELFT>(Phdr, Sec) && checkPTDynamic<ELFT>(Phdr, Sec)) {
4163         Sections +=
4164             unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4165             " ";
4166         BelongsToSegment.insert(&Sec);
4167       }
4168     }
4169     OS << Sections << "\n";
4170     OS.flush();
4171   }
4172 
4173   // Display sections that do not belong to a segment.
4174   std::string Sections;
4175   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4176     if (BelongsToSegment.find(&Sec) == BelongsToSegment.end())
4177       Sections +=
4178           unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4179           ' ';
4180   }
4181   if (!Sections.empty()) {
4182     OS << "   None  " << Sections << '\n';
4183     OS.flush();
4184   }
4185 }
4186 
4187 namespace {
4188 
4189 template <class ELFT>
4190 RelSymbol<ELFT> getSymbolForReloc(const ELFDumper<ELFT> &Dumper,
4191                                   const Relocation<ELFT> &Reloc) {
4192   using Elf_Sym = typename ELFT::Sym;
4193   auto WarnAndReturn = [&](const Elf_Sym *Sym,
4194                            const Twine &Reason) -> RelSymbol<ELFT> {
4195     Dumper.reportUniqueWarning(
4196         "unable to get name of the dynamic symbol with index " +
4197         Twine(Reloc.Symbol) + ": " + Reason);
4198     return {Sym, "<corrupt>"};
4199   };
4200 
4201   ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols();
4202   const Elf_Sym *FirstSym = Symbols.begin();
4203   if (!FirstSym)
4204     return WarnAndReturn(nullptr, "no dynamic symbol table found");
4205 
4206   // We might have an object without a section header. In this case the size of
4207   // Symbols is zero, because there is no way to know the size of the dynamic
4208   // table. We should allow this case and not print a warning.
4209   if (!Symbols.empty() && Reloc.Symbol >= Symbols.size())
4210     return WarnAndReturn(
4211         nullptr,
4212         "index is greater than or equal to the number of dynamic symbols (" +
4213             Twine(Symbols.size()) + ")");
4214 
4215   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
4216   const uint64_t FileSize = Obj.getBufSize();
4217   const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) +
4218                              (uint64_t)Reloc.Symbol * sizeof(Elf_Sym);
4219   if (SymOffset + sizeof(Elf_Sym) > FileSize)
4220     return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(SymOffset) +
4221                                       " goes past the end of the file (0x" +
4222                                       Twine::utohexstr(FileSize) + ")");
4223 
4224   const Elf_Sym *Sym = FirstSym + Reloc.Symbol;
4225   Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable());
4226   if (!ErrOrName)
4227     return WarnAndReturn(Sym, toString(ErrOrName.takeError()));
4228 
4229   return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(*ErrOrName)};
4230 }
4231 } // namespace
4232 
4233 template <class ELFT>
4234 static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj,
4235                                    typename ELFT::DynRange Tags) {
4236   size_t Max = 0;
4237   for (const typename ELFT::Dyn &Dyn : Tags)
4238     Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size());
4239   return Max;
4240 }
4241 
4242 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicTable() {
4243   Elf_Dyn_Range Table = this->dynamic_table();
4244   if (Table.empty())
4245     return;
4246 
4247   OS << "Dynamic section at offset "
4248      << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable.Addr) -
4249                        this->Obj.base(),
4250                    1)
4251      << " contains " << Table.size() << " entries:\n";
4252 
4253   // The type name is surrounded with round brackets, hence add 2.
4254   size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2;
4255   // The "Name/Value" column should be indented from the "Type" column by N
4256   // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
4257   // space (1) = 3.
4258   OS << "  Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type"
4259      << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
4260 
4261   std::string ValueFmt = " %-" + std::to_string(MaxTagSize) + "s ";
4262   for (auto Entry : Table) {
4263     uintX_t Tag = Entry.getTag();
4264     std::string Type =
4265         std::string("(") + this->Obj.getDynamicTagAsString(Tag).c_str() + ")";
4266     std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
4267     OS << "  " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10)
4268        << format(ValueFmt.c_str(), Type.c_str()) << Value << "\n";
4269   }
4270 }
4271 
4272 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicRelocations() {
4273   this->printDynamicRelocationsHelper();
4274 }
4275 
4276 template <class ELFT>
4277 void ELFDumper<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) {
4278   printRelRelaReloc(R, getSymbolForReloc(*this, R));
4279 }
4280 
4281 template <class ELFT>
4282 void ELFDumper<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) {
4283   this->forEachRelocationDo(
4284       Sec, opts::RawRelr,
4285       [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
4286           const Elf_Shdr *SymTab) { printReloc(R, Ndx, Sec, SymTab); },
4287       [&](const Elf_Relr &R) { printRelrReloc(R); });
4288 }
4289 
4290 template <class ELFT> void ELFDumper<ELFT>::printDynamicRelocationsHelper() {
4291   const bool IsMips64EL = this->Obj.isMips64EL();
4292   if (this->DynRelaRegion.Size > 0) {
4293     printDynamicRelocHeader(ELF::SHT_RELA, "RELA", this->DynRelaRegion);
4294     for (const Elf_Rela &Rela :
4295          this->DynRelaRegion.template getAsArrayRef<Elf_Rela>())
4296       printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
4297   }
4298 
4299   if (this->DynRelRegion.Size > 0) {
4300     printDynamicRelocHeader(ELF::SHT_REL, "REL", this->DynRelRegion);
4301     for (const Elf_Rel &Rel :
4302          this->DynRelRegion.template getAsArrayRef<Elf_Rel>())
4303       printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4304   }
4305 
4306   if (this->DynRelrRegion.Size > 0) {
4307     printDynamicRelocHeader(ELF::SHT_REL, "RELR", this->DynRelrRegion);
4308     Elf_Relr_Range Relrs =
4309         this->DynRelrRegion.template getAsArrayRef<Elf_Relr>();
4310     for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs))
4311       printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4312   }
4313 
4314   if (this->DynPLTRelRegion.Size) {
4315     if (this->DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) {
4316       printDynamicRelocHeader(ELF::SHT_RELA, "PLT", this->DynPLTRelRegion);
4317       for (const Elf_Rela &Rela :
4318            this->DynPLTRelRegion.template getAsArrayRef<Elf_Rela>())
4319         printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
4320     } else {
4321       printDynamicRelocHeader(ELF::SHT_REL, "PLT", this->DynPLTRelRegion);
4322       for (const Elf_Rel &Rel :
4323            this->DynPLTRelRegion.template getAsArrayRef<Elf_Rel>())
4324         printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4325     }
4326   }
4327 }
4328 
4329 template <class ELFT>
4330 void GNUELFDumper<ELFT>::printGNUVersionSectionProlog(
4331     const typename ELFT::Shdr &Sec, const Twine &Label, unsigned EntriesNum) {
4332   // Don't inline the SecName, because it might report a warning to stderr and
4333   // corrupt the output.
4334   StringRef SecName = this->getPrintableSectionName(Sec);
4335   OS << Label << " section '" << SecName << "' "
4336      << "contains " << EntriesNum << " entries:\n";
4337 
4338   StringRef LinkedSecName = "<corrupt>";
4339   if (Expected<const typename ELFT::Shdr *> LinkedSecOrErr =
4340           this->Obj.getSection(Sec.sh_link))
4341     LinkedSecName = this->getPrintableSectionName(**LinkedSecOrErr);
4342   else
4343     this->reportUniqueWarning("invalid section linked to " +
4344                               this->describe(Sec) + ": " +
4345                               toString(LinkedSecOrErr.takeError()));
4346 
4347   OS << " Addr: " << format_hex_no_prefix(Sec.sh_addr, 16)
4348      << "  Offset: " << format_hex(Sec.sh_offset, 8)
4349      << "  Link: " << Sec.sh_link << " (" << LinkedSecName << ")\n";
4350 }
4351 
4352 template <class ELFT>
4353 void GNUELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
4354   if (!Sec)
4355     return;
4356 
4357   printGNUVersionSectionProlog(*Sec, "Version symbols",
4358                                Sec->sh_size / sizeof(Elf_Versym));
4359   Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
4360       this->getVersionTable(*Sec, /*SymTab=*/nullptr,
4361                             /*StrTab=*/nullptr, /*SymTabSec=*/nullptr);
4362   if (!VerTableOrErr) {
4363     this->reportUniqueWarning(VerTableOrErr.takeError());
4364     return;
4365   }
4366 
4367   SmallVector<Optional<VersionEntry>, 0> *VersionMap = nullptr;
4368   if (Expected<SmallVector<Optional<VersionEntry>, 0> *> MapOrErr =
4369           this->getVersionMap())
4370     VersionMap = *MapOrErr;
4371   else
4372     this->reportUniqueWarning(MapOrErr.takeError());
4373 
4374   ArrayRef<Elf_Versym> VerTable = *VerTableOrErr;
4375   std::vector<StringRef> Versions;
4376   for (size_t I = 0, E = VerTable.size(); I < E; ++I) {
4377     unsigned Ndx = VerTable[I].vs_index;
4378     if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) {
4379       Versions.emplace_back(Ndx == VER_NDX_LOCAL ? "*local*" : "*global*");
4380       continue;
4381     }
4382 
4383     if (!VersionMap) {
4384       Versions.emplace_back("<corrupt>");
4385       continue;
4386     }
4387 
4388     bool IsDefault;
4389     Expected<StringRef> NameOrErr = this->Obj.getSymbolVersionByIndex(
4390         Ndx, IsDefault, *VersionMap, /*IsSymHidden=*/None);
4391     if (!NameOrErr) {
4392       this->reportUniqueWarning("unable to get a version for entry " +
4393                                 Twine(I) + " of " + this->describe(*Sec) +
4394                                 ": " + toString(NameOrErr.takeError()));
4395       Versions.emplace_back("<corrupt>");
4396       continue;
4397     }
4398     Versions.emplace_back(*NameOrErr);
4399   }
4400 
4401   // readelf prints 4 entries per line.
4402   uint64_t Entries = VerTable.size();
4403   for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) {
4404     OS << "  " << format_hex_no_prefix(VersymRow, 3) << ":";
4405     for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) {
4406       unsigned Ndx = VerTable[VersymRow + I].vs_index;
4407       OS << format("%4x%c", Ndx & VERSYM_VERSION,
4408                    Ndx & VERSYM_HIDDEN ? 'h' : ' ');
4409       OS << left_justify("(" + std::string(Versions[VersymRow + I]) + ")", 13);
4410     }
4411     OS << '\n';
4412   }
4413   OS << '\n';
4414 }
4415 
4416 static std::string versionFlagToString(unsigned Flags) {
4417   if (Flags == 0)
4418     return "none";
4419 
4420   std::string Ret;
4421   auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) {
4422     if (!(Flags & Flag))
4423       return;
4424     if (!Ret.empty())
4425       Ret += " | ";
4426     Ret += Name;
4427     Flags &= ~Flag;
4428   };
4429 
4430   AddFlag(VER_FLG_BASE, "BASE");
4431   AddFlag(VER_FLG_WEAK, "WEAK");
4432   AddFlag(VER_FLG_INFO, "INFO");
4433   AddFlag(~0, "<unknown>");
4434   return Ret;
4435 }
4436 
4437 template <class ELFT>
4438 void GNUELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
4439   if (!Sec)
4440     return;
4441 
4442   printGNUVersionSectionProlog(*Sec, "Version definition", Sec->sh_info);
4443 
4444   Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
4445   if (!V) {
4446     this->reportUniqueWarning(V.takeError());
4447     return;
4448   }
4449 
4450   for (const VerDef &Def : *V) {
4451     OS << format("  0x%04x: Rev: %u  Flags: %s  Index: %u  Cnt: %u  Name: %s\n",
4452                  Def.Offset, Def.Version,
4453                  versionFlagToString(Def.Flags).c_str(), Def.Ndx, Def.Cnt,
4454                  Def.Name.data());
4455     unsigned I = 0;
4456     for (const VerdAux &Aux : Def.AuxV)
4457       OS << format("  0x%04x: Parent %u: %s\n", Aux.Offset, ++I,
4458                    Aux.Name.data());
4459   }
4460 
4461   OS << '\n';
4462 }
4463 
4464 template <class ELFT>
4465 void GNUELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
4466   if (!Sec)
4467     return;
4468 
4469   unsigned VerneedNum = Sec->sh_info;
4470   printGNUVersionSectionProlog(*Sec, "Version needs", VerneedNum);
4471 
4472   Expected<std::vector<VerNeed>> V =
4473       this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
4474   if (!V) {
4475     this->reportUniqueWarning(V.takeError());
4476     return;
4477   }
4478 
4479   for (const VerNeed &VN : *V) {
4480     OS << format("  0x%04x: Version: %u  File: %s  Cnt: %u\n", VN.Offset,
4481                  VN.Version, VN.File.data(), VN.Cnt);
4482     for (const VernAux &Aux : VN.AuxV)
4483       OS << format("  0x%04x:   Name: %s  Flags: %s  Version: %u\n", Aux.Offset,
4484                    Aux.Name.data(), versionFlagToString(Aux.Flags).c_str(),
4485                    Aux.Other);
4486   }
4487   OS << '\n';
4488 }
4489 
4490 template <class ELFT>
4491 void GNUELFDumper<ELFT>::printHashHistogram(const Elf_Hash &HashTable) {
4492   size_t NBucket = HashTable.nbucket;
4493   size_t NChain = HashTable.nchain;
4494   ArrayRef<Elf_Word> Buckets = HashTable.buckets();
4495   ArrayRef<Elf_Word> Chains = HashTable.chains();
4496   size_t TotalSyms = 0;
4497   // If hash table is correct, we have at least chains with 0 length
4498   size_t MaxChain = 1;
4499   size_t CumulativeNonZero = 0;
4500 
4501   if (NChain == 0 || NBucket == 0)
4502     return;
4503 
4504   std::vector<size_t> ChainLen(NBucket, 0);
4505   // Go over all buckets and and note chain lengths of each bucket (total
4506   // unique chain lengths).
4507   for (size_t B = 0; B < NBucket; B++) {
4508     std::vector<bool> Visited(NChain);
4509     for (size_t C = Buckets[B]; C < NChain; C = Chains[C]) {
4510       if (C == ELF::STN_UNDEF)
4511         break;
4512       if (Visited[C]) {
4513         this->reportUniqueWarning(".hash section is invalid: bucket " +
4514                                   Twine(C) +
4515                                   ": a cycle was detected in the linked chain");
4516         break;
4517       }
4518       Visited[C] = true;
4519       if (MaxChain <= ++ChainLen[B])
4520         MaxChain++;
4521     }
4522     TotalSyms += ChainLen[B];
4523   }
4524 
4525   if (!TotalSyms)
4526     return;
4527 
4528   std::vector<size_t> Count(MaxChain, 0);
4529   // Count how long is the chain for each bucket
4530   for (size_t B = 0; B < NBucket; B++)
4531     ++Count[ChainLen[B]];
4532   // Print Number of buckets with each chain lengths and their cumulative
4533   // coverage of the symbols
4534   OS << "Histogram for bucket list length (total of " << NBucket
4535      << " buckets)\n"
4536      << " Length  Number     % of total  Coverage\n";
4537   for (size_t I = 0; I < MaxChain; I++) {
4538     CumulativeNonZero += Count[I] * I;
4539     OS << format("%7lu  %-10lu (%5.1f%%)     %5.1f%%\n", I, Count[I],
4540                  (Count[I] * 100.0) / NBucket,
4541                  (CumulativeNonZero * 100.0) / TotalSyms);
4542   }
4543 }
4544 
4545 template <class ELFT>
4546 void GNUELFDumper<ELFT>::printGnuHashHistogram(
4547     const Elf_GnuHash &GnuHashTable) {
4548   Expected<ArrayRef<Elf_Word>> ChainsOrErr =
4549       getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHashTable);
4550   if (!ChainsOrErr) {
4551     this->reportUniqueWarning("unable to print the GNU hash table histogram: " +
4552                               toString(ChainsOrErr.takeError()));
4553     return;
4554   }
4555 
4556   ArrayRef<Elf_Word> Chains = *ChainsOrErr;
4557   size_t Symndx = GnuHashTable.symndx;
4558   size_t TotalSyms = 0;
4559   size_t MaxChain = 1;
4560   size_t CumulativeNonZero = 0;
4561 
4562   size_t NBucket = GnuHashTable.nbuckets;
4563   if (Chains.empty() || NBucket == 0)
4564     return;
4565 
4566   ArrayRef<Elf_Word> Buckets = GnuHashTable.buckets();
4567   std::vector<size_t> ChainLen(NBucket, 0);
4568   for (size_t B = 0; B < NBucket; B++) {
4569     if (!Buckets[B])
4570       continue;
4571     size_t Len = 1;
4572     for (size_t C = Buckets[B] - Symndx;
4573          C < Chains.size() && (Chains[C] & 1) == 0; C++)
4574       if (MaxChain < ++Len)
4575         MaxChain++;
4576     ChainLen[B] = Len;
4577     TotalSyms += Len;
4578   }
4579   MaxChain++;
4580 
4581   if (!TotalSyms)
4582     return;
4583 
4584   std::vector<size_t> Count(MaxChain, 0);
4585   for (size_t B = 0; B < NBucket; B++)
4586     ++Count[ChainLen[B]];
4587   // Print Number of buckets with each chain lengths and their cumulative
4588   // coverage of the symbols
4589   OS << "Histogram for `.gnu.hash' bucket list length (total of " << NBucket
4590      << " buckets)\n"
4591      << " Length  Number     % of total  Coverage\n";
4592   for (size_t I = 0; I < MaxChain; I++) {
4593     CumulativeNonZero += Count[I] * I;
4594     OS << format("%7lu  %-10lu (%5.1f%%)     %5.1f%%\n", I, Count[I],
4595                  (Count[I] * 100.0) / NBucket,
4596                  (CumulativeNonZero * 100.0) / TotalSyms);
4597   }
4598 }
4599 
4600 // Hash histogram shows statistics of how efficient the hash was for the
4601 // dynamic symbol table. The table shows the number of hash buckets for
4602 // different lengths of chains as an absolute number and percentage of the total
4603 // buckets, and the cumulative coverage of symbols for each set of buckets.
4604 template <class ELFT> void GNUELFDumper<ELFT>::printHashHistograms() {
4605   // Print histogram for the .hash section.
4606   if (this->HashTable) {
4607     if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
4608       this->reportUniqueWarning(std::move(E));
4609     else
4610       printHashHistogram(*this->HashTable);
4611   }
4612 
4613   // Print histogram for the .gnu.hash section.
4614   if (this->GnuHashTable) {
4615     if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
4616       this->reportUniqueWarning(std::move(E));
4617     else
4618       printGnuHashHistogram(*this->GnuHashTable);
4619   }
4620 }
4621 
4622 template <class ELFT> void GNUELFDumper<ELFT>::printCGProfile() {
4623   OS << "GNUStyle::printCGProfile not implemented\n";
4624 }
4625 
4626 static Expected<std::vector<uint64_t>> toULEB128Array(ArrayRef<uint8_t> Data) {
4627   std::vector<uint64_t> Ret;
4628   const uint8_t *Cur = Data.begin();
4629   const uint8_t *End = Data.end();
4630   while (Cur != End) {
4631     unsigned Size;
4632     const char *Err;
4633     Ret.push_back(decodeULEB128(Cur, &Size, End, &Err));
4634     if (Err)
4635       return createError(Err);
4636     Cur += Size;
4637   }
4638   return Ret;
4639 }
4640 
4641 template <class ELFT>
4642 static Expected<std::vector<uint64_t>>
4643 decodeAddrsigSection(const ELFFile<ELFT> &Obj, const typename ELFT::Shdr &Sec) {
4644   Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Sec);
4645   if (!ContentsOrErr)
4646     return ContentsOrErr.takeError();
4647 
4648   if (Expected<std::vector<uint64_t>> SymsOrErr =
4649           toULEB128Array(*ContentsOrErr))
4650     return *SymsOrErr;
4651   else
4652     return createError("unable to decode " + describe(Obj, Sec) + ": " +
4653                        toString(SymsOrErr.takeError()));
4654 }
4655 
4656 template <class ELFT> void GNUELFDumper<ELFT>::printAddrsig() {
4657   if (!this->DotAddrsigSec)
4658     return;
4659 
4660   Expected<std::vector<uint64_t>> SymsOrErr =
4661       decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
4662   if (!SymsOrErr) {
4663     this->reportUniqueWarning(SymsOrErr.takeError());
4664     return;
4665   }
4666 
4667   StringRef Name = this->getPrintableSectionName(*this->DotAddrsigSec);
4668   OS << "\nAddress-significant symbols section '" << Name << "'"
4669      << " contains " << SymsOrErr->size() << " entries:\n";
4670   OS << "   Num: Name\n";
4671 
4672   Field Fields[2] = {0, 8};
4673   size_t SymIndex = 0;
4674   for (uint64_t Sym : *SymsOrErr) {
4675     Fields[0].Str = to_string(format_decimal(++SymIndex, 6)) + ":";
4676     Fields[1].Str = this->getStaticSymbolName(Sym);
4677     for (const Field &Entry : Fields)
4678       printField(Entry);
4679     OS << "\n";
4680   }
4681 }
4682 
4683 template <typename ELFT>
4684 static std::string getGNUProperty(uint32_t Type, uint32_t DataSize,
4685                                   ArrayRef<uint8_t> Data) {
4686   std::string str;
4687   raw_string_ostream OS(str);
4688   uint32_t PrData;
4689   auto DumpBit = [&](uint32_t Flag, StringRef Name) {
4690     if (PrData & Flag) {
4691       PrData &= ~Flag;
4692       OS << Name;
4693       if (PrData)
4694         OS << ", ";
4695     }
4696   };
4697 
4698   switch (Type) {
4699   default:
4700     OS << format("<application-specific type 0x%x>", Type);
4701     return OS.str();
4702   case GNU_PROPERTY_STACK_SIZE: {
4703     OS << "stack size: ";
4704     if (DataSize == sizeof(typename ELFT::uint))
4705       OS << formatv("{0:x}",
4706                     (uint64_t)(*(const typename ELFT::Addr *)Data.data()));
4707     else
4708       OS << format("<corrupt length: 0x%x>", DataSize);
4709     return OS.str();
4710   }
4711   case GNU_PROPERTY_NO_COPY_ON_PROTECTED:
4712     OS << "no copy on protected";
4713     if (DataSize)
4714       OS << format(" <corrupt length: 0x%x>", DataSize);
4715     return OS.str();
4716   case GNU_PROPERTY_AARCH64_FEATURE_1_AND:
4717   case GNU_PROPERTY_X86_FEATURE_1_AND:
4718     OS << ((Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) ? "aarch64 feature: "
4719                                                         : "x86 feature: ");
4720     if (DataSize != 4) {
4721       OS << format("<corrupt length: 0x%x>", DataSize);
4722       return OS.str();
4723     }
4724     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
4725     if (PrData == 0) {
4726       OS << "<None>";
4727       return OS.str();
4728     }
4729     if (Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) {
4730       DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI, "BTI");
4731       DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC, "PAC");
4732     } else {
4733       DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT, "IBT");
4734       DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK, "SHSTK");
4735     }
4736     if (PrData)
4737       OS << format("<unknown flags: 0x%x>", PrData);
4738     return OS.str();
4739   case GNU_PROPERTY_X86_ISA_1_NEEDED:
4740   case GNU_PROPERTY_X86_ISA_1_USED:
4741     OS << "x86 ISA "
4742        << (Type == GNU_PROPERTY_X86_ISA_1_NEEDED ? "needed: " : "used: ");
4743     if (DataSize != 4) {
4744       OS << format("<corrupt length: 0x%x>", DataSize);
4745       return OS.str();
4746     }
4747     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
4748     if (PrData == 0) {
4749       OS << "<None>";
4750       return OS.str();
4751     }
4752     DumpBit(GNU_PROPERTY_X86_ISA_1_CMOV, "CMOV");
4753     DumpBit(GNU_PROPERTY_X86_ISA_1_SSE, "SSE");
4754     DumpBit(GNU_PROPERTY_X86_ISA_1_SSE2, "SSE2");
4755     DumpBit(GNU_PROPERTY_X86_ISA_1_SSE3, "SSE3");
4756     DumpBit(GNU_PROPERTY_X86_ISA_1_SSSE3, "SSSE3");
4757     DumpBit(GNU_PROPERTY_X86_ISA_1_SSE4_1, "SSE4_1");
4758     DumpBit(GNU_PROPERTY_X86_ISA_1_SSE4_2, "SSE4_2");
4759     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX, "AVX");
4760     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX2, "AVX2");
4761     DumpBit(GNU_PROPERTY_X86_ISA_1_FMA, "FMA");
4762     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512F, "AVX512F");
4763     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512CD, "AVX512CD");
4764     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512ER, "AVX512ER");
4765     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512PF, "AVX512PF");
4766     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512VL, "AVX512VL");
4767     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512DQ, "AVX512DQ");
4768     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512BW, "AVX512BW");
4769     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_4FMAPS, "AVX512_4FMAPS");
4770     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_4VNNIW, "AVX512_4VNNIW");
4771     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_BITALG, "AVX512_BITALG");
4772     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_IFMA, "AVX512_IFMA");
4773     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_VBMI, "AVX512_VBMI");
4774     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_VBMI2, "AVX512_VBMI2");
4775     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_VNNI, "AVX512_VNNI");
4776     if (PrData)
4777       OS << format("<unknown flags: 0x%x>", PrData);
4778     return OS.str();
4779     break;
4780   case GNU_PROPERTY_X86_FEATURE_2_NEEDED:
4781   case GNU_PROPERTY_X86_FEATURE_2_USED:
4782     OS << "x86 feature "
4783        << (Type == GNU_PROPERTY_X86_FEATURE_2_NEEDED ? "needed: " : "used: ");
4784     if (DataSize != 4) {
4785       OS << format("<corrupt length: 0x%x>", DataSize);
4786       return OS.str();
4787     }
4788     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
4789     if (PrData == 0) {
4790       OS << "<None>";
4791       return OS.str();
4792     }
4793     DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86, "x86");
4794     DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87, "x87");
4795     DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX, "MMX");
4796     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM, "XMM");
4797     DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM, "YMM");
4798     DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM, "ZMM");
4799     DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR, "FXSR");
4800     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE, "XSAVE");
4801     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT, "XSAVEOPT");
4802     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC, "XSAVEC");
4803     if (PrData)
4804       OS << format("<unknown flags: 0x%x>", PrData);
4805     return OS.str();
4806   }
4807 }
4808 
4809 template <typename ELFT>
4810 static SmallVector<std::string, 4> getGNUPropertyList(ArrayRef<uint8_t> Arr) {
4811   using Elf_Word = typename ELFT::Word;
4812 
4813   SmallVector<std::string, 4> Properties;
4814   while (Arr.size() >= 8) {
4815     uint32_t Type = *reinterpret_cast<const Elf_Word *>(Arr.data());
4816     uint32_t DataSize = *reinterpret_cast<const Elf_Word *>(Arr.data() + 4);
4817     Arr = Arr.drop_front(8);
4818 
4819     // Take padding size into account if present.
4820     uint64_t PaddedSize = alignTo(DataSize, sizeof(typename ELFT::uint));
4821     std::string str;
4822     raw_string_ostream OS(str);
4823     if (Arr.size() < PaddedSize) {
4824       OS << format("<corrupt type (0x%x) datasz: 0x%x>", Type, DataSize);
4825       Properties.push_back(OS.str());
4826       break;
4827     }
4828     Properties.push_back(
4829         getGNUProperty<ELFT>(Type, DataSize, Arr.take_front(PaddedSize)));
4830     Arr = Arr.drop_front(PaddedSize);
4831   }
4832 
4833   if (!Arr.empty())
4834     Properties.push_back("<corrupted GNU_PROPERTY_TYPE_0>");
4835 
4836   return Properties;
4837 }
4838 
4839 struct GNUAbiTag {
4840   std::string OSName;
4841   std::string ABI;
4842   bool IsValid;
4843 };
4844 
4845 template <typename ELFT> static GNUAbiTag getGNUAbiTag(ArrayRef<uint8_t> Desc) {
4846   typedef typename ELFT::Word Elf_Word;
4847 
4848   ArrayRef<Elf_Word> Words(reinterpret_cast<const Elf_Word *>(Desc.begin()),
4849                            reinterpret_cast<const Elf_Word *>(Desc.end()));
4850 
4851   if (Words.size() < 4)
4852     return {"", "", /*IsValid=*/false};
4853 
4854   static const char *OSNames[] = {
4855       "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable", "NaCl",
4856   };
4857   StringRef OSName = "Unknown";
4858   if (Words[0] < array_lengthof(OSNames))
4859     OSName = OSNames[Words[0]];
4860   uint32_t Major = Words[1], Minor = Words[2], Patch = Words[3];
4861   std::string str;
4862   raw_string_ostream ABI(str);
4863   ABI << Major << "." << Minor << "." << Patch;
4864   return {std::string(OSName), ABI.str(), /*IsValid=*/true};
4865 }
4866 
4867 static std::string getGNUBuildId(ArrayRef<uint8_t> Desc) {
4868   std::string str;
4869   raw_string_ostream OS(str);
4870   for (uint8_t B : Desc)
4871     OS << format_hex_no_prefix(B, 2);
4872   return OS.str();
4873 }
4874 
4875 static StringRef getGNUGoldVersion(ArrayRef<uint8_t> Desc) {
4876   return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
4877 }
4878 
4879 template <typename ELFT>
4880 static void printGNUNote(raw_ostream &OS, uint32_t NoteType,
4881                          ArrayRef<uint8_t> Desc) {
4882   switch (NoteType) {
4883   default:
4884     return;
4885   case ELF::NT_GNU_ABI_TAG: {
4886     const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
4887     if (!AbiTag.IsValid)
4888       OS << "    <corrupt GNU_ABI_TAG>";
4889     else
4890       OS << "    OS: " << AbiTag.OSName << ", ABI: " << AbiTag.ABI;
4891     break;
4892   }
4893   case ELF::NT_GNU_BUILD_ID: {
4894     OS << "    Build ID: " << getGNUBuildId(Desc);
4895     break;
4896   }
4897   case ELF::NT_GNU_GOLD_VERSION:
4898     OS << "    Version: " << getGNUGoldVersion(Desc);
4899     break;
4900   case ELF::NT_GNU_PROPERTY_TYPE_0:
4901     OS << "    Properties:";
4902     for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
4903       OS << "    " << Property << "\n";
4904     break;
4905   }
4906   OS << '\n';
4907 }
4908 
4909 struct AMDNote {
4910   std::string Type;
4911   std::string Value;
4912 };
4913 
4914 template <typename ELFT>
4915 static AMDNote getAMDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
4916   switch (NoteType) {
4917   default:
4918     return {"", ""};
4919   case ELF::NT_AMD_AMDGPU_HSA_METADATA:
4920     return {
4921         "HSA Metadata",
4922         std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
4923   case ELF::NT_AMD_AMDGPU_ISA:
4924     return {
4925         "ISA Version",
4926         std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
4927   }
4928 }
4929 
4930 struct AMDGPUNote {
4931   std::string Type;
4932   std::string Value;
4933 };
4934 
4935 template <typename ELFT>
4936 static AMDGPUNote getAMDGPUNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
4937   switch (NoteType) {
4938   default:
4939     return {"", ""};
4940   case ELF::NT_AMDGPU_METADATA: {
4941     StringRef MsgPackString =
4942         StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
4943     msgpack::Document MsgPackDoc;
4944     if (!MsgPackDoc.readFromBlob(MsgPackString, /*Multi=*/false))
4945       return {"AMDGPU Metadata", "Invalid AMDGPU Metadata"};
4946 
4947     AMDGPU::HSAMD::V3::MetadataVerifier Verifier(true);
4948     std::string HSAMetadataString;
4949     if (!Verifier.verify(MsgPackDoc.getRoot()))
4950       HSAMetadataString = "Invalid AMDGPU Metadata\n";
4951 
4952     raw_string_ostream StrOS(HSAMetadataString);
4953     MsgPackDoc.toYAML(StrOS);
4954 
4955     return {"AMDGPU Metadata", StrOS.str()};
4956   }
4957   }
4958 }
4959 
4960 struct CoreFileMapping {
4961   uint64_t Start, End, Offset;
4962   StringRef Filename;
4963 };
4964 
4965 struct CoreNote {
4966   uint64_t PageSize;
4967   std::vector<CoreFileMapping> Mappings;
4968 };
4969 
4970 static Expected<CoreNote> readCoreNote(DataExtractor Desc) {
4971   // Expected format of the NT_FILE note description:
4972   // 1. # of file mappings (call it N)
4973   // 2. Page size
4974   // 3. N (start, end, offset) triples
4975   // 4. N packed filenames (null delimited)
4976   // Each field is an Elf_Addr, except for filenames which are char* strings.
4977 
4978   CoreNote Ret;
4979   const int Bytes = Desc.getAddressSize();
4980 
4981   if (!Desc.isValidOffsetForAddress(2))
4982     return createError("the note of size 0x" + Twine::utohexstr(Desc.size()) +
4983                        " is too short, expected at least 0x" +
4984                        Twine::utohexstr(Bytes * 2));
4985   if (Desc.getData().back() != 0)
4986     return createError("the note is not NUL terminated");
4987 
4988   uint64_t DescOffset = 0;
4989   uint64_t FileCount = Desc.getAddress(&DescOffset);
4990   Ret.PageSize = Desc.getAddress(&DescOffset);
4991 
4992   if (!Desc.isValidOffsetForAddress(3 * FileCount * Bytes))
4993     return createError("unable to read file mappings (found " +
4994                        Twine(FileCount) + "): the note of size 0x" +
4995                        Twine::utohexstr(Desc.size()) + " is too short");
4996 
4997   uint64_t FilenamesOffset = 0;
4998   DataExtractor Filenames(
4999       Desc.getData().drop_front(DescOffset + 3 * FileCount * Bytes),
5000       Desc.isLittleEndian(), Desc.getAddressSize());
5001 
5002   Ret.Mappings.resize(FileCount);
5003   size_t I = 0;
5004   for (CoreFileMapping &Mapping : Ret.Mappings) {
5005     ++I;
5006     if (!Filenames.isValidOffsetForDataOfSize(FilenamesOffset, 1))
5007       return createError(
5008           "unable to read the file name for the mapping with index " +
5009           Twine(I) + ": the note of size 0x" + Twine::utohexstr(Desc.size()) +
5010           " is truncated");
5011     Mapping.Start = Desc.getAddress(&DescOffset);
5012     Mapping.End = Desc.getAddress(&DescOffset);
5013     Mapping.Offset = Desc.getAddress(&DescOffset);
5014     Mapping.Filename = Filenames.getCStrRef(&FilenamesOffset);
5015   }
5016 
5017   return Ret;
5018 }
5019 
5020 template <typename ELFT>
5021 static void printCoreNote(raw_ostream &OS, const CoreNote &Note) {
5022   // Length of "0x<address>" string.
5023   const int FieldWidth = ELFT::Is64Bits ? 18 : 10;
5024 
5025   OS << "    Page size: " << format_decimal(Note.PageSize, 0) << '\n';
5026   OS << "    " << right_justify("Start", FieldWidth) << "  "
5027      << right_justify("End", FieldWidth) << "  "
5028      << right_justify("Page Offset", FieldWidth) << '\n';
5029   for (const CoreFileMapping &Mapping : Note.Mappings) {
5030     OS << "    " << format_hex(Mapping.Start, FieldWidth) << "  "
5031        << format_hex(Mapping.End, FieldWidth) << "  "
5032        << format_hex(Mapping.Offset, FieldWidth) << "\n        "
5033        << Mapping.Filename << '\n';
5034   }
5035 }
5036 
5037 static const NoteType GenericNoteTypes[] = {
5038     {ELF::NT_VERSION, "NT_VERSION (version)"},
5039     {ELF::NT_ARCH, "NT_ARCH (architecture)"},
5040     {ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN, "OPEN"},
5041     {ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC, "func"},
5042 };
5043 
5044 static const NoteType GNUNoteTypes[] = {
5045     {ELF::NT_GNU_ABI_TAG, "NT_GNU_ABI_TAG (ABI version tag)"},
5046     {ELF::NT_GNU_HWCAP, "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"},
5047     {ELF::NT_GNU_BUILD_ID, "NT_GNU_BUILD_ID (unique build ID bitstring)"},
5048     {ELF::NT_GNU_GOLD_VERSION, "NT_GNU_GOLD_VERSION (gold version)"},
5049     {ELF::NT_GNU_PROPERTY_TYPE_0, "NT_GNU_PROPERTY_TYPE_0 (property note)"},
5050 };
5051 
5052 static const NoteType FreeBSDNoteTypes[] = {
5053     {ELF::NT_FREEBSD_THRMISC, "NT_THRMISC (thrmisc structure)"},
5054     {ELF::NT_FREEBSD_PROCSTAT_PROC, "NT_PROCSTAT_PROC (proc data)"},
5055     {ELF::NT_FREEBSD_PROCSTAT_FILES, "NT_PROCSTAT_FILES (files data)"},
5056     {ELF::NT_FREEBSD_PROCSTAT_VMMAP, "NT_PROCSTAT_VMMAP (vmmap data)"},
5057     {ELF::NT_FREEBSD_PROCSTAT_GROUPS, "NT_PROCSTAT_GROUPS (groups data)"},
5058     {ELF::NT_FREEBSD_PROCSTAT_UMASK, "NT_PROCSTAT_UMASK (umask data)"},
5059     {ELF::NT_FREEBSD_PROCSTAT_RLIMIT, "NT_PROCSTAT_RLIMIT (rlimit data)"},
5060     {ELF::NT_FREEBSD_PROCSTAT_OSREL, "NT_PROCSTAT_OSREL (osreldate data)"},
5061     {ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS,
5062      "NT_PROCSTAT_PSSTRINGS (ps_strings data)"},
5063     {ELF::NT_FREEBSD_PROCSTAT_AUXV, "NT_PROCSTAT_AUXV (auxv data)"},
5064 };
5065 
5066 static const NoteType AMDNoteTypes[] = {
5067     {ELF::NT_AMD_AMDGPU_HSA_METADATA,
5068      "NT_AMD_AMDGPU_HSA_METADATA (HSA Metadata)"},
5069     {ELF::NT_AMD_AMDGPU_ISA, "NT_AMD_AMDGPU_ISA (ISA Version)"},
5070     {ELF::NT_AMD_AMDGPU_PAL_METADATA,
5071      "NT_AMD_AMDGPU_PAL_METADATA (PAL Metadata)"},
5072 };
5073 
5074 static const NoteType AMDGPUNoteTypes[] = {
5075     {ELF::NT_AMDGPU_METADATA, "NT_AMDGPU_METADATA (AMDGPU Metadata)"},
5076 };
5077 
5078 static const NoteType CoreNoteTypes[] = {
5079     {ELF::NT_PRSTATUS, "NT_PRSTATUS (prstatus structure)"},
5080     {ELF::NT_FPREGSET, "NT_FPREGSET (floating point registers)"},
5081     {ELF::NT_PRPSINFO, "NT_PRPSINFO (prpsinfo structure)"},
5082     {ELF::NT_TASKSTRUCT, "NT_TASKSTRUCT (task structure)"},
5083     {ELF::NT_AUXV, "NT_AUXV (auxiliary vector)"},
5084     {ELF::NT_PSTATUS, "NT_PSTATUS (pstatus structure)"},
5085     {ELF::NT_FPREGS, "NT_FPREGS (floating point registers)"},
5086     {ELF::NT_PSINFO, "NT_PSINFO (psinfo structure)"},
5087     {ELF::NT_LWPSTATUS, "NT_LWPSTATUS (lwpstatus_t structure)"},
5088     {ELF::NT_LWPSINFO, "NT_LWPSINFO (lwpsinfo_t structure)"},
5089     {ELF::NT_WIN32PSTATUS, "NT_WIN32PSTATUS (win32_pstatus structure)"},
5090 
5091     {ELF::NT_PPC_VMX, "NT_PPC_VMX (ppc Altivec registers)"},
5092     {ELF::NT_PPC_VSX, "NT_PPC_VSX (ppc VSX registers)"},
5093     {ELF::NT_PPC_TAR, "NT_PPC_TAR (ppc TAR register)"},
5094     {ELF::NT_PPC_PPR, "NT_PPC_PPR (ppc PPR register)"},
5095     {ELF::NT_PPC_DSCR, "NT_PPC_DSCR (ppc DSCR register)"},
5096     {ELF::NT_PPC_EBB, "NT_PPC_EBB (ppc EBB registers)"},
5097     {ELF::NT_PPC_PMU, "NT_PPC_PMU (ppc PMU registers)"},
5098     {ELF::NT_PPC_TM_CGPR, "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"},
5099     {ELF::NT_PPC_TM_CFPR,
5100      "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"},
5101     {ELF::NT_PPC_TM_CVMX,
5102      "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"},
5103     {ELF::NT_PPC_TM_CVSX, "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"},
5104     {ELF::NT_PPC_TM_SPR, "NT_PPC_TM_SPR (ppc TM special purpose registers)"},
5105     {ELF::NT_PPC_TM_CTAR, "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"},
5106     {ELF::NT_PPC_TM_CPPR, "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"},
5107     {ELF::NT_PPC_TM_CDSCR, "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"},
5108 
5109     {ELF::NT_386_TLS, "NT_386_TLS (x86 TLS information)"},
5110     {ELF::NT_386_IOPERM, "NT_386_IOPERM (x86 I/O permissions)"},
5111     {ELF::NT_X86_XSTATE, "NT_X86_XSTATE (x86 XSAVE extended state)"},
5112 
5113     {ELF::NT_S390_HIGH_GPRS, "NT_S390_HIGH_GPRS (s390 upper register halves)"},
5114     {ELF::NT_S390_TIMER, "NT_S390_TIMER (s390 timer register)"},
5115     {ELF::NT_S390_TODCMP, "NT_S390_TODCMP (s390 TOD comparator register)"},
5116     {ELF::NT_S390_TODPREG, "NT_S390_TODPREG (s390 TOD programmable register)"},
5117     {ELF::NT_S390_CTRS, "NT_S390_CTRS (s390 control registers)"},
5118     {ELF::NT_S390_PREFIX, "NT_S390_PREFIX (s390 prefix register)"},
5119     {ELF::NT_S390_LAST_BREAK,
5120      "NT_S390_LAST_BREAK (s390 last breaking event address)"},
5121     {ELF::NT_S390_SYSTEM_CALL,
5122      "NT_S390_SYSTEM_CALL (s390 system call restart data)"},
5123     {ELF::NT_S390_TDB, "NT_S390_TDB (s390 transaction diagnostic block)"},
5124     {ELF::NT_S390_VXRS_LOW,
5125      "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"},
5126     {ELF::NT_S390_VXRS_HIGH, "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"},
5127     {ELF::NT_S390_GS_CB, "NT_S390_GS_CB (s390 guarded-storage registers)"},
5128     {ELF::NT_S390_GS_BC,
5129      "NT_S390_GS_BC (s390 guarded-storage broadcast control)"},
5130 
5131     {ELF::NT_ARM_VFP, "NT_ARM_VFP (arm VFP registers)"},
5132     {ELF::NT_ARM_TLS, "NT_ARM_TLS (AArch TLS registers)"},
5133     {ELF::NT_ARM_HW_BREAK,
5134      "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"},
5135     {ELF::NT_ARM_HW_WATCH,
5136      "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"},
5137 
5138     {ELF::NT_FILE, "NT_FILE (mapped files)"},
5139     {ELF::NT_PRXFPREG, "NT_PRXFPREG (user_xfpregs structure)"},
5140     {ELF::NT_SIGINFO, "NT_SIGINFO (siginfo_t data)"},
5141 };
5142 
5143 template <class ELFT>
5144 const StringRef getNoteTypeName(const typename ELFT::Note &Note,
5145                                 unsigned ELFType) {
5146   uint32_t Type = Note.getType();
5147   auto FindNote = [&](ArrayRef<NoteType> V) -> StringRef {
5148     for (const NoteType &N : V)
5149       if (N.ID == Type)
5150         return N.Name;
5151     return "";
5152   };
5153 
5154   StringRef Name = Note.getName();
5155   if (Name == "GNU")
5156     return FindNote(GNUNoteTypes);
5157   if (Name == "FreeBSD")
5158     return FindNote(FreeBSDNoteTypes);
5159   if (Name == "AMD")
5160     return FindNote(AMDNoteTypes);
5161   if (Name == "AMDGPU")
5162     return FindNote(AMDGPUNoteTypes);
5163 
5164   if (ELFType == ELF::ET_CORE)
5165     return FindNote(CoreNoteTypes);
5166   return FindNote(GenericNoteTypes);
5167 }
5168 
5169 template <class ELFT>
5170 static void printNotesHelper(
5171     const ELFDumper<ELFT> &Dumper,
5172     llvm::function_ref<void(Optional<StringRef>, typename ELFT::Off,
5173                             typename ELFT::Addr)>
5174         StartNotesFn,
5175     llvm::function_ref<Error(const typename ELFT::Note &)> ProcessNoteFn,
5176     llvm::function_ref<void()> FinishNotesFn) {
5177   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
5178 
5179   ArrayRef<typename ELFT::Shdr> Sections = cantFail(Obj.sections());
5180   if (Obj.getHeader().e_type != ELF::ET_CORE && !Sections.empty()) {
5181     for (const typename ELFT::Shdr &S : Sections) {
5182       if (S.sh_type != SHT_NOTE)
5183         continue;
5184       StartNotesFn(expectedToOptional(Obj.getSectionName(S)), S.sh_offset,
5185                    S.sh_size);
5186       Error Err = Error::success();
5187       size_t I = 0;
5188       for (const typename ELFT::Note Note : Obj.notes(S, Err)) {
5189         if (Error E = ProcessNoteFn(Note))
5190           Dumper.reportUniqueWarning(
5191               "unable to read note with index " + Twine(I) + " from the " +
5192               describe(Obj, S) + ": " + toString(std::move(E)));
5193         ++I;
5194       }
5195       if (Err)
5196         Dumper.reportUniqueWarning("unable to read notes from the " +
5197                                    describe(Obj, S) + ": " +
5198                                    toString(std::move(Err)));
5199       FinishNotesFn();
5200     }
5201     return;
5202   }
5203 
5204   Expected<ArrayRef<typename ELFT::Phdr>> PhdrsOrErr = Obj.program_headers();
5205   if (!PhdrsOrErr) {
5206     Dumper.reportUniqueWarning(
5207         "unable to read program headers to locate the PT_NOTE segment: " +
5208         toString(PhdrsOrErr.takeError()));
5209     return;
5210   }
5211 
5212   for (size_t I = 0, E = (*PhdrsOrErr).size(); I != E; ++I) {
5213     const typename ELFT::Phdr &P = (*PhdrsOrErr)[I];
5214     if (P.p_type != PT_NOTE)
5215       continue;
5216     StartNotesFn(/*SecName=*/None, P.p_offset, P.p_filesz);
5217     Error Err = Error::success();
5218     size_t Index = 0;
5219     for (const typename ELFT::Note Note : Obj.notes(P, Err)) {
5220       if (Error E = ProcessNoteFn(Note))
5221         Dumper.reportUniqueWarning("unable to read note with index " +
5222                                    Twine(Index) +
5223                                    " from the PT_NOTE segment with index " +
5224                                    Twine(I) + ": " + toString(std::move(E)));
5225       ++Index;
5226     }
5227     if (Err)
5228       Dumper.reportUniqueWarning(
5229           "unable to read notes from the PT_NOTE segment with index " +
5230           Twine(I) + ": " + toString(std::move(Err)));
5231     FinishNotesFn();
5232   }
5233 }
5234 
5235 template <class ELFT> void GNUELFDumper<ELFT>::printNotes() {
5236   auto PrintHeader = [&](Optional<StringRef> SecName,
5237                          const typename ELFT::Off Offset,
5238                          const typename ELFT::Addr Size) {
5239     OS << "Displaying notes found ";
5240 
5241     if (SecName)
5242       OS << "in: " << *SecName << "\n";
5243     else
5244       OS << "at file offset " << format_hex(Offset, 10) << " with length "
5245          << format_hex(Size, 10) << ":\n";
5246 
5247     OS << "  Owner                Data size \tDescription\n";
5248   };
5249 
5250   auto ProcessNote = [&](const Elf_Note &Note) -> Error {
5251     StringRef Name = Note.getName();
5252     ArrayRef<uint8_t> Descriptor = Note.getDesc();
5253     Elf_Word Type = Note.getType();
5254 
5255     // Print the note owner/type.
5256     OS << "  " << left_justify(Name, 20) << ' '
5257        << format_hex(Descriptor.size(), 10) << '\t';
5258 
5259     StringRef NoteType =
5260         getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
5261     if (!NoteType.empty())
5262       OS << NoteType << '\n';
5263     else
5264       OS << "Unknown note type: (" << format_hex(Type, 10) << ")\n";
5265 
5266     // Print the description, or fallback to printing raw bytes for unknown
5267     // owners.
5268     if (Name == "GNU") {
5269       printGNUNote<ELFT>(OS, Type, Descriptor);
5270     } else if (Name == "AMD") {
5271       const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
5272       if (!N.Type.empty())
5273         OS << "    " << N.Type << ":\n        " << N.Value << '\n';
5274     } else if (Name == "AMDGPU") {
5275       const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
5276       if (!N.Type.empty())
5277         OS << "    " << N.Type << ":\n        " << N.Value << '\n';
5278     } else if (Name == "CORE") {
5279       if (Type == ELF::NT_FILE) {
5280         DataExtractor DescExtractor(Descriptor,
5281                                     ELFT::TargetEndianness == support::little,
5282                                     sizeof(Elf_Addr));
5283         if (Expected<CoreNote> NoteOrErr = readCoreNote(DescExtractor))
5284           printCoreNote<ELFT>(OS, *NoteOrErr);
5285         else
5286           return NoteOrErr.takeError();
5287       }
5288     } else if (!Descriptor.empty()) {
5289       OS << "   description data:";
5290       for (uint8_t B : Descriptor)
5291         OS << " " << format("%02x", B);
5292       OS << '\n';
5293     }
5294     return Error::success();
5295   };
5296 
5297   printNotesHelper(*this, PrintHeader, ProcessNote, []() {});
5298 }
5299 
5300 template <class ELFT> void GNUELFDumper<ELFT>::printELFLinkerOptions() {
5301   OS << "printELFLinkerOptions not implemented!\n";
5302 }
5303 
5304 template <class ELFT>
5305 void ELFDumper<ELFT>::printDependentLibsHelper(
5306     function_ref<void(const Elf_Shdr &)> OnSectionStart,
5307     function_ref<void(StringRef, uint64_t)> OnLibEntry) {
5308   auto Warn = [this](unsigned SecNdx, StringRef Msg) {
5309     this->reportUniqueWarning("SHT_LLVM_DEPENDENT_LIBRARIES section at index " +
5310                               Twine(SecNdx) + " is broken: " + Msg);
5311   };
5312 
5313   unsigned I = -1;
5314   for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
5315     ++I;
5316     if (Shdr.sh_type != ELF::SHT_LLVM_DEPENDENT_LIBRARIES)
5317       continue;
5318 
5319     OnSectionStart(Shdr);
5320 
5321     Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Shdr);
5322     if (!ContentsOrErr) {
5323       Warn(I, toString(ContentsOrErr.takeError()));
5324       continue;
5325     }
5326 
5327     ArrayRef<uint8_t> Contents = *ContentsOrErr;
5328     if (!Contents.empty() && Contents.back() != 0) {
5329       Warn(I, "the content is not null-terminated");
5330       continue;
5331     }
5332 
5333     for (const uint8_t *I = Contents.begin(), *E = Contents.end(); I < E;) {
5334       StringRef Lib((const char *)I);
5335       OnLibEntry(Lib, I - Contents.begin());
5336       I += Lib.size() + 1;
5337     }
5338   }
5339 }
5340 
5341 template <class ELFT>
5342 void ELFDumper<ELFT>::forEachRelocationDo(
5343     const Elf_Shdr &Sec, bool RawRelr,
5344     llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
5345                             const Elf_Shdr &, const Elf_Shdr *)>
5346         RelRelaFn,
5347     llvm::function_ref<void(const Elf_Relr &)> RelrFn) {
5348   auto Warn = [&](Error &&E,
5349                   const Twine &Prefix = "unable to read relocations from") {
5350     this->reportUniqueWarning(Prefix + " " + describe(Sec) + ": " +
5351                               toString(std::move(E)));
5352   };
5353 
5354   // SHT_RELR/SHT_ANDROID_RELR sections do not have an associated symbol table.
5355   // For them we should not treat the value of the sh_link field as an index of
5356   // a symbol table.
5357   const Elf_Shdr *SymTab;
5358   if (Sec.sh_type != ELF::SHT_RELR && Sec.sh_type != ELF::SHT_ANDROID_RELR) {
5359     Expected<const Elf_Shdr *> SymTabOrErr = Obj.getSection(Sec.sh_link);
5360     if (!SymTabOrErr) {
5361       Warn(SymTabOrErr.takeError(), "unable to locate a symbol table for");
5362       return;
5363     }
5364     SymTab = *SymTabOrErr;
5365   }
5366 
5367   unsigned RelNdx = 0;
5368   const bool IsMips64EL = this->Obj.isMips64EL();
5369   switch (Sec.sh_type) {
5370   case ELF::SHT_REL:
5371     if (Expected<Elf_Rel_Range> RangeOrErr = Obj.rels(Sec)) {
5372       for (const Elf_Rel &R : *RangeOrErr)
5373         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5374     } else {
5375       Warn(RangeOrErr.takeError());
5376     }
5377     break;
5378   case ELF::SHT_RELA:
5379     if (Expected<Elf_Rela_Range> RangeOrErr = Obj.relas(Sec)) {
5380       for (const Elf_Rela &R : *RangeOrErr)
5381         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5382     } else {
5383       Warn(RangeOrErr.takeError());
5384     }
5385     break;
5386   case ELF::SHT_RELR:
5387   case ELF::SHT_ANDROID_RELR: {
5388     Expected<Elf_Relr_Range> RangeOrErr = Obj.relrs(Sec);
5389     if (!RangeOrErr) {
5390       Warn(RangeOrErr.takeError());
5391       break;
5392     }
5393     if (RawRelr) {
5394       for (const Elf_Relr &R : *RangeOrErr)
5395         RelrFn(R);
5396       break;
5397     }
5398 
5399     for (const Elf_Rel &R : Obj.decode_relrs(*RangeOrErr))
5400       RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec,
5401                 /*SymTab=*/nullptr);
5402     break;
5403   }
5404   case ELF::SHT_ANDROID_REL:
5405   case ELF::SHT_ANDROID_RELA:
5406     if (Expected<std::vector<Elf_Rela>> RelasOrErr = Obj.android_relas(Sec)) {
5407       for (const Elf_Rela &R : *RelasOrErr)
5408         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5409     } else {
5410       Warn(RelasOrErr.takeError());
5411     }
5412     break;
5413   }
5414 }
5415 
5416 template <class ELFT>
5417 StringRef ELFDumper<ELFT>::getPrintableSectionName(const Elf_Shdr &Sec) const {
5418   StringRef Name = "<?>";
5419   if (Expected<StringRef> SecNameOrErr =
5420           Obj.getSectionName(Sec, this->WarningHandler))
5421     Name = *SecNameOrErr;
5422   else
5423     this->reportUniqueWarning("unable to get the name of " + describe(Sec) +
5424                               ": " + toString(SecNameOrErr.takeError()));
5425   return Name;
5426 }
5427 
5428 template <class ELFT> void GNUELFDumper<ELFT>::printDependentLibs() {
5429   bool SectionStarted = false;
5430   struct NameOffset {
5431     StringRef Name;
5432     uint64_t Offset;
5433   };
5434   std::vector<NameOffset> SecEntries;
5435   NameOffset Current;
5436   auto PrintSection = [&]() {
5437     OS << "Dependent libraries section " << Current.Name << " at offset "
5438        << format_hex(Current.Offset, 1) << " contains " << SecEntries.size()
5439        << " entries:\n";
5440     for (NameOffset Entry : SecEntries)
5441       OS << "  [" << format("%6" PRIx64, Entry.Offset) << "]  " << Entry.Name
5442          << "\n";
5443     OS << "\n";
5444     SecEntries.clear();
5445   };
5446 
5447   auto OnSectionStart = [&](const Elf_Shdr &Shdr) {
5448     if (SectionStarted)
5449       PrintSection();
5450     SectionStarted = true;
5451     Current.Offset = Shdr.sh_offset;
5452     Current.Name = this->getPrintableSectionName(Shdr);
5453   };
5454   auto OnLibEntry = [&](StringRef Lib, uint64_t Offset) {
5455     SecEntries.push_back(NameOffset{Lib, Offset});
5456   };
5457 
5458   this->printDependentLibsHelper(OnSectionStart, OnLibEntry);
5459   if (SectionStarted)
5460     PrintSection();
5461 }
5462 
5463 template <class ELFT>
5464 bool ELFDumper<ELFT>::printFunctionStackSize(
5465     uint64_t SymValue, Optional<const Elf_Shdr *> FunctionSec,
5466     const Elf_Shdr &StackSizeSec, DataExtractor Data, uint64_t *Offset) {
5467   uint32_t FuncSymIndex = 0;
5468   if (this->DotSymtabSec) {
5469     if (Expected<Elf_Sym_Range> SymsOrError = Obj.symbols(this->DotSymtabSec)) {
5470       uint32_t Index = (uint32_t)-1;
5471       for (const Elf_Sym &Sym : *SymsOrError) {
5472         ++Index;
5473 
5474         if (Sym.st_shndx == ELF::SHN_UNDEF || Sym.getType() != ELF::STT_FUNC)
5475           continue;
5476 
5477         if (Expected<uint64_t> SymAddrOrErr =
5478                 ObjF.toSymbolRef(this->DotSymtabSec, Index).getAddress()) {
5479           if (SymValue != *SymAddrOrErr)
5480             continue;
5481         } else {
5482           std::string Name = this->getStaticSymbolName(Index);
5483           reportUniqueWarning("unable to get address of symbol '" + Name +
5484                               "': " + toString(SymAddrOrErr.takeError()));
5485           break;
5486         }
5487 
5488         // Check if the symbol is in the right section. FunctionSec == None
5489         // means "any section".
5490         if (FunctionSec) {
5491           if (Expected<const Elf_Shdr *> SecOrErr =
5492                   Obj.getSection(Sym, this->DotSymtabSec,
5493                                  this->getShndxTable(this->DotSymtabSec))) {
5494             if (*FunctionSec != *SecOrErr)
5495               continue;
5496           } else {
5497             std::string Name = this->getStaticSymbolName(Index);
5498             // Note: it is impossible to trigger this error currently, it is
5499             // untested.
5500             reportUniqueWarning("unable to get section of symbol '" + Name +
5501                                 "': " + toString(SecOrErr.takeError()));
5502             break;
5503           }
5504         }
5505 
5506         FuncSymIndex = Index;
5507         break;
5508       }
5509     } else {
5510       reportUniqueWarning("unable to read the symbol table: " +
5511                           toString(SymsOrError.takeError()));
5512     }
5513   }
5514 
5515   std::string FuncName = "?";
5516   if (!FuncSymIndex)
5517     reportUniqueWarning(
5518         "could not identify function symbol for stack size entry in " +
5519         describe(StackSizeSec));
5520   else
5521     FuncName = this->getStaticSymbolName(FuncSymIndex);
5522 
5523   // Extract the size. The expectation is that Offset is pointing to the right
5524   // place, i.e. past the function address.
5525   Error Err = Error::success();
5526   uint64_t StackSize = Data.getULEB128(Offset, &Err);
5527   if (Err) {
5528     reportUniqueWarning("could not extract a valid stack size from " +
5529                         describe(StackSizeSec) + ": " +
5530                         toString(std::move(Err)));
5531     return false;
5532   }
5533   printStackSizeEntry(StackSize, FuncName);
5534   return true;
5535 }
5536 
5537 template <class ELFT>
5538 void GNUELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
5539                                              StringRef FuncName) {
5540   OS.PadToColumn(2);
5541   OS << format_decimal(Size, 11);
5542   OS.PadToColumn(18);
5543   OS << FuncName << "\n";
5544 }
5545 
5546 template <class ELFT>
5547 void ELFDumper<ELFT>::printStackSize(const Relocation<ELFT> &R,
5548                                      const Elf_Shdr &RelocSec, unsigned Ndx,
5549                                      const Elf_Shdr *SymTab,
5550                                      const Elf_Shdr *FunctionSec,
5551                                      const Elf_Shdr &StackSizeSec,
5552                                      const RelocationResolver &Resolver,
5553                                      DataExtractor Data) {
5554   // This function ignores potentially erroneous input, unless it is directly
5555   // related to stack size reporting.
5556   const Elf_Sym *Sym = nullptr;
5557   Expected<RelSymbol<ELFT>> TargetOrErr = this->getRelocationTarget(R, SymTab);
5558   if (!TargetOrErr)
5559     reportUniqueWarning("unable to get the target of relocation with index " +
5560                         Twine(Ndx) + " in " + describe(RelocSec) + ": " +
5561                         toString(TargetOrErr.takeError()));
5562   else
5563     Sym = TargetOrErr->Sym;
5564 
5565   uint64_t RelocSymValue = 0;
5566   if (Sym) {
5567     Expected<const Elf_Shdr *> SectionOrErr =
5568         this->Obj.getSection(*Sym, SymTab, this->getShndxTable(SymTab));
5569     if (!SectionOrErr) {
5570       reportUniqueWarning(
5571           "cannot identify the section for relocation symbol '" +
5572           (*TargetOrErr).Name + "': " + toString(SectionOrErr.takeError()));
5573     } else if (*SectionOrErr != FunctionSec) {
5574       reportUniqueWarning("relocation symbol '" + (*TargetOrErr).Name +
5575                           "' is not in the expected section");
5576       // Pretend that the symbol is in the correct section and report its
5577       // stack size anyway.
5578       FunctionSec = *SectionOrErr;
5579     }
5580 
5581     RelocSymValue = Sym->st_value;
5582   }
5583 
5584   uint64_t Offset = R.Offset;
5585   if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
5586     reportUniqueWarning("found invalid relocation offset (0x" +
5587                         Twine::utohexstr(Offset) + ") into " +
5588                         describe(StackSizeSec) +
5589                         " while trying to extract a stack size entry");
5590     return;
5591   }
5592 
5593   uint64_t SymValue =
5594       Resolver(R.Type, Offset, RelocSymValue, Data.getAddress(&Offset),
5595                R.Addend.getValueOr(0));
5596   this->printFunctionStackSize(SymValue, FunctionSec, StackSizeSec, Data,
5597                                &Offset);
5598 }
5599 
5600 template <class ELFT>
5601 void ELFDumper<ELFT>::printNonRelocatableStackSizes(
5602     std::function<void()> PrintHeader) {
5603   // This function ignores potentially erroneous input, unless it is directly
5604   // related to stack size reporting.
5605   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
5606     if (this->getPrintableSectionName(Sec) != ".stack_sizes")
5607       continue;
5608     PrintHeader();
5609     ArrayRef<uint8_t> Contents =
5610         unwrapOrError(this->FileName, Obj.getSectionContents(Sec));
5611     DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
5612     uint64_t Offset = 0;
5613     while (Offset < Contents.size()) {
5614       // The function address is followed by a ULEB representing the stack
5615       // size. Check for an extra byte before we try to process the entry.
5616       if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
5617         reportUniqueWarning(
5618             describe(Sec) +
5619             " ended while trying to extract a stack size entry");
5620         break;
5621       }
5622       uint64_t SymValue = Data.getAddress(&Offset);
5623       if (!printFunctionStackSize(SymValue, /*FunctionSec=*/None, Sec, Data,
5624                                   &Offset))
5625         break;
5626     }
5627   }
5628 }
5629 
5630 template <class ELFT>
5631 void ELFDumper<ELFT>::printRelocatableStackSizes(
5632     std::function<void()> PrintHeader) {
5633   // Build a map between stack size sections and their corresponding relocation
5634   // sections.
5635   llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> StackSizeRelocMap;
5636   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
5637     StringRef SectionName;
5638     if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec))
5639       SectionName = *NameOrErr;
5640     else
5641       consumeError(NameOrErr.takeError());
5642 
5643     // A stack size section that we haven't encountered yet is mapped to the
5644     // null section until we find its corresponding relocation section.
5645     if (SectionName == ".stack_sizes")
5646       if (StackSizeRelocMap
5647               .insert(std::make_pair(&Sec, (const Elf_Shdr *)nullptr))
5648               .second)
5649         continue;
5650 
5651     // Check relocation sections if they are relocating contents of a
5652     // stack sizes section.
5653     if (Sec.sh_type != ELF::SHT_RELA && Sec.sh_type != ELF::SHT_REL)
5654       continue;
5655 
5656     Expected<const Elf_Shdr *> RelSecOrErr = Obj.getSection(Sec.sh_info);
5657     if (!RelSecOrErr) {
5658       reportUniqueWarning(describe(Sec) +
5659                           ": failed to get a relocated section: " +
5660                           toString(RelSecOrErr.takeError()));
5661       continue;
5662     }
5663 
5664     const Elf_Shdr *ContentsSec = *RelSecOrErr;
5665     if (this->getPrintableSectionName(**RelSecOrErr) != ".stack_sizes")
5666       continue;
5667 
5668     // Insert a mapping from the stack sizes section to its relocation section.
5669     StackSizeRelocMap[ContentsSec] = &Sec;
5670   }
5671 
5672   for (const auto &StackSizeMapEntry : StackSizeRelocMap) {
5673     PrintHeader();
5674     const Elf_Shdr *StackSizesELFSec = StackSizeMapEntry.first;
5675     const Elf_Shdr *RelocSec = StackSizeMapEntry.second;
5676 
5677     // Warn about stack size sections without a relocation section.
5678     if (!RelocSec) {
5679       reportWarning(createError(".stack_sizes (" + describe(*StackSizesELFSec) +
5680                                 ") does not have a corresponding "
5681                                 "relocation section"),
5682                     FileName);
5683       continue;
5684     }
5685 
5686     // A .stack_sizes section header's sh_link field is supposed to point
5687     // to the section that contains the functions whose stack sizes are
5688     // described in it.
5689     const Elf_Shdr *FunctionSec = unwrapOrError(
5690         this->FileName, Obj.getSection(StackSizesELFSec->sh_link));
5691 
5692     SupportsRelocation IsSupportedFn;
5693     RelocationResolver Resolver;
5694     std::tie(IsSupportedFn, Resolver) = getRelocationResolver(this->ObjF);
5695     ArrayRef<uint8_t> Contents =
5696         unwrapOrError(this->FileName, Obj.getSectionContents(*StackSizesELFSec));
5697     DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
5698 
5699     forEachRelocationDo(
5700         *RelocSec, /*RawRelr=*/false,
5701         [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
5702             const Elf_Shdr *SymTab) {
5703           if (!IsSupportedFn || !IsSupportedFn(R.Type)) {
5704             reportUniqueWarning(
5705                 describe(*RelocSec) +
5706                 " contains an unsupported relocation with index " + Twine(Ndx) +
5707                 ": " + Obj.getRelocationTypeName(R.Type));
5708             return;
5709           }
5710 
5711           this->printStackSize(R, *RelocSec, Ndx, SymTab, FunctionSec,
5712                                *StackSizesELFSec, Resolver, Data);
5713         },
5714         [](const Elf_Relr &) {
5715           llvm_unreachable("can't get here, because we only support "
5716                            "SHT_REL/SHT_RELA sections");
5717         });
5718   }
5719 }
5720 
5721 template <class ELFT>
5722 void GNUELFDumper<ELFT>::printStackSizes() {
5723   bool HeaderHasBeenPrinted = false;
5724   auto PrintHeader = [&]() {
5725     if (HeaderHasBeenPrinted)
5726       return;
5727     OS << "\nStack Sizes:\n";
5728     OS.PadToColumn(9);
5729     OS << "Size";
5730     OS.PadToColumn(18);
5731     OS << "Function\n";
5732     HeaderHasBeenPrinted = true;
5733   };
5734 
5735   // For non-relocatable objects, look directly for sections whose name starts
5736   // with .stack_sizes and process the contents.
5737   if (this->Obj.getHeader().e_type == ELF::ET_REL)
5738     this->printRelocatableStackSizes(PrintHeader);
5739   else
5740     this->printNonRelocatableStackSizes(PrintHeader);
5741 }
5742 
5743 template <class ELFT>
5744 void GNUELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
5745   size_t Bias = ELFT::Is64Bits ? 8 : 0;
5746   auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
5747     OS.PadToColumn(2);
5748     OS << format_hex_no_prefix(Parser.getGotAddress(E), 8 + Bias);
5749     OS.PadToColumn(11 + Bias);
5750     OS << format_decimal(Parser.getGotOffset(E), 6) << "(gp)";
5751     OS.PadToColumn(22 + Bias);
5752     OS << format_hex_no_prefix(*E, 8 + Bias);
5753     OS.PadToColumn(31 + 2 * Bias);
5754     OS << Purpose << "\n";
5755   };
5756 
5757   OS << (Parser.IsStatic ? "Static GOT:\n" : "Primary GOT:\n");
5758   OS << " Canonical gp value: "
5759      << format_hex_no_prefix(Parser.getGp(), 8 + Bias) << "\n\n";
5760 
5761   OS << " Reserved entries:\n";
5762   if (ELFT::Is64Bits)
5763     OS << "           Address     Access          Initial Purpose\n";
5764   else
5765     OS << "   Address     Access  Initial Purpose\n";
5766   PrintEntry(Parser.getGotLazyResolver(), "Lazy resolver");
5767   if (Parser.getGotModulePointer())
5768     PrintEntry(Parser.getGotModulePointer(), "Module pointer (GNU extension)");
5769 
5770   if (!Parser.getLocalEntries().empty()) {
5771     OS << "\n";
5772     OS << " Local entries:\n";
5773     if (ELFT::Is64Bits)
5774       OS << "           Address     Access          Initial\n";
5775     else
5776       OS << "   Address     Access  Initial\n";
5777     for (auto &E : Parser.getLocalEntries())
5778       PrintEntry(&E, "");
5779   }
5780 
5781   if (Parser.IsStatic)
5782     return;
5783 
5784   if (!Parser.getGlobalEntries().empty()) {
5785     OS << "\n";
5786     OS << " Global entries:\n";
5787     if (ELFT::Is64Bits)
5788       OS << "           Address     Access          Initial         Sym.Val."
5789          << " Type    Ndx Name\n";
5790     else
5791       OS << "   Address     Access  Initial Sym.Val. Type    Ndx Name\n";
5792 
5793     DataRegion<Elf_Word> ShndxTable(
5794         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
5795     for (auto &E : Parser.getGlobalEntries()) {
5796       const Elf_Sym &Sym = *Parser.getGotSym(&E);
5797       const Elf_Sym &FirstSym = this->dynamic_symbols()[0];
5798       std::string SymName = this->getFullSymbolName(
5799           Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
5800 
5801       OS.PadToColumn(2);
5802       OS << to_string(format_hex_no_prefix(Parser.getGotAddress(&E), 8 + Bias));
5803       OS.PadToColumn(11 + Bias);
5804       OS << to_string(format_decimal(Parser.getGotOffset(&E), 6)) + "(gp)";
5805       OS.PadToColumn(22 + Bias);
5806       OS << to_string(format_hex_no_prefix(E, 8 + Bias));
5807       OS.PadToColumn(31 + 2 * Bias);
5808       OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
5809       OS.PadToColumn(40 + 3 * Bias);
5810       OS << printEnum(Sym.getType(), makeArrayRef(ElfSymbolTypes));
5811       OS.PadToColumn(48 + 3 * Bias);
5812       OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
5813                                 ShndxTable);
5814       OS.PadToColumn(52 + 3 * Bias);
5815       OS << SymName << "\n";
5816     }
5817   }
5818 
5819   if (!Parser.getOtherEntries().empty())
5820     OS << "\n Number of TLS and multi-GOT entries "
5821        << Parser.getOtherEntries().size() << "\n";
5822 }
5823 
5824 template <class ELFT>
5825 void GNUELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
5826   size_t Bias = ELFT::Is64Bits ? 8 : 0;
5827   auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
5828     OS.PadToColumn(2);
5829     OS << format_hex_no_prefix(Parser.getPltAddress(E), 8 + Bias);
5830     OS.PadToColumn(11 + Bias);
5831     OS << format_hex_no_prefix(*E, 8 + Bias);
5832     OS.PadToColumn(20 + 2 * Bias);
5833     OS << Purpose << "\n";
5834   };
5835 
5836   OS << "PLT GOT:\n\n";
5837 
5838   OS << " Reserved entries:\n";
5839   OS << "   Address  Initial Purpose\n";
5840   PrintEntry(Parser.getPltLazyResolver(), "PLT lazy resolver");
5841   if (Parser.getPltModulePointer())
5842     PrintEntry(Parser.getPltModulePointer(), "Module pointer");
5843 
5844   if (!Parser.getPltEntries().empty()) {
5845     OS << "\n";
5846     OS << " Entries:\n";
5847     OS << "   Address  Initial Sym.Val. Type    Ndx Name\n";
5848     DataRegion<Elf_Word> ShndxTable(
5849         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
5850     for (auto &E : Parser.getPltEntries()) {
5851       const Elf_Sym &Sym = *Parser.getPltSym(&E);
5852       const Elf_Sym &FirstSym = *cantFail(
5853           this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
5854       std::string SymName = this->getFullSymbolName(
5855           Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
5856 
5857       OS.PadToColumn(2);
5858       OS << to_string(format_hex_no_prefix(Parser.getPltAddress(&E), 8 + Bias));
5859       OS.PadToColumn(11 + Bias);
5860       OS << to_string(format_hex_no_prefix(E, 8 + Bias));
5861       OS.PadToColumn(20 + 2 * Bias);
5862       OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
5863       OS.PadToColumn(29 + 3 * Bias);
5864       OS << printEnum(Sym.getType(), makeArrayRef(ElfSymbolTypes));
5865       OS.PadToColumn(37 + 3 * Bias);
5866       OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
5867                                 ShndxTable);
5868       OS.PadToColumn(41 + 3 * Bias);
5869       OS << SymName << "\n";
5870     }
5871   }
5872 }
5873 
5874 template <class ELFT>
5875 Expected<const Elf_Mips_ABIFlags<ELFT> *>
5876 getMipsAbiFlagsSection(const ELFDumper<ELFT> &Dumper) {
5877   const typename ELFT::Shdr *Sec = Dumper.findSectionByName(".MIPS.abiflags");
5878   if (Sec == nullptr)
5879     return nullptr;
5880 
5881   constexpr StringRef ErrPrefix = "unable to read the .MIPS.abiflags section: ";
5882   Expected<ArrayRef<uint8_t>> DataOrErr =
5883       Dumper.getElfObject().getELFFile().getSectionContents(*Sec);
5884   if (!DataOrErr)
5885     return createError(ErrPrefix + toString(DataOrErr.takeError()));
5886 
5887   if (DataOrErr->size() != sizeof(Elf_Mips_ABIFlags<ELFT>))
5888     return createError(ErrPrefix + "it has a wrong size (" +
5889         Twine(DataOrErr->size()) + ")");
5890   return reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(DataOrErr->data());
5891 }
5892 
5893 template <class ELFT> void GNUELFDumper<ELFT>::printMipsABIFlags() {
5894   const Elf_Mips_ABIFlags<ELFT> *Flags = nullptr;
5895   if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
5896           getMipsAbiFlagsSection(*this))
5897     Flags = *SecOrErr;
5898   else
5899     this->reportUniqueWarning(SecOrErr.takeError());
5900   if (!Flags)
5901     return;
5902 
5903   OS << "MIPS ABI Flags Version: " << Flags->version << "\n\n";
5904   OS << "ISA: MIPS" << int(Flags->isa_level);
5905   if (Flags->isa_rev > 1)
5906     OS << "r" << int(Flags->isa_rev);
5907   OS << "\n";
5908   OS << "GPR size: " << getMipsRegisterSize(Flags->gpr_size) << "\n";
5909   OS << "CPR1 size: " << getMipsRegisterSize(Flags->cpr1_size) << "\n";
5910   OS << "CPR2 size: " << getMipsRegisterSize(Flags->cpr2_size) << "\n";
5911   OS << "FP ABI: " << printEnum(Flags->fp_abi, makeArrayRef(ElfMipsFpABIType))
5912      << "\n";
5913   OS << "ISA Extension: "
5914      << printEnum(Flags->isa_ext, makeArrayRef(ElfMipsISAExtType)) << "\n";
5915   if (Flags->ases == 0)
5916     OS << "ASEs: None\n";
5917   else
5918     // FIXME: Print each flag on a separate line.
5919     OS << "ASEs: " << printFlags(Flags->ases, makeArrayRef(ElfMipsASEFlags))
5920        << "\n";
5921   OS << "FLAGS 1: " << format_hex_no_prefix(Flags->flags1, 8, false) << "\n";
5922   OS << "FLAGS 2: " << format_hex_no_prefix(Flags->flags2, 8, false) << "\n";
5923   OS << "\n";
5924 }
5925 
5926 template <class ELFT> void LLVMELFDumper<ELFT>::printFileHeaders() {
5927   const Elf_Ehdr &E = this->Obj.getHeader();
5928   {
5929     DictScope D(W, "ElfHeader");
5930     {
5931       DictScope D(W, "Ident");
5932       W.printBinary("Magic", makeArrayRef(E.e_ident).slice(ELF::EI_MAG0, 4));
5933       W.printEnum("Class", E.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass));
5934       W.printEnum("DataEncoding", E.e_ident[ELF::EI_DATA],
5935                   makeArrayRef(ElfDataEncoding));
5936       W.printNumber("FileVersion", E.e_ident[ELF::EI_VERSION]);
5937 
5938       auto OSABI = makeArrayRef(ElfOSABI);
5939       if (E.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH &&
5940           E.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) {
5941         switch (E.e_machine) {
5942         case ELF::EM_AMDGPU:
5943           OSABI = makeArrayRef(AMDGPUElfOSABI);
5944           break;
5945         case ELF::EM_ARM:
5946           OSABI = makeArrayRef(ARMElfOSABI);
5947           break;
5948         case ELF::EM_TI_C6000:
5949           OSABI = makeArrayRef(C6000ElfOSABI);
5950           break;
5951         }
5952       }
5953       W.printEnum("OS/ABI", E.e_ident[ELF::EI_OSABI], OSABI);
5954       W.printNumber("ABIVersion", E.e_ident[ELF::EI_ABIVERSION]);
5955       W.printBinary("Unused", makeArrayRef(E.e_ident).slice(ELF::EI_PAD));
5956     }
5957 
5958     std::string TypeStr;
5959     if (const EnumEntry<unsigned> *Ent = getObjectFileEnumEntry(E.e_type)) {
5960       TypeStr = Ent->Name.str();
5961     } else {
5962       if (E.e_type >= ET_LOPROC)
5963         TypeStr = "Processor Specific";
5964       else if (E.e_type >= ET_LOOS)
5965         TypeStr = "OS Specific";
5966       else
5967         TypeStr = "Unknown";
5968     }
5969     W.printString("Type", TypeStr + " (0x" + to_hexString(E.e_type) + ")");
5970 
5971     W.printEnum("Machine", E.e_machine, makeArrayRef(ElfMachineType));
5972     W.printNumber("Version", E.e_version);
5973     W.printHex("Entry", E.e_entry);
5974     W.printHex("ProgramHeaderOffset", E.e_phoff);
5975     W.printHex("SectionHeaderOffset", E.e_shoff);
5976     if (E.e_machine == EM_MIPS)
5977       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderMipsFlags),
5978                    unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
5979                    unsigned(ELF::EF_MIPS_MACH));
5980     else if (E.e_machine == EM_AMDGPU)
5981       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderAMDGPUFlags),
5982                    unsigned(ELF::EF_AMDGPU_MACH));
5983     else if (E.e_machine == EM_RISCV)
5984       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderRISCVFlags));
5985     else
5986       W.printFlags("Flags", E.e_flags);
5987     W.printNumber("HeaderSize", E.e_ehsize);
5988     W.printNumber("ProgramHeaderEntrySize", E.e_phentsize);
5989     W.printNumber("ProgramHeaderCount", E.e_phnum);
5990     W.printNumber("SectionHeaderEntrySize", E.e_shentsize);
5991     W.printString("SectionHeaderCount",
5992                   getSectionHeadersNumString(this->Obj, this->FileName));
5993     W.printString("StringTableSectionIndex",
5994                   getSectionHeaderTableIndexString(this->Obj, this->FileName));
5995   }
5996 }
5997 
5998 template <class ELFT> void LLVMELFDumper<ELFT>::printGroupSections() {
5999   DictScope Lists(W, "Groups");
6000   std::vector<GroupSection> V = this->getGroups();
6001   DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
6002   for (const GroupSection &G : V) {
6003     DictScope D(W, "Group");
6004     W.printNumber("Name", G.Name, G.ShName);
6005     W.printNumber("Index", G.Index);
6006     W.printNumber("Link", G.Link);
6007     W.printNumber("Info", G.Info);
6008     W.printHex("Type", getGroupType(G.Type), G.Type);
6009     W.startLine() << "Signature: " << G.Signature << "\n";
6010 
6011     ListScope L(W, "Section(s) in group");
6012     for (const GroupMember &GM : G.Members) {
6013       const GroupSection *MainGroup = Map[GM.Index];
6014       if (MainGroup != &G)
6015         this->reportUniqueWarning(
6016             "section with index " + Twine(GM.Index) +
6017             ", included in the group section with index " +
6018             Twine(MainGroup->Index) +
6019             ", was also found in the group section with index " +
6020             Twine(G.Index));
6021       W.startLine() << GM.Name << " (" << GM.Index << ")\n";
6022     }
6023   }
6024 
6025   if (V.empty())
6026     W.startLine() << "There are no group sections in the file.\n";
6027 }
6028 
6029 template <class ELFT> void LLVMELFDumper<ELFT>::printRelocations() {
6030   ListScope D(W, "Relocations");
6031 
6032   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6033     if (!isRelocationSec<ELFT>(Sec))
6034       continue;
6035 
6036     StringRef Name = this->getPrintableSectionName(Sec);
6037     unsigned SecNdx = &Sec - &cantFail(this->Obj.sections()).front();
6038     W.startLine() << "Section (" << SecNdx << ") " << Name << " {\n";
6039     W.indent();
6040     this->printRelocationsHelper(Sec);
6041     W.unindent();
6042     W.startLine() << "}\n";
6043   }
6044 }
6045 
6046 template <class ELFT>
6047 void LLVMELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
6048   W.startLine() << W.hex(R) << "\n";
6049 }
6050 
6051 template <class ELFT>
6052 void LLVMELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
6053                                             const RelSymbol<ELFT> &RelSym) {
6054   StringRef SymbolName = RelSym.Name;
6055   SmallString<32> RelocName;
6056   this->Obj.getRelocationTypeName(R.Type, RelocName);
6057 
6058   if (opts::ExpandRelocs) {
6059     DictScope Group(W, "Relocation");
6060     W.printHex("Offset", R.Offset);
6061     W.printNumber("Type", RelocName, R.Type);
6062     W.printNumber("Symbol", !SymbolName.empty() ? SymbolName : "-", R.Symbol);
6063     if (R.Addend)
6064       W.printHex("Addend", (uintX_t)*R.Addend);
6065   } else {
6066     raw_ostream &OS = W.startLine();
6067     OS << W.hex(R.Offset) << " " << RelocName << " "
6068        << (!SymbolName.empty() ? SymbolName : "-");
6069     if (R.Addend)
6070       OS << " " << W.hex((uintX_t)*R.Addend);
6071     OS << "\n";
6072   }
6073 }
6074 
6075 template <class ELFT> void LLVMELFDumper<ELFT>::printSectionHeaders() {
6076   ListScope SectionsD(W, "Sections");
6077 
6078   int SectionIndex = -1;
6079   std::vector<EnumEntry<unsigned>> FlagsList =
6080       getSectionFlagsForTarget(this->Obj.getHeader().e_machine);
6081   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6082     DictScope SectionD(W, "Section");
6083     W.printNumber("Index", ++SectionIndex);
6084     W.printNumber("Name", this->getPrintableSectionName(Sec), Sec.sh_name);
6085     W.printHex("Type",
6086                object::getELFSectionTypeName(this->Obj.getHeader().e_machine,
6087                                              Sec.sh_type),
6088                Sec.sh_type);
6089     W.printFlags("Flags", Sec.sh_flags, makeArrayRef(FlagsList));
6090     W.printHex("Address", Sec.sh_addr);
6091     W.printHex("Offset", Sec.sh_offset);
6092     W.printNumber("Size", Sec.sh_size);
6093     W.printNumber("Link", Sec.sh_link);
6094     W.printNumber("Info", Sec.sh_info);
6095     W.printNumber("AddressAlignment", Sec.sh_addralign);
6096     W.printNumber("EntrySize", Sec.sh_entsize);
6097 
6098     if (opts::SectionRelocations) {
6099       ListScope D(W, "Relocations");
6100       this->printRelocationsHelper(Sec);
6101     }
6102 
6103     if (opts::SectionSymbols) {
6104       ListScope D(W, "Symbols");
6105       if (this->DotSymtabSec) {
6106         StringRef StrTable = unwrapOrError(
6107             this->FileName,
6108             this->Obj.getStringTableForSymtab(*this->DotSymtabSec));
6109         ArrayRef<Elf_Word> ShndxTable = this->getShndxTable(this->DotSymtabSec);
6110 
6111         typename ELFT::SymRange Symbols = unwrapOrError(
6112             this->FileName, this->Obj.symbols(this->DotSymtabSec));
6113         for (const Elf_Sym &Sym : Symbols) {
6114           const Elf_Shdr *SymSec = unwrapOrError(
6115               this->FileName,
6116               this->Obj.getSection(Sym, this->DotSymtabSec, ShndxTable));
6117           if (SymSec == &Sec)
6118             printSymbol(Sym, &Sym - &Symbols[0], ShndxTable, StrTable, false,
6119                         false);
6120         }
6121       }
6122     }
6123 
6124     if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) {
6125       ArrayRef<uint8_t> Data =
6126           unwrapOrError(this->FileName, this->Obj.getSectionContents(Sec));
6127       W.printBinaryBlock(
6128           "SectionData",
6129           StringRef(reinterpret_cast<const char *>(Data.data()), Data.size()));
6130     }
6131   }
6132 }
6133 
6134 template <class ELFT>
6135 void LLVMELFDumper<ELFT>::printSymbolSection(
6136     const Elf_Sym &Symbol, unsigned SymIndex,
6137     DataRegion<Elf_Word> ShndxTable) const {
6138   auto GetSectionSpecialType = [&]() -> Optional<StringRef> {
6139     if (Symbol.isUndefined())
6140       return StringRef("Undefined");
6141     if (Symbol.isProcessorSpecific())
6142       return StringRef("Processor Specific");
6143     if (Symbol.isOSSpecific())
6144       return StringRef("Operating System Specific");
6145     if (Symbol.isAbsolute())
6146       return StringRef("Absolute");
6147     if (Symbol.isCommon())
6148       return StringRef("Common");
6149     if (Symbol.isReserved() && Symbol.st_shndx != SHN_XINDEX)
6150       return StringRef("Reserved");
6151     return None;
6152   };
6153 
6154   if (Optional<StringRef> Type = GetSectionSpecialType()) {
6155     W.printHex("Section", *Type, Symbol.st_shndx);
6156     return;
6157   }
6158 
6159   Expected<unsigned> SectionIndex =
6160       this->getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
6161   if (!SectionIndex) {
6162     assert(Symbol.st_shndx == SHN_XINDEX &&
6163            "getSymbolSectionIndex should only fail due to an invalid "
6164            "SHT_SYMTAB_SHNDX table/reference");
6165     this->reportUniqueWarning(SectionIndex.takeError());
6166     W.printHex("Section", "Reserved", SHN_XINDEX);
6167     return;
6168   }
6169 
6170   Expected<StringRef> SectionName =
6171       this->getSymbolSectionName(Symbol, *SectionIndex);
6172   if (!SectionName) {
6173     // Don't report an invalid section name if the section headers are missing.
6174     // In such situations, all sections will be "invalid".
6175     if (!this->ObjF.sections().empty())
6176       this->reportUniqueWarning(SectionName.takeError());
6177     else
6178       consumeError(SectionName.takeError());
6179     W.printHex("Section", "<?>", *SectionIndex);
6180   } else {
6181     W.printHex("Section", *SectionName, *SectionIndex);
6182   }
6183 }
6184 
6185 template <class ELFT>
6186 void LLVMELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
6187                                       DataRegion<Elf_Word> ShndxTable,
6188                                       Optional<StringRef> StrTable,
6189                                       bool IsDynamic,
6190                                       bool /*NonVisibilityBitsUsed*/) const {
6191   std::string FullSymbolName = this->getFullSymbolName(
6192       Symbol, SymIndex, ShndxTable, StrTable, IsDynamic);
6193   unsigned char SymbolType = Symbol.getType();
6194 
6195   DictScope D(W, "Symbol");
6196   W.printNumber("Name", FullSymbolName, Symbol.st_name);
6197   W.printHex("Value", Symbol.st_value);
6198   W.printNumber("Size", Symbol.st_size);
6199   W.printEnum("Binding", Symbol.getBinding(), makeArrayRef(ElfSymbolBindings));
6200   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
6201       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
6202     W.printEnum("Type", SymbolType, makeArrayRef(AMDGPUSymbolTypes));
6203   else
6204     W.printEnum("Type", SymbolType, makeArrayRef(ElfSymbolTypes));
6205   if (Symbol.st_other == 0)
6206     // Usually st_other flag is zero. Do not pollute the output
6207     // by flags enumeration in that case.
6208     W.printNumber("Other", 0);
6209   else {
6210     std::vector<EnumEntry<unsigned>> SymOtherFlags(std::begin(ElfSymOtherFlags),
6211                                                    std::end(ElfSymOtherFlags));
6212     if (this->Obj.getHeader().e_machine == EM_MIPS) {
6213       // Someones in their infinite wisdom decided to make STO_MIPS_MIPS16
6214       // flag overlapped with other ST_MIPS_xxx flags. So consider both
6215       // cases separately.
6216       if ((Symbol.st_other & STO_MIPS_MIPS16) == STO_MIPS_MIPS16)
6217         SymOtherFlags.insert(SymOtherFlags.end(),
6218                              std::begin(ElfMips16SymOtherFlags),
6219                              std::end(ElfMips16SymOtherFlags));
6220       else
6221         SymOtherFlags.insert(SymOtherFlags.end(),
6222                              std::begin(ElfMipsSymOtherFlags),
6223                              std::end(ElfMipsSymOtherFlags));
6224     } else if (this->Obj.getHeader().e_machine == EM_AARCH64) {
6225       SymOtherFlags.insert(SymOtherFlags.end(),
6226                            std::begin(ElfAArch64SymOtherFlags),
6227                            std::end(ElfAArch64SymOtherFlags));
6228     }
6229     W.printFlags("Other", Symbol.st_other, makeArrayRef(SymOtherFlags), 0x3u);
6230   }
6231   printSymbolSection(Symbol, SymIndex, ShndxTable);
6232 }
6233 
6234 template <class ELFT>
6235 void LLVMELFDumper<ELFT>::printSymbols(bool PrintSymbols,
6236                                        bool PrintDynamicSymbols) {
6237   if (PrintSymbols) {
6238     ListScope Group(W, "Symbols");
6239     this->printSymbolsHelper(false);
6240   }
6241   if (PrintDynamicSymbols) {
6242     ListScope Group(W, "DynamicSymbols");
6243     this->printSymbolsHelper(true);
6244   }
6245 }
6246 
6247 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicTable() {
6248   Elf_Dyn_Range Table = this->dynamic_table();
6249   if (Table.empty())
6250     return;
6251 
6252   W.startLine() << "DynamicSection [ (" << Table.size() << " entries)\n";
6253 
6254   size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table);
6255   // The "Name/Value" column should be indented from the "Type" column by N
6256   // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
6257   // space (1) = -3.
6258   W.startLine() << "  Tag" << std::string(ELFT::Is64Bits ? 16 : 8, ' ')
6259                 << "Type" << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
6260 
6261   std::string ValueFmt = "%-" + std::to_string(MaxTagSize) + "s ";
6262   for (auto Entry : Table) {
6263     uintX_t Tag = Entry.getTag();
6264     std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
6265     W.startLine() << "  " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10, true)
6266                   << " "
6267                   << format(ValueFmt.c_str(),
6268                             this->Obj.getDynamicTagAsString(Tag).c_str())
6269                   << Value << "\n";
6270   }
6271   W.startLine() << "]\n";
6272 }
6273 
6274 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicRelocations() {
6275   W.startLine() << "Dynamic Relocations {\n";
6276   W.indent();
6277   this->printDynamicRelocationsHelper();
6278   W.unindent();
6279   W.startLine() << "}\n";
6280 }
6281 
6282 template <class ELFT>
6283 void LLVMELFDumper<ELFT>::printProgramHeaders(
6284     bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
6285   if (PrintProgramHeaders)
6286     printProgramHeaders();
6287   if (PrintSectionMapping == cl::BOU_TRUE)
6288     printSectionMapping();
6289 }
6290 
6291 template <class ELFT> void LLVMELFDumper<ELFT>::printProgramHeaders() {
6292   ListScope L(W, "ProgramHeaders");
6293 
6294   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
6295   if (!PhdrsOrErr) {
6296     this->reportUniqueWarning("unable to dump program headers: " +
6297                               toString(PhdrsOrErr.takeError()));
6298     return;
6299   }
6300 
6301   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
6302     DictScope P(W, "ProgramHeader");
6303     StringRef Type =
6304         segmentTypeToString(this->Obj.getHeader().e_machine, Phdr.p_type);
6305 
6306     W.printHex("Type", Type.empty() ? "Unknown" : Type, Phdr.p_type);
6307     W.printHex("Offset", Phdr.p_offset);
6308     W.printHex("VirtualAddress", Phdr.p_vaddr);
6309     W.printHex("PhysicalAddress", Phdr.p_paddr);
6310     W.printNumber("FileSize", Phdr.p_filesz);
6311     W.printNumber("MemSize", Phdr.p_memsz);
6312     W.printFlags("Flags", Phdr.p_flags, makeArrayRef(ElfSegmentFlags));
6313     W.printNumber("Alignment", Phdr.p_align);
6314   }
6315 }
6316 
6317 template <class ELFT>
6318 void LLVMELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
6319   ListScope SS(W, "VersionSymbols");
6320   if (!Sec)
6321     return;
6322 
6323   StringRef StrTable;
6324   ArrayRef<Elf_Sym> Syms;
6325   const Elf_Shdr *SymTabSec;
6326   Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
6327       this->getVersionTable(*Sec, &Syms, &StrTable, &SymTabSec);
6328   if (!VerTableOrErr) {
6329     this->reportUniqueWarning(VerTableOrErr.takeError());
6330     return;
6331   }
6332 
6333   if (StrTable.empty() || Syms.empty() || Syms.size() != VerTableOrErr->size())
6334     return;
6335 
6336   ArrayRef<Elf_Word> ShNdxTable = this->getShndxTable(SymTabSec);
6337   for (size_t I = 0, E = Syms.size(); I < E; ++I) {
6338     DictScope S(W, "Symbol");
6339     W.printNumber("Version", (*VerTableOrErr)[I].vs_index & VERSYM_VERSION);
6340     W.printString("Name",
6341                   this->getFullSymbolName(Syms[I], I, ShNdxTable, StrTable,
6342                                           /*IsDynamic=*/true));
6343   }
6344 }
6345 
6346 static const EnumEntry<unsigned> SymVersionFlags[] = {
6347     {"Base", "BASE", VER_FLG_BASE},
6348     {"Weak", "WEAK", VER_FLG_WEAK},
6349     {"Info", "INFO", VER_FLG_INFO}};
6350 
6351 template <class ELFT>
6352 void LLVMELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
6353   ListScope SD(W, "VersionDefinitions");
6354   if (!Sec)
6355     return;
6356 
6357   Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
6358   if (!V) {
6359     this->reportUniqueWarning(V.takeError());
6360     return;
6361   }
6362 
6363   for (const VerDef &D : *V) {
6364     DictScope Def(W, "Definition");
6365     W.printNumber("Version", D.Version);
6366     W.printFlags("Flags", D.Flags, makeArrayRef(SymVersionFlags));
6367     W.printNumber("Index", D.Ndx);
6368     W.printNumber("Hash", D.Hash);
6369     W.printString("Name", D.Name.c_str());
6370     W.printList(
6371         "Predecessors", D.AuxV,
6372         [](raw_ostream &OS, const VerdAux &Aux) { OS << Aux.Name.c_str(); });
6373   }
6374 }
6375 
6376 template <class ELFT>
6377 void LLVMELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
6378   ListScope SD(W, "VersionRequirements");
6379   if (!Sec)
6380     return;
6381 
6382   Expected<std::vector<VerNeed>> V =
6383       this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
6384   if (!V) {
6385     this->reportUniqueWarning(V.takeError());
6386     return;
6387   }
6388 
6389   for (const VerNeed &VN : *V) {
6390     DictScope Entry(W, "Dependency");
6391     W.printNumber("Version", VN.Version);
6392     W.printNumber("Count", VN.Cnt);
6393     W.printString("FileName", VN.File.c_str());
6394 
6395     ListScope L(W, "Entries");
6396     for (const VernAux &Aux : VN.AuxV) {
6397       DictScope Entry(W, "Entry");
6398       W.printNumber("Hash", Aux.Hash);
6399       W.printFlags("Flags", Aux.Flags, makeArrayRef(SymVersionFlags));
6400       W.printNumber("Index", Aux.Other);
6401       W.printString("Name", Aux.Name.c_str());
6402     }
6403   }
6404 }
6405 
6406 template <class ELFT> void LLVMELFDumper<ELFT>::printHashHistograms() {
6407   W.startLine() << "Hash Histogram not implemented!\n";
6408 }
6409 
6410 template <class ELFT> void LLVMELFDumper<ELFT>::printCGProfile() {
6411   ListScope L(W, "CGProfile");
6412   if (!this->DotCGProfileSec)
6413     return;
6414 
6415   Expected<ArrayRef<Elf_CGProfile>> CGProfileOrErr =
6416       this->Obj.template getSectionContentsAsArray<Elf_CGProfile>(
6417           *this->DotCGProfileSec);
6418   if (!CGProfileOrErr) {
6419     this->reportUniqueWarning(
6420         "unable to dump the SHT_LLVM_CALL_GRAPH_PROFILE section: " +
6421         toString(CGProfileOrErr.takeError()));
6422     return;
6423   }
6424 
6425   for (const Elf_CGProfile &CGPE : *CGProfileOrErr) {
6426     DictScope D(W, "CGProfileEntry");
6427     W.printNumber("From", this->getStaticSymbolName(CGPE.cgp_from),
6428                   CGPE.cgp_from);
6429     W.printNumber("To", this->getStaticSymbolName(CGPE.cgp_to),
6430                   CGPE.cgp_to);
6431     W.printNumber("Weight", CGPE.cgp_weight);
6432   }
6433 }
6434 
6435 template <class ELFT> void LLVMELFDumper<ELFT>::printAddrsig() {
6436   ListScope L(W, "Addrsig");
6437   if (!this->DotAddrsigSec)
6438     return;
6439 
6440   Expected<std::vector<uint64_t>> SymsOrErr =
6441       decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
6442   if (!SymsOrErr) {
6443     this->reportUniqueWarning(SymsOrErr.takeError());
6444     return;
6445   }
6446 
6447   for (uint64_t Sym : *SymsOrErr)
6448     W.printNumber("Sym", this->getStaticSymbolName(Sym), Sym);
6449 }
6450 
6451 template <typename ELFT>
6452 static void printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
6453                                   ScopedPrinter &W) {
6454   switch (NoteType) {
6455   default:
6456     return;
6457   case ELF::NT_GNU_ABI_TAG: {
6458     const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
6459     if (!AbiTag.IsValid) {
6460       W.printString("ABI", "<corrupt GNU_ABI_TAG>");
6461     } else {
6462       W.printString("OS", AbiTag.OSName);
6463       W.printString("ABI", AbiTag.ABI);
6464     }
6465     break;
6466   }
6467   case ELF::NT_GNU_BUILD_ID: {
6468     W.printString("Build ID", getGNUBuildId(Desc));
6469     break;
6470   }
6471   case ELF::NT_GNU_GOLD_VERSION:
6472     W.printString("Version", getGNUGoldVersion(Desc));
6473     break;
6474   case ELF::NT_GNU_PROPERTY_TYPE_0:
6475     ListScope D(W, "Property");
6476     for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
6477       W.printString(Property);
6478     break;
6479   }
6480 }
6481 
6482 static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) {
6483   W.printNumber("Page Size", Note.PageSize);
6484   for (const CoreFileMapping &Mapping : Note.Mappings) {
6485     ListScope D(W, "Mapping");
6486     W.printHex("Start", Mapping.Start);
6487     W.printHex("End", Mapping.End);
6488     W.printHex("Offset", Mapping.Offset);
6489     W.printString("Filename", Mapping.Filename);
6490   }
6491 }
6492 
6493 template <class ELFT> void LLVMELFDumper<ELFT>::printNotes() {
6494   ListScope L(W, "Notes");
6495 
6496   std::unique_ptr<DictScope> NoteScope;
6497   auto StartNotes = [&](Optional<StringRef> SecName,
6498                         const typename ELFT::Off Offset,
6499                         const typename ELFT::Addr Size) {
6500     NoteScope = std::make_unique<DictScope>(W, "NoteSection");
6501     W.printString("Name", SecName ? *SecName : "<?>");
6502     W.printHex("Offset", Offset);
6503     W.printHex("Size", Size);
6504   };
6505 
6506   auto EndNotes = [&] { NoteScope.reset(); };
6507 
6508   auto ProcessNote = [&](const Elf_Note &Note) -> Error {
6509     DictScope D2(W, "Note");
6510     StringRef Name = Note.getName();
6511     ArrayRef<uint8_t> Descriptor = Note.getDesc();
6512     Elf_Word Type = Note.getType();
6513 
6514     // Print the note owner/type.
6515     W.printString("Owner", Name);
6516     W.printHex("Data size", Descriptor.size());
6517 
6518     StringRef NoteType =
6519         getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
6520     if (!NoteType.empty())
6521       W.printString("Type", NoteType);
6522     else
6523       W.printString("Type",
6524                     "Unknown (" + to_string(format_hex(Type, 10)) + ")");
6525 
6526     // Print the description, or fallback to printing raw bytes for unknown
6527     // owners.
6528     if (Name == "GNU") {
6529       printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W);
6530     } else if (Name == "AMD") {
6531       const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
6532       if (!N.Type.empty())
6533         W.printString(N.Type, N.Value);
6534     } else if (Name == "AMDGPU") {
6535       const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
6536       if (!N.Type.empty())
6537         W.printString(N.Type, N.Value);
6538     } else if (Name == "CORE") {
6539       if (Type == ELF::NT_FILE) {
6540         DataExtractor DescExtractor(Descriptor,
6541                                     ELFT::TargetEndianness == support::little,
6542                                     sizeof(Elf_Addr));
6543         if (Expected<CoreNote> Note = readCoreNote(DescExtractor))
6544           printCoreNoteLLVMStyle(*Note, W);
6545         else
6546           return Note.takeError();
6547       }
6548     } else if (!Descriptor.empty()) {
6549       W.printBinaryBlock("Description data", Descriptor);
6550     }
6551     return Error::success();
6552   };
6553 
6554   printNotesHelper(*this, StartNotes, ProcessNote, EndNotes);
6555 }
6556 
6557 template <class ELFT> void LLVMELFDumper<ELFT>::printELFLinkerOptions() {
6558   ListScope L(W, "LinkerOptions");
6559 
6560   unsigned I = -1;
6561   for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) {
6562     ++I;
6563     if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS)
6564       continue;
6565 
6566     Expected<ArrayRef<uint8_t>> ContentsOrErr =
6567         this->Obj.getSectionContents(Shdr);
6568     if (!ContentsOrErr) {
6569       this->reportUniqueWarning("unable to read the content of the "
6570                                 "SHT_LLVM_LINKER_OPTIONS section: " +
6571                                 toString(ContentsOrErr.takeError()));
6572       continue;
6573     }
6574     if (ContentsOrErr->empty())
6575       continue;
6576 
6577     if (ContentsOrErr->back() != 0) {
6578       this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " +
6579                                 Twine(I) +
6580                                 " is broken: the "
6581                                 "content is not null-terminated");
6582       continue;
6583     }
6584 
6585     SmallVector<StringRef, 16> Strings;
6586     toStringRef(ContentsOrErr->drop_back()).split(Strings, '\0');
6587     if (Strings.size() % 2 != 0) {
6588       this->reportUniqueWarning(
6589           "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) +
6590           " is broken: an incomplete "
6591           "key-value pair was found. The last possible key was: \"" +
6592           Strings.back() + "\"");
6593       continue;
6594     }
6595 
6596     for (size_t I = 0; I < Strings.size(); I += 2)
6597       W.printString(Strings[I], Strings[I + 1]);
6598   }
6599 }
6600 
6601 template <class ELFT> void LLVMELFDumper<ELFT>::printDependentLibs() {
6602   ListScope L(W, "DependentLibs");
6603   this->printDependentLibsHelper(
6604       [](const Elf_Shdr &) {},
6605       [this](StringRef Lib, uint64_t) { W.printString(Lib); });
6606 }
6607 
6608 template <class ELFT> void LLVMELFDumper<ELFT>::printStackSizes() {
6609   ListScope L(W, "StackSizes");
6610   if (this->Obj.getHeader().e_type == ELF::ET_REL)
6611     this->printRelocatableStackSizes([]() {});
6612   else
6613     this->printNonRelocatableStackSizes([]() {});
6614 }
6615 
6616 template <class ELFT>
6617 void LLVMELFDumper<ELFT>::printStackSizeEntry(uint64_t Size, StringRef FuncName) {
6618   DictScope D(W, "Entry");
6619   W.printString("Function", FuncName);
6620   W.printHex("Size", Size);
6621 }
6622 
6623 template <class ELFT>
6624 void LLVMELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
6625   auto PrintEntry = [&](const Elf_Addr *E) {
6626     W.printHex("Address", Parser.getGotAddress(E));
6627     W.printNumber("Access", Parser.getGotOffset(E));
6628     W.printHex("Initial", *E);
6629   };
6630 
6631   DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT");
6632 
6633   W.printHex("Canonical gp value", Parser.getGp());
6634   {
6635     ListScope RS(W, "Reserved entries");
6636     {
6637       DictScope D(W, "Entry");
6638       PrintEntry(Parser.getGotLazyResolver());
6639       W.printString("Purpose", StringRef("Lazy resolver"));
6640     }
6641 
6642     if (Parser.getGotModulePointer()) {
6643       DictScope D(W, "Entry");
6644       PrintEntry(Parser.getGotModulePointer());
6645       W.printString("Purpose", StringRef("Module pointer (GNU extension)"));
6646     }
6647   }
6648   {
6649     ListScope LS(W, "Local entries");
6650     for (auto &E : Parser.getLocalEntries()) {
6651       DictScope D(W, "Entry");
6652       PrintEntry(&E);
6653     }
6654   }
6655 
6656   if (Parser.IsStatic)
6657     return;
6658 
6659   {
6660     ListScope GS(W, "Global entries");
6661     for (auto &E : Parser.getGlobalEntries()) {
6662       DictScope D(W, "Entry");
6663 
6664       PrintEntry(&E);
6665 
6666       const Elf_Sym &Sym = *Parser.getGotSym(&E);
6667       W.printHex("Value", Sym.st_value);
6668       W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes));
6669 
6670       const unsigned SymIndex = &Sym - this->dynamic_symbols().begin();
6671       DataRegion<Elf_Word> ShndxTable(
6672           (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6673       printSymbolSection(Sym, SymIndex, ShndxTable);
6674 
6675       std::string SymName = this->getFullSymbolName(
6676           Sym, SymIndex, ShndxTable, this->DynamicStringTable, true);
6677       W.printNumber("Name", SymName, Sym.st_name);
6678     }
6679   }
6680 
6681   W.printNumber("Number of TLS and multi-GOT entries",
6682                 uint64_t(Parser.getOtherEntries().size()));
6683 }
6684 
6685 template <class ELFT>
6686 void LLVMELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
6687   auto PrintEntry = [&](const Elf_Addr *E) {
6688     W.printHex("Address", Parser.getPltAddress(E));
6689     W.printHex("Initial", *E);
6690   };
6691 
6692   DictScope GS(W, "PLT GOT");
6693 
6694   {
6695     ListScope RS(W, "Reserved entries");
6696     {
6697       DictScope D(W, "Entry");
6698       PrintEntry(Parser.getPltLazyResolver());
6699       W.printString("Purpose", StringRef("PLT lazy resolver"));
6700     }
6701 
6702     if (auto E = Parser.getPltModulePointer()) {
6703       DictScope D(W, "Entry");
6704       PrintEntry(E);
6705       W.printString("Purpose", StringRef("Module pointer"));
6706     }
6707   }
6708   {
6709     ListScope LS(W, "Entries");
6710     DataRegion<Elf_Word> ShndxTable(
6711         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6712     for (auto &E : Parser.getPltEntries()) {
6713       DictScope D(W, "Entry");
6714       PrintEntry(&E);
6715 
6716       const Elf_Sym &Sym = *Parser.getPltSym(&E);
6717       W.printHex("Value", Sym.st_value);
6718       W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes));
6719       printSymbolSection(Sym, &Sym - this->dynamic_symbols().begin(),
6720                          ShndxTable);
6721 
6722       const Elf_Sym *FirstSym = cantFail(
6723           this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
6724       std::string SymName = this->getFullSymbolName(
6725           Sym, &Sym - FirstSym, ShndxTable, Parser.getPltStrTable(), true);
6726       W.printNumber("Name", SymName, Sym.st_name);
6727     }
6728   }
6729 }
6730 
6731 template <class ELFT> void LLVMELFDumper<ELFT>::printMipsABIFlags() {
6732   const Elf_Mips_ABIFlags<ELFT> *Flags;
6733   if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
6734           getMipsAbiFlagsSection(*this)) {
6735     Flags = *SecOrErr;
6736     if (!Flags) {
6737       W.startLine() << "There is no .MIPS.abiflags section in the file.\n";
6738       return;
6739     }
6740   } else {
6741     this->reportUniqueWarning(SecOrErr.takeError());
6742     return;
6743   }
6744 
6745   raw_ostream &OS = W.getOStream();
6746   DictScope GS(W, "MIPS ABI Flags");
6747 
6748   W.printNumber("Version", Flags->version);
6749   W.startLine() << "ISA: ";
6750   if (Flags->isa_rev <= 1)
6751     OS << format("MIPS%u", Flags->isa_level);
6752   else
6753     OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev);
6754   OS << "\n";
6755   W.printEnum("ISA Extension", Flags->isa_ext, makeArrayRef(ElfMipsISAExtType));
6756   W.printFlags("ASEs", Flags->ases, makeArrayRef(ElfMipsASEFlags));
6757   W.printEnum("FP ABI", Flags->fp_abi, makeArrayRef(ElfMipsFpABIType));
6758   W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size));
6759   W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size));
6760   W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size));
6761   W.printFlags("Flags 1", Flags->flags1, makeArrayRef(ElfMipsFlags1));
6762   W.printHex("Flags 2", Flags->flags2);
6763 }
6764