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