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