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.begin() == Syms.end())
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 template <> void ELFDumper<ELF32LE>::printUnwindInfo() {
2540   if (Obj.getHeader().e_machine == EM_ARM) {
2541     ARM::EHABI::PrinterContext<ELF32LE> Ctx(W, Obj, ObjF.getFileName(),
2542                                             DotSymtabSec);
2543     Ctx.PrintUnwindInformation();
2544   }
2545   DwarfCFIEH::PrinterContext<ELF32LE> Ctx(W, ObjF);
2546   Ctx.printUnwindInformation();
2547 }
2548 
2549 template <class ELFT> void ELFDumper<ELFT>::printNeededLibraries() {
2550   ListScope D(W, "NeededLibraries");
2551 
2552   std::vector<StringRef> Libs;
2553   for (const auto &Entry : dynamic_table())
2554     if (Entry.d_tag == ELF::DT_NEEDED)
2555       Libs.push_back(getDynamicString(Entry.d_un.d_val));
2556 
2557   llvm::sort(Libs);
2558 
2559   for (StringRef L : Libs)
2560     W.startLine() << L << "\n";
2561 }
2562 
2563 template <class ELFT>
2564 static Error checkHashTable(const ELFDumper<ELFT> &Dumper,
2565                             const typename ELFT::Hash *H,
2566                             bool *IsHeaderValid = nullptr) {
2567   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
2568   const uint64_t SecOffset = (const uint8_t *)H - Obj.base();
2569   if (Dumper.getHashTableEntSize() == 8) {
2570     auto It = llvm::find_if(ElfMachineType, [&](const EnumEntry<unsigned> &E) {
2571       return E.Value == Obj.getHeader().e_machine;
2572     });
2573     if (IsHeaderValid)
2574       *IsHeaderValid = false;
2575     return createError("the hash table at 0x" + Twine::utohexstr(SecOffset) +
2576                        " is not supported: it contains non-standard 8 "
2577                        "byte entries on " +
2578                        It->AltName + " platform");
2579   }
2580 
2581   auto MakeError = [&](const Twine &Msg = "") {
2582     return createError("the hash table at offset 0x" +
2583                        Twine::utohexstr(SecOffset) +
2584                        " goes past the end of the file (0x" +
2585                        Twine::utohexstr(Obj.getBufSize()) + ")" + Msg);
2586   };
2587 
2588   // Each SHT_HASH section starts from two 32-bit fields: nbucket and nchain.
2589   const unsigned HeaderSize = 2 * sizeof(typename ELFT::Word);
2590 
2591   if (IsHeaderValid)
2592     *IsHeaderValid = Obj.getBufSize() - SecOffset >= HeaderSize;
2593 
2594   if (Obj.getBufSize() - SecOffset < HeaderSize)
2595     return MakeError();
2596 
2597   if (Obj.getBufSize() - SecOffset - HeaderSize <
2598       ((uint64_t)H->nbucket + H->nchain) * sizeof(typename ELFT::Word))
2599     return MakeError(", nbucket = " + Twine(H->nbucket) +
2600                      ", nchain = " + Twine(H->nchain));
2601   return Error::success();
2602 }
2603 
2604 template <class ELFT>
2605 static Error checkGNUHashTable(const ELFFile<ELFT> &Obj,
2606                                const typename ELFT::GnuHash *GnuHashTable,
2607                                bool *IsHeaderValid = nullptr) {
2608   const uint8_t *TableData = reinterpret_cast<const uint8_t *>(GnuHashTable);
2609   assert(TableData >= Obj.base() && TableData < Obj.base() + Obj.getBufSize() &&
2610          "GnuHashTable must always point to a location inside the file");
2611 
2612   uint64_t TableOffset = TableData - Obj.base();
2613   if (IsHeaderValid)
2614     *IsHeaderValid = TableOffset + /*Header size:*/ 16 < Obj.getBufSize();
2615   if (TableOffset + 16 + (uint64_t)GnuHashTable->nbuckets * 4 +
2616           (uint64_t)GnuHashTable->maskwords * sizeof(typename ELFT::Off) >=
2617       Obj.getBufSize())
2618     return createError("unable to dump the SHT_GNU_HASH "
2619                        "section at 0x" +
2620                        Twine::utohexstr(TableOffset) +
2621                        ": it goes past the end of the file");
2622   return Error::success();
2623 }
2624 
2625 template <typename ELFT> void ELFDumper<ELFT>::printHashTable() {
2626   DictScope D(W, "HashTable");
2627   if (!HashTable)
2628     return;
2629 
2630   bool IsHeaderValid;
2631   Error Err = checkHashTable(*this, HashTable, &IsHeaderValid);
2632   if (IsHeaderValid) {
2633     W.printNumber("Num Buckets", HashTable->nbucket);
2634     W.printNumber("Num Chains", HashTable->nchain);
2635   }
2636 
2637   if (Err) {
2638     reportUniqueWarning(std::move(Err));
2639     return;
2640   }
2641 
2642   W.printList("Buckets", HashTable->buckets());
2643   W.printList("Chains", HashTable->chains());
2644 }
2645 
2646 template <class ELFT>
2647 static Expected<ArrayRef<typename ELFT::Word>>
2648 getGnuHashTableChains(Optional<DynRegionInfo> DynSymRegion,
2649                       const typename ELFT::GnuHash *GnuHashTable) {
2650   if (!DynSymRegion)
2651     return createError("no dynamic symbol table found");
2652 
2653   ArrayRef<typename ELFT::Sym> DynSymTable =
2654       DynSymRegion->template getAsArrayRef<typename ELFT::Sym>();
2655   size_t NumSyms = DynSymTable.size();
2656   if (!NumSyms)
2657     return createError("the dynamic symbol table is empty");
2658 
2659   if (GnuHashTable->symndx < NumSyms)
2660     return GnuHashTable->values(NumSyms);
2661 
2662   // A normal empty GNU hash table section produced by linker might have
2663   // symndx set to the number of dynamic symbols + 1 (for the zero symbol)
2664   // and have dummy null values in the Bloom filter and in the buckets
2665   // vector (or no values at all). It happens because the value of symndx is not
2666   // important for dynamic loaders when the GNU hash table is empty. They just
2667   // skip the whole object during symbol lookup. In such cases, the symndx value
2668   // is irrelevant and we should not report a warning.
2669   ArrayRef<typename ELFT::Word> Buckets = GnuHashTable->buckets();
2670   if (!llvm::all_of(Buckets, [](typename ELFT::Word V) { return V == 0; }))
2671     return createError(
2672         "the first hashed symbol index (" + Twine(GnuHashTable->symndx) +
2673         ") is greater than or equal to the number of dynamic symbols (" +
2674         Twine(NumSyms) + ")");
2675   // There is no way to represent an array of (dynamic symbols count - symndx)
2676   // length.
2677   return ArrayRef<typename ELFT::Word>();
2678 }
2679 
2680 template <typename ELFT>
2681 void ELFDumper<ELFT>::printGnuHashTable() {
2682   DictScope D(W, "GnuHashTable");
2683   if (!GnuHashTable)
2684     return;
2685 
2686   bool IsHeaderValid;
2687   Error Err = checkGNUHashTable<ELFT>(Obj, GnuHashTable, &IsHeaderValid);
2688   if (IsHeaderValid) {
2689     W.printNumber("Num Buckets", GnuHashTable->nbuckets);
2690     W.printNumber("First Hashed Symbol Index", GnuHashTable->symndx);
2691     W.printNumber("Num Mask Words", GnuHashTable->maskwords);
2692     W.printNumber("Shift Count", GnuHashTable->shift2);
2693   }
2694 
2695   if (Err) {
2696     reportUniqueWarning(std::move(Err));
2697     return;
2698   }
2699 
2700   ArrayRef<typename ELFT::Off> BloomFilter = GnuHashTable->filter();
2701   W.printHexList("Bloom Filter", BloomFilter);
2702 
2703   ArrayRef<Elf_Word> Buckets = GnuHashTable->buckets();
2704   W.printList("Buckets", Buckets);
2705 
2706   Expected<ArrayRef<Elf_Word>> Chains =
2707       getGnuHashTableChains<ELFT>(DynSymRegion, GnuHashTable);
2708   if (!Chains) {
2709     reportUniqueWarning("unable to dump 'Values' for the SHT_GNU_HASH "
2710                         "section: " +
2711                         toString(Chains.takeError()));
2712     return;
2713   }
2714 
2715   W.printHexList("Values", *Chains);
2716 }
2717 
2718 template <typename ELFT> void ELFDumper<ELFT>::printLoadName() {
2719   StringRef SOName = "<Not found>";
2720   if (SONameOffset)
2721     SOName = getDynamicString(*SONameOffset);
2722   W.printString("LoadName", SOName);
2723 }
2724 
2725 template <class ELFT> void ELFDumper<ELFT>::printArchSpecificInfo() {
2726   switch (Obj.getHeader().e_machine) {
2727   case EM_ARM:
2728   case EM_RISCV:
2729     printAttributes();
2730     break;
2731   case EM_MIPS: {
2732     printMipsABIFlags();
2733     printMipsOptions();
2734     printMipsReginfo();
2735     MipsGOTParser<ELFT> Parser(*this);
2736     if (Error E = Parser.findGOT(dynamic_table(), dynamic_symbols()))
2737       reportUniqueWarning(std::move(E));
2738     else if (!Parser.isGotEmpty())
2739       printMipsGOT(Parser);
2740 
2741     if (Error E = Parser.findPLT(dynamic_table()))
2742       reportUniqueWarning(std::move(E));
2743     else if (!Parser.isPltEmpty())
2744       printMipsPLT(Parser);
2745     break;
2746   }
2747   default:
2748     break;
2749   }
2750 }
2751 
2752 template <class ELFT> void ELFDumper<ELFT>::printAttributes() {
2753   if (!Obj.isLE()) {
2754     W.startLine() << "Attributes not implemented.\n";
2755     return;
2756   }
2757 
2758   const unsigned Machine = Obj.getHeader().e_machine;
2759   assert((Machine == EM_ARM || Machine == EM_RISCV) &&
2760          "Attributes not implemented.");
2761 
2762   DictScope BA(W, "BuildAttributes");
2763   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
2764     if (Sec.sh_type != ELF::SHT_ARM_ATTRIBUTES &&
2765         Sec.sh_type != ELF::SHT_RISCV_ATTRIBUTES)
2766       continue;
2767 
2768     ArrayRef<uint8_t> Contents;
2769     if (Expected<ArrayRef<uint8_t>> ContentOrErr =
2770             Obj.getSectionContents(Sec)) {
2771       Contents = *ContentOrErr;
2772       if (Contents.empty()) {
2773         reportUniqueWarning("the " + describe(Sec) + " is empty");
2774         continue;
2775       }
2776     } else {
2777       reportUniqueWarning("unable to read the content of the " + describe(Sec) +
2778                           ": " + toString(ContentOrErr.takeError()));
2779       continue;
2780     }
2781 
2782     W.printHex("FormatVersion", Contents[0]);
2783 
2784     auto ParseAttrubutes = [&]() {
2785       if (Machine == EM_ARM)
2786         return ARMAttributeParser(&W).parse(Contents, support::little);
2787       return RISCVAttributeParser(&W).parse(Contents, support::little);
2788     };
2789 
2790     if (Error E = ParseAttrubutes())
2791       reportUniqueWarning("unable to dump attributes from the " +
2792                           describe(Sec) + ": " + toString(std::move(E)));
2793   }
2794 }
2795 
2796 namespace {
2797 
2798 template <class ELFT> class MipsGOTParser {
2799 public:
2800   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
2801   using Entry = typename ELFT::Addr;
2802   using Entries = ArrayRef<Entry>;
2803 
2804   const bool IsStatic;
2805   const ELFFile<ELFT> &Obj;
2806   const ELFDumper<ELFT> &Dumper;
2807 
2808   MipsGOTParser(const ELFDumper<ELFT> &D);
2809   Error findGOT(Elf_Dyn_Range DynTable, Elf_Sym_Range DynSyms);
2810   Error findPLT(Elf_Dyn_Range DynTable);
2811 
2812   bool isGotEmpty() const { return GotEntries.empty(); }
2813   bool isPltEmpty() const { return PltEntries.empty(); }
2814 
2815   uint64_t getGp() const;
2816 
2817   const Entry *getGotLazyResolver() const;
2818   const Entry *getGotModulePointer() const;
2819   const Entry *getPltLazyResolver() const;
2820   const Entry *getPltModulePointer() const;
2821 
2822   Entries getLocalEntries() const;
2823   Entries getGlobalEntries() const;
2824   Entries getOtherEntries() const;
2825   Entries getPltEntries() const;
2826 
2827   uint64_t getGotAddress(const Entry * E) const;
2828   int64_t getGotOffset(const Entry * E) const;
2829   const Elf_Sym *getGotSym(const Entry *E) const;
2830 
2831   uint64_t getPltAddress(const Entry * E) const;
2832   const Elf_Sym *getPltSym(const Entry *E) const;
2833 
2834   StringRef getPltStrTable() const { return PltStrTable; }
2835   const Elf_Shdr *getPltSymTable() const { return PltSymTable; }
2836 
2837 private:
2838   const Elf_Shdr *GotSec;
2839   size_t LocalNum;
2840   size_t GlobalNum;
2841 
2842   const Elf_Shdr *PltSec;
2843   const Elf_Shdr *PltRelSec;
2844   const Elf_Shdr *PltSymTable;
2845   StringRef FileName;
2846 
2847   Elf_Sym_Range GotDynSyms;
2848   StringRef PltStrTable;
2849 
2850   Entries GotEntries;
2851   Entries PltEntries;
2852 };
2853 
2854 } // end anonymous namespace
2855 
2856 template <class ELFT>
2857 MipsGOTParser<ELFT>::MipsGOTParser(const ELFDumper<ELFT> &D)
2858     : IsStatic(D.dynamic_table().empty()), Obj(D.getElfObject().getELFFile()),
2859       Dumper(D), GotSec(nullptr), LocalNum(0), GlobalNum(0), PltSec(nullptr),
2860       PltRelSec(nullptr), PltSymTable(nullptr),
2861       FileName(D.getElfObject().getFileName()) {}
2862 
2863 template <class ELFT>
2864 Error MipsGOTParser<ELFT>::findGOT(Elf_Dyn_Range DynTable,
2865                                    Elf_Sym_Range DynSyms) {
2866   // See "Global Offset Table" in Chapter 5 in the following document
2867   // for detailed GOT description.
2868   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
2869 
2870   // Find static GOT secton.
2871   if (IsStatic) {
2872     GotSec = Dumper.findSectionByName(".got");
2873     if (!GotSec)
2874       return Error::success();
2875 
2876     ArrayRef<uint8_t> Content =
2877         unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
2878     GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
2879                          Content.size() / sizeof(Entry));
2880     LocalNum = GotEntries.size();
2881     return Error::success();
2882   }
2883 
2884   // Lookup dynamic table tags which define the GOT layout.
2885   Optional<uint64_t> DtPltGot;
2886   Optional<uint64_t> DtLocalGotNum;
2887   Optional<uint64_t> DtGotSym;
2888   for (const auto &Entry : DynTable) {
2889     switch (Entry.getTag()) {
2890     case ELF::DT_PLTGOT:
2891       DtPltGot = Entry.getVal();
2892       break;
2893     case ELF::DT_MIPS_LOCAL_GOTNO:
2894       DtLocalGotNum = Entry.getVal();
2895       break;
2896     case ELF::DT_MIPS_GOTSYM:
2897       DtGotSym = Entry.getVal();
2898       break;
2899     }
2900   }
2901 
2902   if (!DtPltGot && !DtLocalGotNum && !DtGotSym)
2903     return Error::success();
2904 
2905   if (!DtPltGot)
2906     return createError("cannot find PLTGOT dynamic tag");
2907   if (!DtLocalGotNum)
2908     return createError("cannot find MIPS_LOCAL_GOTNO dynamic tag");
2909   if (!DtGotSym)
2910     return createError("cannot find MIPS_GOTSYM dynamic tag");
2911 
2912   size_t DynSymTotal = DynSyms.size();
2913   if (*DtGotSym > DynSymTotal)
2914     return createError("DT_MIPS_GOTSYM value (" + Twine(*DtGotSym) +
2915                        ") exceeds the number of dynamic symbols (" +
2916                        Twine(DynSymTotal) + ")");
2917 
2918   GotSec = findNotEmptySectionByAddress(Obj, FileName, *DtPltGot);
2919   if (!GotSec)
2920     return createError("there is no non-empty GOT section at 0x" +
2921                        Twine::utohexstr(*DtPltGot));
2922 
2923   LocalNum = *DtLocalGotNum;
2924   GlobalNum = DynSymTotal - *DtGotSym;
2925 
2926   ArrayRef<uint8_t> Content =
2927       unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
2928   GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
2929                        Content.size() / sizeof(Entry));
2930   GotDynSyms = DynSyms.drop_front(*DtGotSym);
2931 
2932   return Error::success();
2933 }
2934 
2935 template <class ELFT>
2936 Error MipsGOTParser<ELFT>::findPLT(Elf_Dyn_Range DynTable) {
2937   // Lookup dynamic table tags which define the PLT layout.
2938   Optional<uint64_t> DtMipsPltGot;
2939   Optional<uint64_t> DtJmpRel;
2940   for (const auto &Entry : DynTable) {
2941     switch (Entry.getTag()) {
2942     case ELF::DT_MIPS_PLTGOT:
2943       DtMipsPltGot = Entry.getVal();
2944       break;
2945     case ELF::DT_JMPREL:
2946       DtJmpRel = Entry.getVal();
2947       break;
2948     }
2949   }
2950 
2951   if (!DtMipsPltGot && !DtJmpRel)
2952     return Error::success();
2953 
2954   // Find PLT section.
2955   if (!DtMipsPltGot)
2956     return createError("cannot find MIPS_PLTGOT dynamic tag");
2957   if (!DtJmpRel)
2958     return createError("cannot find JMPREL dynamic tag");
2959 
2960   PltSec = findNotEmptySectionByAddress(Obj, FileName, *DtMipsPltGot);
2961   if (!PltSec)
2962     return createError("there is no non-empty PLTGOT section at 0x" +
2963                        Twine::utohexstr(*DtMipsPltGot));
2964 
2965   PltRelSec = findNotEmptySectionByAddress(Obj, FileName, *DtJmpRel);
2966   if (!PltRelSec)
2967     return createError("there is no non-empty RELPLT section at 0x" +
2968                        Twine::utohexstr(*DtJmpRel));
2969 
2970   if (Expected<ArrayRef<uint8_t>> PltContentOrErr =
2971           Obj.getSectionContents(*PltSec))
2972     PltEntries =
2973         Entries(reinterpret_cast<const Entry *>(PltContentOrErr->data()),
2974                 PltContentOrErr->size() / sizeof(Entry));
2975   else
2976     return createError("unable to read PLTGOT section content: " +
2977                        toString(PltContentOrErr.takeError()));
2978 
2979   if (Expected<const Elf_Shdr *> PltSymTableOrErr =
2980           Obj.getSection(PltRelSec->sh_link))
2981     PltSymTable = *PltSymTableOrErr;
2982   else
2983     return createError("unable to get a symbol table linked to the " +
2984                        describe(Obj, *PltRelSec) + ": " +
2985                        toString(PltSymTableOrErr.takeError()));
2986 
2987   if (Expected<StringRef> StrTabOrErr =
2988           Obj.getStringTableForSymtab(*PltSymTable))
2989     PltStrTable = *StrTabOrErr;
2990   else
2991     return createError("unable to get a string table for the " +
2992                        describe(Obj, *PltSymTable) + ": " +
2993                        toString(StrTabOrErr.takeError()));
2994 
2995   return Error::success();
2996 }
2997 
2998 template <class ELFT> uint64_t MipsGOTParser<ELFT>::getGp() const {
2999   return GotSec->sh_addr + 0x7ff0;
3000 }
3001 
3002 template <class ELFT>
3003 const typename MipsGOTParser<ELFT>::Entry *
3004 MipsGOTParser<ELFT>::getGotLazyResolver() const {
3005   return LocalNum > 0 ? &GotEntries[0] : nullptr;
3006 }
3007 
3008 template <class ELFT>
3009 const typename MipsGOTParser<ELFT>::Entry *
3010 MipsGOTParser<ELFT>::getGotModulePointer() const {
3011   if (LocalNum < 2)
3012     return nullptr;
3013   const Entry &E = GotEntries[1];
3014   if ((E >> (sizeof(Entry) * 8 - 1)) == 0)
3015     return nullptr;
3016   return &E;
3017 }
3018 
3019 template <class ELFT>
3020 typename MipsGOTParser<ELFT>::Entries
3021 MipsGOTParser<ELFT>::getLocalEntries() const {
3022   size_t Skip = getGotModulePointer() ? 2 : 1;
3023   if (LocalNum - Skip <= 0)
3024     return Entries();
3025   return GotEntries.slice(Skip, LocalNum - Skip);
3026 }
3027 
3028 template <class ELFT>
3029 typename MipsGOTParser<ELFT>::Entries
3030 MipsGOTParser<ELFT>::getGlobalEntries() const {
3031   if (GlobalNum == 0)
3032     return Entries();
3033   return GotEntries.slice(LocalNum, GlobalNum);
3034 }
3035 
3036 template <class ELFT>
3037 typename MipsGOTParser<ELFT>::Entries
3038 MipsGOTParser<ELFT>::getOtherEntries() const {
3039   size_t OtherNum = GotEntries.size() - LocalNum - GlobalNum;
3040   if (OtherNum == 0)
3041     return Entries();
3042   return GotEntries.slice(LocalNum + GlobalNum, OtherNum);
3043 }
3044 
3045 template <class ELFT>
3046 uint64_t MipsGOTParser<ELFT>::getGotAddress(const Entry *E) const {
3047   int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
3048   return GotSec->sh_addr + Offset;
3049 }
3050 
3051 template <class ELFT>
3052 int64_t MipsGOTParser<ELFT>::getGotOffset(const Entry *E) const {
3053   int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
3054   return Offset - 0x7ff0;
3055 }
3056 
3057 template <class ELFT>
3058 const typename MipsGOTParser<ELFT>::Elf_Sym *
3059 MipsGOTParser<ELFT>::getGotSym(const Entry *E) const {
3060   int64_t Offset = std::distance(GotEntries.data(), E);
3061   return &GotDynSyms[Offset - LocalNum];
3062 }
3063 
3064 template <class ELFT>
3065 const typename MipsGOTParser<ELFT>::Entry *
3066 MipsGOTParser<ELFT>::getPltLazyResolver() const {
3067   return PltEntries.empty() ? nullptr : &PltEntries[0];
3068 }
3069 
3070 template <class ELFT>
3071 const typename MipsGOTParser<ELFT>::Entry *
3072 MipsGOTParser<ELFT>::getPltModulePointer() const {
3073   return PltEntries.size() < 2 ? nullptr : &PltEntries[1];
3074 }
3075 
3076 template <class ELFT>
3077 typename MipsGOTParser<ELFT>::Entries
3078 MipsGOTParser<ELFT>::getPltEntries() const {
3079   if (PltEntries.size() <= 2)
3080     return Entries();
3081   return PltEntries.slice(2, PltEntries.size() - 2);
3082 }
3083 
3084 template <class ELFT>
3085 uint64_t MipsGOTParser<ELFT>::getPltAddress(const Entry *E) const {
3086   int64_t Offset = std::distance(PltEntries.data(), E) * sizeof(Entry);
3087   return PltSec->sh_addr + Offset;
3088 }
3089 
3090 template <class ELFT>
3091 const typename MipsGOTParser<ELFT>::Elf_Sym *
3092 MipsGOTParser<ELFT>::getPltSym(const Entry *E) const {
3093   int64_t Offset = std::distance(getPltEntries().data(), E);
3094   if (PltRelSec->sh_type == ELF::SHT_REL) {
3095     Elf_Rel_Range Rels = unwrapOrError(FileName, Obj.rels(*PltRelSec));
3096     return unwrapOrError(FileName,
3097                          Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
3098   } else {
3099     Elf_Rela_Range Rels = unwrapOrError(FileName, Obj.relas(*PltRelSec));
3100     return unwrapOrError(FileName,
3101                          Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
3102   }
3103 }
3104 
3105 static const EnumEntry<unsigned> ElfMipsISAExtType[] = {
3106   {"None",                    Mips::AFL_EXT_NONE},
3107   {"Broadcom SB-1",           Mips::AFL_EXT_SB1},
3108   {"Cavium Networks Octeon",  Mips::AFL_EXT_OCTEON},
3109   {"Cavium Networks Octeon2", Mips::AFL_EXT_OCTEON2},
3110   {"Cavium Networks OcteonP", Mips::AFL_EXT_OCTEONP},
3111   {"Cavium Networks Octeon3", Mips::AFL_EXT_OCTEON3},
3112   {"LSI R4010",               Mips::AFL_EXT_4010},
3113   {"Loongson 2E",             Mips::AFL_EXT_LOONGSON_2E},
3114   {"Loongson 2F",             Mips::AFL_EXT_LOONGSON_2F},
3115   {"Loongson 3A",             Mips::AFL_EXT_LOONGSON_3A},
3116   {"MIPS R4650",              Mips::AFL_EXT_4650},
3117   {"MIPS R5900",              Mips::AFL_EXT_5900},
3118   {"MIPS R10000",             Mips::AFL_EXT_10000},
3119   {"NEC VR4100",              Mips::AFL_EXT_4100},
3120   {"NEC VR4111/VR4181",       Mips::AFL_EXT_4111},
3121   {"NEC VR4120",              Mips::AFL_EXT_4120},
3122   {"NEC VR5400",              Mips::AFL_EXT_5400},
3123   {"NEC VR5500",              Mips::AFL_EXT_5500},
3124   {"RMI Xlr",                 Mips::AFL_EXT_XLR},
3125   {"Toshiba R3900",           Mips::AFL_EXT_3900}
3126 };
3127 
3128 static const EnumEntry<unsigned> ElfMipsASEFlags[] = {
3129   {"DSP",                Mips::AFL_ASE_DSP},
3130   {"DSPR2",              Mips::AFL_ASE_DSPR2},
3131   {"Enhanced VA Scheme", Mips::AFL_ASE_EVA},
3132   {"MCU",                Mips::AFL_ASE_MCU},
3133   {"MDMX",               Mips::AFL_ASE_MDMX},
3134   {"MIPS-3D",            Mips::AFL_ASE_MIPS3D},
3135   {"MT",                 Mips::AFL_ASE_MT},
3136   {"SmartMIPS",          Mips::AFL_ASE_SMARTMIPS},
3137   {"VZ",                 Mips::AFL_ASE_VIRT},
3138   {"MSA",                Mips::AFL_ASE_MSA},
3139   {"MIPS16",             Mips::AFL_ASE_MIPS16},
3140   {"microMIPS",          Mips::AFL_ASE_MICROMIPS},
3141   {"XPA",                Mips::AFL_ASE_XPA},
3142   {"CRC",                Mips::AFL_ASE_CRC},
3143   {"GINV",               Mips::AFL_ASE_GINV},
3144 };
3145 
3146 static const EnumEntry<unsigned> ElfMipsFpABIType[] = {
3147   {"Hard or soft float",                  Mips::Val_GNU_MIPS_ABI_FP_ANY},
3148   {"Hard float (double precision)",       Mips::Val_GNU_MIPS_ABI_FP_DOUBLE},
3149   {"Hard float (single precision)",       Mips::Val_GNU_MIPS_ABI_FP_SINGLE},
3150   {"Soft float",                          Mips::Val_GNU_MIPS_ABI_FP_SOFT},
3151   {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)",
3152    Mips::Val_GNU_MIPS_ABI_FP_OLD_64},
3153   {"Hard float (32-bit CPU, Any FPU)",    Mips::Val_GNU_MIPS_ABI_FP_XX},
3154   {"Hard float (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64},
3155   {"Hard float compat (32-bit CPU, 64-bit FPU)",
3156    Mips::Val_GNU_MIPS_ABI_FP_64A}
3157 };
3158 
3159 static const EnumEntry<unsigned> ElfMipsFlags1[] {
3160   {"ODDSPREG", Mips::AFL_FLAGS1_ODDSPREG},
3161 };
3162 
3163 static int getMipsRegisterSize(uint8_t Flag) {
3164   switch (Flag) {
3165   case Mips::AFL_REG_NONE:
3166     return 0;
3167   case Mips::AFL_REG_32:
3168     return 32;
3169   case Mips::AFL_REG_64:
3170     return 64;
3171   case Mips::AFL_REG_128:
3172     return 128;
3173   default:
3174     return -1;
3175   }
3176 }
3177 
3178 template <class ELFT>
3179 static void printMipsReginfoData(ScopedPrinter &W,
3180                                  const Elf_Mips_RegInfo<ELFT> &Reginfo) {
3181   W.printHex("GP", Reginfo.ri_gp_value);
3182   W.printHex("General Mask", Reginfo.ri_gprmask);
3183   W.printHex("Co-Proc Mask0", Reginfo.ri_cprmask[0]);
3184   W.printHex("Co-Proc Mask1", Reginfo.ri_cprmask[1]);
3185   W.printHex("Co-Proc Mask2", Reginfo.ri_cprmask[2]);
3186   W.printHex("Co-Proc Mask3", Reginfo.ri_cprmask[3]);
3187 }
3188 
3189 template <class ELFT> void ELFDumper<ELFT>::printMipsReginfo() {
3190   const Elf_Shdr *RegInfoSec = findSectionByName(".reginfo");
3191   if (!RegInfoSec) {
3192     W.startLine() << "There is no .reginfo section in the file.\n";
3193     return;
3194   }
3195 
3196   Expected<ArrayRef<uint8_t>> ContentsOrErr =
3197       Obj.getSectionContents(*RegInfoSec);
3198   if (!ContentsOrErr) {
3199     this->reportUniqueWarning(
3200         "unable to read the content of the .reginfo section (" +
3201         describe(*RegInfoSec) + "): " + toString(ContentsOrErr.takeError()));
3202     return;
3203   }
3204 
3205   if (ContentsOrErr->size() < sizeof(Elf_Mips_RegInfo<ELFT>)) {
3206     this->reportUniqueWarning("the .reginfo section has an invalid size (0x" +
3207                               Twine::utohexstr(ContentsOrErr->size()) + ")");
3208     return;
3209   }
3210 
3211   DictScope GS(W, "MIPS RegInfo");
3212   printMipsReginfoData(W, *reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(
3213                               ContentsOrErr->data()));
3214 }
3215 
3216 template <class ELFT>
3217 static Expected<const Elf_Mips_Options<ELFT> *>
3218 readMipsOptions(const uint8_t *SecBegin, ArrayRef<uint8_t> &SecData,
3219                 bool &IsSupported) {
3220   if (SecData.size() < sizeof(Elf_Mips_Options<ELFT>))
3221     return createError("the .MIPS.options section has an invalid size (0x" +
3222                        Twine::utohexstr(SecData.size()) + ")");
3223 
3224   const Elf_Mips_Options<ELFT> *O =
3225       reinterpret_cast<const Elf_Mips_Options<ELFT> *>(SecData.data());
3226   const uint8_t Size = O->size;
3227   if (Size > SecData.size()) {
3228     const uint64_t Offset = SecData.data() - SecBegin;
3229     const uint64_t SecSize = Offset + SecData.size();
3230     return createError("a descriptor of size 0x" + Twine::utohexstr(Size) +
3231                        " at offset 0x" + Twine::utohexstr(Offset) +
3232                        " goes past the end of the .MIPS.options "
3233                        "section of size 0x" +
3234                        Twine::utohexstr(SecSize));
3235   }
3236 
3237   IsSupported = O->kind == ODK_REGINFO;
3238   const size_t ExpectedSize =
3239       sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>);
3240 
3241   if (IsSupported)
3242     if (Size < ExpectedSize)
3243       return createError(
3244           "a .MIPS.options entry of kind " +
3245           Twine(getElfMipsOptionsOdkType(O->kind)) +
3246           " has an invalid size (0x" + Twine::utohexstr(Size) +
3247           "), the expected size is 0x" + Twine::utohexstr(ExpectedSize));
3248 
3249   SecData = SecData.drop_front(Size);
3250   return O;
3251 }
3252 
3253 template <class ELFT> void ELFDumper<ELFT>::printMipsOptions() {
3254   const Elf_Shdr *MipsOpts = findSectionByName(".MIPS.options");
3255   if (!MipsOpts) {
3256     W.startLine() << "There is no .MIPS.options section in the file.\n";
3257     return;
3258   }
3259 
3260   DictScope GS(W, "MIPS Options");
3261 
3262   ArrayRef<uint8_t> Data =
3263       unwrapOrError(ObjF.getFileName(), Obj.getSectionContents(*MipsOpts));
3264   const uint8_t *const SecBegin = Data.begin();
3265   while (!Data.empty()) {
3266     bool IsSupported;
3267     Expected<const Elf_Mips_Options<ELFT> *> OptsOrErr =
3268         readMipsOptions<ELFT>(SecBegin, Data, IsSupported);
3269     if (!OptsOrErr) {
3270       reportUniqueWarning(OptsOrErr.takeError());
3271       break;
3272     }
3273 
3274     unsigned Kind = (*OptsOrErr)->kind;
3275     const char *Type = getElfMipsOptionsOdkType(Kind);
3276     if (!IsSupported) {
3277       W.startLine() << "Unsupported MIPS options tag: " << Type << " (" << Kind
3278                     << ")\n";
3279       continue;
3280     }
3281 
3282     DictScope GS(W, Type);
3283     if (Kind == ODK_REGINFO)
3284       printMipsReginfoData(W, (*OptsOrErr)->getRegInfo());
3285     else
3286       llvm_unreachable("unexpected .MIPS.options section descriptor kind");
3287   }
3288 }
3289 
3290 template <class ELFT> void ELFDumper<ELFT>::printStackMap() const {
3291   const Elf_Shdr *StackMapSection = findSectionByName(".llvm_stackmaps");
3292   if (!StackMapSection)
3293     return;
3294 
3295   auto Warn = [&](Error &&E) {
3296     this->reportUniqueWarning("unable to read the stack map from " +
3297                               describe(*StackMapSection) + ": " +
3298                               toString(std::move(E)));
3299   };
3300 
3301   Expected<ArrayRef<uint8_t>> ContentOrErr =
3302       Obj.getSectionContents(*StackMapSection);
3303   if (!ContentOrErr) {
3304     Warn(ContentOrErr.takeError());
3305     return;
3306   }
3307 
3308   if (Error E = StackMapParser<ELFT::TargetEndianness>::validateHeader(
3309           *ContentOrErr)) {
3310     Warn(std::move(E));
3311     return;
3312   }
3313 
3314   prettyPrintStackMap(W, StackMapParser<ELFT::TargetEndianness>(*ContentOrErr));
3315 }
3316 
3317 template <class ELFT>
3318 void ELFDumper<ELFT>::printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
3319                                  const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
3320   Expected<RelSymbol<ELFT>> Target = getRelocationTarget(R, SymTab);
3321   if (!Target)
3322     reportUniqueWarning("unable to print relocation " + Twine(RelIndex) +
3323                         " in " + describe(Sec) + ": " +
3324                         toString(Target.takeError()));
3325   else
3326     printRelRelaReloc(R, *Target);
3327 }
3328 
3329 static inline void printFields(formatted_raw_ostream &OS, StringRef Str1,
3330                                StringRef Str2) {
3331   OS.PadToColumn(2u);
3332   OS << Str1;
3333   OS.PadToColumn(37u);
3334   OS << Str2 << "\n";
3335   OS.flush();
3336 }
3337 
3338 template <class ELFT>
3339 static std::string getSectionHeadersNumString(const ELFFile<ELFT> &Obj,
3340                                               StringRef FileName) {
3341   const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3342   if (ElfHeader.e_shnum != 0)
3343     return to_string(ElfHeader.e_shnum);
3344 
3345   Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3346   if (!ArrOrErr) {
3347     // In this case we can ignore an error, because we have already reported a
3348     // warning about the broken section header table earlier.
3349     consumeError(ArrOrErr.takeError());
3350     return "<?>";
3351   }
3352 
3353   if (ArrOrErr->empty())
3354     return "0";
3355   return "0 (" + to_string((*ArrOrErr)[0].sh_size) + ")";
3356 }
3357 
3358 template <class ELFT>
3359 static std::string getSectionHeaderTableIndexString(const ELFFile<ELFT> &Obj,
3360                                                     StringRef FileName) {
3361   const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3362   if (ElfHeader.e_shstrndx != SHN_XINDEX)
3363     return to_string(ElfHeader.e_shstrndx);
3364 
3365   Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3366   if (!ArrOrErr) {
3367     // In this case we can ignore an error, because we have already reported a
3368     // warning about the broken section header table earlier.
3369     consumeError(ArrOrErr.takeError());
3370     return "<?>";
3371   }
3372 
3373   if (ArrOrErr->empty())
3374     return "65535 (corrupt: out of range)";
3375   return to_string(ElfHeader.e_shstrndx) + " (" +
3376          to_string((*ArrOrErr)[0].sh_link) + ")";
3377 }
3378 
3379 static const EnumEntry<unsigned> *getObjectFileEnumEntry(unsigned Type) {
3380   auto It = llvm::find_if(ElfObjectFileType, [&](const EnumEntry<unsigned> &E) {
3381     return E.Value == Type;
3382   });
3383   if (It != makeArrayRef(ElfObjectFileType).end())
3384     return It;
3385   return nullptr;
3386 }
3387 
3388 template <class ELFT> void GNUELFDumper<ELFT>::printFileHeaders() {
3389   const Elf_Ehdr &e = this->Obj.getHeader();
3390   OS << "ELF Header:\n";
3391   OS << "  Magic:  ";
3392   std::string Str;
3393   for (int i = 0; i < ELF::EI_NIDENT; i++)
3394     OS << format(" %02x", static_cast<int>(e.e_ident[i]));
3395   OS << "\n";
3396   Str = printEnum(e.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass));
3397   printFields(OS, "Class:", Str);
3398   Str = printEnum(e.e_ident[ELF::EI_DATA], makeArrayRef(ElfDataEncoding));
3399   printFields(OS, "Data:", Str);
3400   OS.PadToColumn(2u);
3401   OS << "Version:";
3402   OS.PadToColumn(37u);
3403   OS << to_hexString(e.e_ident[ELF::EI_VERSION]);
3404   if (e.e_version == ELF::EV_CURRENT)
3405     OS << " (current)";
3406   OS << "\n";
3407   Str = printEnum(e.e_ident[ELF::EI_OSABI], makeArrayRef(ElfOSABI));
3408   printFields(OS, "OS/ABI:", Str);
3409   printFields(OS,
3410               "ABI Version:", std::to_string(e.e_ident[ELF::EI_ABIVERSION]));
3411 
3412   if (const EnumEntry<unsigned> *E = getObjectFileEnumEntry(e.e_type)) {
3413     Str = E->AltName.str();
3414   } else {
3415     if (e.e_type >= ET_LOPROC)
3416       Str = "Processor Specific: (" + to_hexString(e.e_type, false) + ")";
3417     else if (e.e_type >= ET_LOOS)
3418       Str = "OS Specific: (" + to_hexString(e.e_type, false) + ")";
3419     else
3420       Str = "<unknown>: " + to_hexString(e.e_type, false);
3421   }
3422   printFields(OS, "Type:", Str);
3423 
3424   Str = printEnum(e.e_machine, makeArrayRef(ElfMachineType));
3425   printFields(OS, "Machine:", Str);
3426   Str = "0x" + to_hexString(e.e_version);
3427   printFields(OS, "Version:", Str);
3428   Str = "0x" + to_hexString(e.e_entry);
3429   printFields(OS, "Entry point address:", Str);
3430   Str = to_string(e.e_phoff) + " (bytes into file)";
3431   printFields(OS, "Start of program headers:", Str);
3432   Str = to_string(e.e_shoff) + " (bytes into file)";
3433   printFields(OS, "Start of section headers:", Str);
3434   std::string ElfFlags;
3435   if (e.e_machine == EM_MIPS)
3436     ElfFlags =
3437         printFlags(e.e_flags, makeArrayRef(ElfHeaderMipsFlags),
3438                    unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
3439                    unsigned(ELF::EF_MIPS_MACH));
3440   else if (e.e_machine == EM_RISCV)
3441     ElfFlags = printFlags(e.e_flags, makeArrayRef(ElfHeaderRISCVFlags));
3442   Str = "0x" + to_hexString(e.e_flags);
3443   if (!ElfFlags.empty())
3444     Str = Str + ", " + ElfFlags;
3445   printFields(OS, "Flags:", Str);
3446   Str = to_string(e.e_ehsize) + " (bytes)";
3447   printFields(OS, "Size of this header:", Str);
3448   Str = to_string(e.e_phentsize) + " (bytes)";
3449   printFields(OS, "Size of program headers:", Str);
3450   Str = to_string(e.e_phnum);
3451   printFields(OS, "Number of program headers:", Str);
3452   Str = to_string(e.e_shentsize) + " (bytes)";
3453   printFields(OS, "Size of section headers:", Str);
3454   Str = getSectionHeadersNumString(this->Obj, this->FileName);
3455   printFields(OS, "Number of section headers:", Str);
3456   Str = getSectionHeaderTableIndexString(this->Obj, this->FileName);
3457   printFields(OS, "Section header string table index:", Str);
3458 }
3459 
3460 template <class ELFT> std::vector<GroupSection> ELFDumper<ELFT>::getGroups() {
3461   auto GetSignature = [&](const Elf_Sym &Sym, unsigned SymNdx,
3462                           const Elf_Shdr &Symtab) -> StringRef {
3463     Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(Symtab);
3464     if (!StrTableOrErr) {
3465       reportUniqueWarning("unable to get the string table for " +
3466                           describe(Symtab) + ": " +
3467                           toString(StrTableOrErr.takeError()));
3468       return "<?>";
3469     }
3470 
3471     StringRef Strings = *StrTableOrErr;
3472     if (Sym.st_name >= Strings.size()) {
3473       reportUniqueWarning("unable to get the name of the symbol with index " +
3474                           Twine(SymNdx) + ": st_name (0x" +
3475                           Twine::utohexstr(Sym.st_name) +
3476                           ") is past the end of the string table of size 0x" +
3477                           Twine::utohexstr(Strings.size()));
3478       return "<?>";
3479     }
3480 
3481     return StrTableOrErr->data() + Sym.st_name;
3482   };
3483 
3484   std::vector<GroupSection> Ret;
3485   uint64_t I = 0;
3486   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
3487     ++I;
3488     if (Sec.sh_type != ELF::SHT_GROUP)
3489       continue;
3490 
3491     StringRef Signature = "<?>";
3492     if (Expected<const Elf_Shdr *> SymtabOrErr = Obj.getSection(Sec.sh_link)) {
3493       if (Expected<const Elf_Sym *> SymOrErr =
3494               Obj.template getEntry<Elf_Sym>(**SymtabOrErr, Sec.sh_info))
3495         Signature = GetSignature(**SymOrErr, Sec.sh_info, **SymtabOrErr);
3496       else
3497         reportUniqueWarning("unable to get the signature symbol for " +
3498                             describe(Sec) + ": " +
3499                             toString(SymOrErr.takeError()));
3500     } else {
3501       reportUniqueWarning("unable to get the symbol table for " +
3502                           describe(Sec) + ": " +
3503                           toString(SymtabOrErr.takeError()));
3504     }
3505 
3506     ArrayRef<Elf_Word> Data;
3507     if (Expected<ArrayRef<Elf_Word>> ContentsOrErr =
3508             Obj.template getSectionContentsAsArray<Elf_Word>(Sec)) {
3509       if (ContentsOrErr->empty())
3510         reportUniqueWarning("unable to read the section group flag from the " +
3511                             describe(Sec) + ": the section is empty");
3512       else
3513         Data = *ContentsOrErr;
3514     } else {
3515       reportUniqueWarning("unable to get the content of the " + describe(Sec) +
3516                           ": " + toString(ContentsOrErr.takeError()));
3517     }
3518 
3519     Ret.push_back({getPrintableSectionName(Sec),
3520                    maybeDemangle(Signature),
3521                    Sec.sh_name,
3522                    I - 1,
3523                    Sec.sh_link,
3524                    Sec.sh_info,
3525                    Data.empty() ? Elf_Word(0) : Data[0],
3526                    {}});
3527 
3528     if (Data.empty())
3529       continue;
3530 
3531     std::vector<GroupMember> &GM = Ret.back().Members;
3532     for (uint32_t Ndx : Data.slice(1)) {
3533       if (Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(Ndx)) {
3534         GM.push_back({getPrintableSectionName(**SecOrErr), Ndx});
3535       } else {
3536         reportUniqueWarning("unable to get the section with index " +
3537                             Twine(Ndx) + " when dumping the " + describe(Sec) +
3538                             ": " + toString(SecOrErr.takeError()));
3539         GM.push_back({"<?>", Ndx});
3540       }
3541     }
3542   }
3543   return Ret;
3544 }
3545 
3546 static DenseMap<uint64_t, const GroupSection *>
3547 mapSectionsToGroups(ArrayRef<GroupSection> Groups) {
3548   DenseMap<uint64_t, const GroupSection *> Ret;
3549   for (const GroupSection &G : Groups)
3550     for (const GroupMember &GM : G.Members)
3551       Ret.insert({GM.Index, &G});
3552   return Ret;
3553 }
3554 
3555 template <class ELFT> void GNUELFDumper<ELFT>::printGroupSections() {
3556   std::vector<GroupSection> V = this->getGroups();
3557   DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
3558   for (const GroupSection &G : V) {
3559     OS << "\n"
3560        << getGroupType(G.Type) << " group section ["
3561        << format_decimal(G.Index, 5) << "] `" << G.Name << "' [" << G.Signature
3562        << "] contains " << G.Members.size() << " sections:\n"
3563        << "   [Index]    Name\n";
3564     for (const GroupMember &GM : G.Members) {
3565       const GroupSection *MainGroup = Map[GM.Index];
3566       if (MainGroup != &G)
3567         this->reportUniqueWarning(
3568             "section with index " + Twine(GM.Index) +
3569             ", included in the group section with index " +
3570             Twine(MainGroup->Index) +
3571             ", was also found in the group section with index " +
3572             Twine(G.Index));
3573       OS << "   [" << format_decimal(GM.Index, 5) << "]   " << GM.Name << "\n";
3574     }
3575   }
3576 
3577   if (V.empty())
3578     OS << "There are no section groups in this file.\n";
3579 }
3580 
3581 template <class ELFT>
3582 void GNUELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
3583   OS << to_string(format_hex_no_prefix(R, ELFT::Is64Bits ? 16 : 8)) << "\n";
3584 }
3585 
3586 template <class ELFT>
3587 void GNUELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
3588                                            const RelSymbol<ELFT> &RelSym) {
3589   // First two fields are bit width dependent. The rest of them are fixed width.
3590   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3591   Field Fields[5] = {0, 10 + Bias, 19 + 2 * Bias, 42 + 2 * Bias, 53 + 2 * Bias};
3592   unsigned Width = ELFT::Is64Bits ? 16 : 8;
3593 
3594   Fields[0].Str = to_string(format_hex_no_prefix(R.Offset, Width));
3595   Fields[1].Str = to_string(format_hex_no_prefix(R.Info, Width));
3596 
3597   SmallString<32> RelocName;
3598   this->Obj.getRelocationTypeName(R.Type, RelocName);
3599   Fields[2].Str = RelocName.c_str();
3600 
3601   if (RelSym.Sym)
3602     Fields[3].Str =
3603         to_string(format_hex_no_prefix(RelSym.Sym->getValue(), Width));
3604 
3605   Fields[4].Str = std::string(RelSym.Name);
3606   for (const Field &F : Fields)
3607     printField(F);
3608 
3609   std::string Addend;
3610   if (Optional<int64_t> A = R.Addend) {
3611     int64_t RelAddend = *A;
3612     if (!RelSym.Name.empty()) {
3613       if (RelAddend < 0) {
3614         Addend = " - ";
3615         RelAddend = std::abs(RelAddend);
3616       } else {
3617         Addend = " + ";
3618       }
3619     }
3620     Addend += to_hexString(RelAddend, false);
3621   }
3622   OS << Addend << "\n";
3623 }
3624 
3625 template <class ELFT>
3626 static void printRelocHeaderFields(formatted_raw_ostream &OS, unsigned SType) {
3627   bool IsRela = SType == ELF::SHT_RELA || SType == ELF::SHT_ANDROID_RELA;
3628   bool IsRelr = SType == ELF::SHT_RELR || SType == ELF::SHT_ANDROID_RELR;
3629   if (ELFT::Is64Bits)
3630     OS << "    ";
3631   else
3632     OS << " ";
3633   if (IsRelr && opts::RawRelr)
3634     OS << "Data  ";
3635   else
3636     OS << "Offset";
3637   if (ELFT::Is64Bits)
3638     OS << "             Info             Type"
3639        << "               Symbol's Value  Symbol's Name";
3640   else
3641     OS << "     Info    Type                Sym. Value  Symbol's Name";
3642   if (IsRela)
3643     OS << " + Addend";
3644   OS << "\n";
3645 }
3646 
3647 template <class ELFT>
3648 void GNUELFDumper<ELFT>::printDynamicRelocHeader(unsigned Type, StringRef Name,
3649                                                  const DynRegionInfo &Reg) {
3650   uint64_t Offset = Reg.Addr - this->Obj.base();
3651   OS << "\n'" << Name.str().c_str() << "' relocation section at offset 0x"
3652      << to_hexString(Offset, false) << " contains " << Reg.Size << " bytes:\n";
3653   printRelocHeaderFields<ELFT>(OS, Type);
3654 }
3655 
3656 template <class ELFT>
3657 static bool isRelocationSec(const typename ELFT::Shdr &Sec) {
3658   return Sec.sh_type == ELF::SHT_REL || Sec.sh_type == ELF::SHT_RELA ||
3659          Sec.sh_type == ELF::SHT_RELR || Sec.sh_type == ELF::SHT_ANDROID_REL ||
3660          Sec.sh_type == ELF::SHT_ANDROID_RELA ||
3661          Sec.sh_type == ELF::SHT_ANDROID_RELR;
3662 }
3663 
3664 template <class ELFT> void GNUELFDumper<ELFT>::printRelocations() {
3665   auto GetEntriesNum = [&](const Elf_Shdr &Sec) -> Expected<size_t> {
3666     // Android's packed relocation section needs to be unpacked first
3667     // to get the actual number of entries.
3668     if (Sec.sh_type == ELF::SHT_ANDROID_REL ||
3669         Sec.sh_type == ELF::SHT_ANDROID_RELA) {
3670       Expected<std::vector<typename ELFT::Rela>> RelasOrErr =
3671           this->Obj.android_relas(Sec);
3672       if (!RelasOrErr)
3673         return RelasOrErr.takeError();
3674       return RelasOrErr->size();
3675     }
3676 
3677     if (!opts::RawRelr && (Sec.sh_type == ELF::SHT_RELR ||
3678                            Sec.sh_type == ELF::SHT_ANDROID_RELR)) {
3679       Expected<Elf_Relr_Range> RelrsOrErr = this->Obj.relrs(Sec);
3680       if (!RelrsOrErr)
3681         return RelrsOrErr.takeError();
3682       return this->Obj.decode_relrs(*RelrsOrErr).size();
3683     }
3684 
3685     return Sec.getEntityCount();
3686   };
3687 
3688   bool HasRelocSections = false;
3689   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
3690     if (!isRelocationSec<ELFT>(Sec))
3691       continue;
3692     HasRelocSections = true;
3693 
3694     std::string EntriesNum = "<?>";
3695     if (Expected<size_t> NumOrErr = GetEntriesNum(Sec))
3696       EntriesNum = std::to_string(*NumOrErr);
3697     else
3698       this->reportUniqueWarning("unable to get the number of relocations in " +
3699                                 this->describe(Sec) + ": " +
3700                                 toString(NumOrErr.takeError()));
3701 
3702     uintX_t Offset = Sec.sh_offset;
3703     StringRef Name = this->getPrintableSectionName(Sec);
3704     OS << "\nRelocation section '" << Name << "' at offset 0x"
3705        << to_hexString(Offset, false) << " contains " << EntriesNum
3706        << " entries:\n";
3707     printRelocHeaderFields<ELFT>(OS, Sec.sh_type);
3708     this->printRelocationsHelper(Sec);
3709   }
3710   if (!HasRelocSections)
3711     OS << "\nThere are no relocations in this file.\n";
3712 }
3713 
3714 // Print the offset of a particular section from anyone of the ranges:
3715 // [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER].
3716 // If 'Type' does not fall within any of those ranges, then a string is
3717 // returned as '<unknown>' followed by the type value.
3718 static std::string getSectionTypeOffsetString(unsigned Type) {
3719   if (Type >= SHT_LOOS && Type <= SHT_HIOS)
3720     return "LOOS+0x" + to_hexString(Type - SHT_LOOS);
3721   else if (Type >= SHT_LOPROC && Type <= SHT_HIPROC)
3722     return "LOPROC+0x" + to_hexString(Type - SHT_LOPROC);
3723   else if (Type >= SHT_LOUSER && Type <= SHT_HIUSER)
3724     return "LOUSER+0x" + to_hexString(Type - SHT_LOUSER);
3725   return "0x" + to_hexString(Type) + ": <unknown>";
3726 }
3727 
3728 static std::string getSectionTypeString(unsigned Machine, unsigned Type) {
3729   StringRef Name = getELFSectionTypeName(Machine, Type);
3730 
3731   // Handle SHT_GNU_* type names.
3732   if (Name.startswith("SHT_GNU_")) {
3733     if (Name == "SHT_GNU_HASH")
3734       return "GNU_HASH";
3735     // E.g. SHT_GNU_verneed -> VERNEED.
3736     return Name.drop_front(8).upper();
3737   }
3738 
3739   if (Name == "SHT_SYMTAB_SHNDX")
3740     return "SYMTAB SECTION INDICES";
3741 
3742   if (Name.startswith("SHT_"))
3743     return Name.drop_front(4).str();
3744   return getSectionTypeOffsetString(Type);
3745 }
3746 
3747 static void printSectionDescription(formatted_raw_ostream &OS,
3748                                     unsigned EMachine) {
3749   OS << "Key to Flags:\n";
3750   OS << "  W (write), A (alloc), X (execute), M (merge), S (strings), I "
3751         "(info),\n";
3752   OS << "  L (link order), O (extra OS processing required), G (group), T "
3753         "(TLS),\n";
3754   OS << "  C (compressed), x (unknown), o (OS specific), E (exclude),\n";
3755 
3756   if (EMachine == EM_X86_64)
3757     OS << "  l (large), ";
3758   else if (EMachine == EM_ARM)
3759     OS << "  y (purecode), ";
3760   else
3761     OS << "  ";
3762 
3763   OS << "p (processor specific)\n";
3764 }
3765 
3766 template <class ELFT> void GNUELFDumper<ELFT>::printSectionHeaders() {
3767   unsigned Bias = ELFT::Is64Bits ? 0 : 8;
3768   ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
3769   OS << "There are " << to_string(Sections.size())
3770      << " section headers, starting at offset "
3771      << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n";
3772   OS << "Section Headers:\n";
3773   Field Fields[11] = {
3774       {"[Nr]", 2},        {"Name", 7},        {"Type", 25},
3775       {"Address", 41},    {"Off", 58 - Bias}, {"Size", 65 - Bias},
3776       {"ES", 72 - Bias},  {"Flg", 75 - Bias}, {"Lk", 79 - Bias},
3777       {"Inf", 82 - Bias}, {"Al", 86 - Bias}};
3778   for (const Field &F : Fields)
3779     printField(F);
3780   OS << "\n";
3781 
3782   StringRef SecStrTable;
3783   if (Expected<StringRef> SecStrTableOrErr =
3784           this->Obj.getSectionStringTable(Sections, this->WarningHandler))
3785     SecStrTable = *SecStrTableOrErr;
3786   else
3787     this->reportUniqueWarning(SecStrTableOrErr.takeError());
3788 
3789   size_t SectionIndex = 0;
3790   for (const Elf_Shdr &Sec : Sections) {
3791     Fields[0].Str = to_string(SectionIndex);
3792     if (SecStrTable.empty())
3793       Fields[1].Str = "<no-strings>";
3794     else
3795       Fields[1].Str = std::string(unwrapOrError<StringRef>(
3796           this->FileName, this->Obj.getSectionName(Sec, SecStrTable)));
3797     Fields[2].Str =
3798         getSectionTypeString(this->Obj.getHeader().e_machine, Sec.sh_type);
3799     Fields[3].Str =
3800         to_string(format_hex_no_prefix(Sec.sh_addr, ELFT::Is64Bits ? 16 : 8));
3801     Fields[4].Str = to_string(format_hex_no_prefix(Sec.sh_offset, 6));
3802     Fields[5].Str = to_string(format_hex_no_prefix(Sec.sh_size, 6));
3803     Fields[6].Str = to_string(format_hex_no_prefix(Sec.sh_entsize, 2));
3804     Fields[7].Str = getGNUFlags(this->Obj.getHeader().e_machine, Sec.sh_flags);
3805     Fields[8].Str = to_string(Sec.sh_link);
3806     Fields[9].Str = to_string(Sec.sh_info);
3807     Fields[10].Str = to_string(Sec.sh_addralign);
3808 
3809     OS.PadToColumn(Fields[0].Column);
3810     OS << "[" << right_justify(Fields[0].Str, 2) << "]";
3811     for (int i = 1; i < 7; i++)
3812       printField(Fields[i]);
3813     OS.PadToColumn(Fields[7].Column);
3814     OS << right_justify(Fields[7].Str, 3);
3815     OS.PadToColumn(Fields[8].Column);
3816     OS << right_justify(Fields[8].Str, 2);
3817     OS.PadToColumn(Fields[9].Column);
3818     OS << right_justify(Fields[9].Str, 3);
3819     OS.PadToColumn(Fields[10].Column);
3820     OS << right_justify(Fields[10].Str, 2);
3821     OS << "\n";
3822     ++SectionIndex;
3823   }
3824   printSectionDescription(OS, this->Obj.getHeader().e_machine);
3825 }
3826 
3827 template <class ELFT>
3828 void GNUELFDumper<ELFT>::printSymtabMessage(const Elf_Shdr *Symtab,
3829                                             size_t Entries,
3830                                             bool NonVisibilityBitsUsed) const {
3831   StringRef Name;
3832   if (Symtab)
3833     Name = this->getPrintableSectionName(*Symtab);
3834   if (!Name.empty())
3835     OS << "\nSymbol table '" << Name << "'";
3836   else
3837     OS << "\nSymbol table for image";
3838   OS << " contains " << Entries << " entries:\n";
3839 
3840   if (ELFT::Is64Bits)
3841     OS << "   Num:    Value          Size Type    Bind   Vis";
3842   else
3843     OS << "   Num:    Value  Size Type    Bind   Vis";
3844 
3845   if (NonVisibilityBitsUsed)
3846     OS << "             ";
3847   OS << "       Ndx Name\n";
3848 }
3849 
3850 template <class ELFT>
3851 std::string
3852 GNUELFDumper<ELFT>::getSymbolSectionNdx(const Elf_Sym &Symbol,
3853                                         unsigned SymIndex,
3854                                         DataRegion<Elf_Word> ShndxTable) const {
3855   unsigned SectionIndex = Symbol.st_shndx;
3856   switch (SectionIndex) {
3857   case ELF::SHN_UNDEF:
3858     return "UND";
3859   case ELF::SHN_ABS:
3860     return "ABS";
3861   case ELF::SHN_COMMON:
3862     return "COM";
3863   case ELF::SHN_XINDEX: {
3864     Expected<uint32_t> IndexOrErr =
3865         object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, ShndxTable);
3866     if (!IndexOrErr) {
3867       assert(Symbol.st_shndx == SHN_XINDEX &&
3868              "getExtendedSymbolTableIndex should only fail due to an invalid "
3869              "SHT_SYMTAB_SHNDX table/reference");
3870       this->reportUniqueWarning(IndexOrErr.takeError());
3871       return "RSV[0xffff]";
3872     }
3873     return to_string(format_decimal(*IndexOrErr, 3));
3874   }
3875   default:
3876     // Find if:
3877     // Processor specific
3878     if (SectionIndex >= ELF::SHN_LOPROC && SectionIndex <= ELF::SHN_HIPROC)
3879       return std::string("PRC[0x") +
3880              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3881     // OS specific
3882     if (SectionIndex >= ELF::SHN_LOOS && SectionIndex <= ELF::SHN_HIOS)
3883       return std::string("OS[0x") +
3884              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3885     // Architecture reserved:
3886     if (SectionIndex >= ELF::SHN_LORESERVE &&
3887         SectionIndex <= ELF::SHN_HIRESERVE)
3888       return std::string("RSV[0x") +
3889              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3890     // A normal section with an index
3891     return to_string(format_decimal(SectionIndex, 3));
3892   }
3893 }
3894 
3895 template <class ELFT>
3896 void GNUELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
3897                                      DataRegion<Elf_Word> ShndxTable,
3898                                      Optional<StringRef> StrTable,
3899                                      bool IsDynamic,
3900                                      bool NonVisibilityBitsUsed) const {
3901   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3902   Field Fields[8] = {0,         8,         17 + Bias, 23 + Bias,
3903                      31 + Bias, 38 + Bias, 48 + Bias, 51 + Bias};
3904   Fields[0].Str = to_string(format_decimal(SymIndex, 6)) + ":";
3905   Fields[1].Str =
3906       to_string(format_hex_no_prefix(Symbol.st_value, ELFT::Is64Bits ? 16 : 8));
3907   Fields[2].Str = to_string(format_decimal(Symbol.st_size, 5));
3908 
3909   unsigned char SymbolType = Symbol.getType();
3910   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
3911       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
3912     Fields[3].Str = printEnum(SymbolType, makeArrayRef(AMDGPUSymbolTypes));
3913   else
3914     Fields[3].Str = printEnum(SymbolType, makeArrayRef(ElfSymbolTypes));
3915 
3916   Fields[4].Str =
3917       printEnum(Symbol.getBinding(), makeArrayRef(ElfSymbolBindings));
3918   Fields[5].Str =
3919       printEnum(Symbol.getVisibility(), makeArrayRef(ElfSymbolVisibilities));
3920 
3921   if (Symbol.st_other & ~0x3) {
3922     if (this->Obj.getHeader().e_machine == ELF::EM_AARCH64) {
3923       uint8_t Other = Symbol.st_other & ~0x3;
3924       if (Other & STO_AARCH64_VARIANT_PCS) {
3925         Other &= ~STO_AARCH64_VARIANT_PCS;
3926         Fields[5].Str += " [VARIANT_PCS";
3927         if (Other != 0)
3928           Fields[5].Str.append(" | " + to_hexString(Other, false));
3929         Fields[5].Str.append("]");
3930       }
3931     } else {
3932       Fields[5].Str +=
3933           " [<other: " + to_string(format_hex(Symbol.st_other, 2)) + ">]";
3934     }
3935   }
3936 
3937   Fields[6].Column += NonVisibilityBitsUsed ? 13 : 0;
3938   Fields[6].Str = getSymbolSectionNdx(Symbol, SymIndex, ShndxTable);
3939 
3940   Fields[7].Str = this->getFullSymbolName(Symbol, SymIndex, ShndxTable,
3941                                           StrTable, IsDynamic);
3942   for (const Field &Entry : Fields)
3943     printField(Entry);
3944   OS << "\n";
3945 }
3946 
3947 template <class ELFT>
3948 void GNUELFDumper<ELFT>::printHashedSymbol(const Elf_Sym *Symbol,
3949                                            unsigned SymIndex,
3950                                            DataRegion<Elf_Word> ShndxTable,
3951                                            StringRef StrTable,
3952                                            uint32_t Bucket) {
3953   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3954   Field Fields[9] = {0,         6,         11,        20 + Bias, 25 + Bias,
3955                      34 + Bias, 41 + Bias, 49 + Bias, 53 + Bias};
3956   Fields[0].Str = to_string(format_decimal(SymIndex, 5));
3957   Fields[1].Str = to_string(format_decimal(Bucket, 3)) + ":";
3958 
3959   Fields[2].Str = to_string(
3960       format_hex_no_prefix(Symbol->st_value, ELFT::Is64Bits ? 16 : 8));
3961   Fields[3].Str = to_string(format_decimal(Symbol->st_size, 5));
3962 
3963   unsigned char SymbolType = Symbol->getType();
3964   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
3965       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
3966     Fields[4].Str = printEnum(SymbolType, makeArrayRef(AMDGPUSymbolTypes));
3967   else
3968     Fields[4].Str = printEnum(SymbolType, makeArrayRef(ElfSymbolTypes));
3969 
3970   Fields[5].Str =
3971       printEnum(Symbol->getBinding(), makeArrayRef(ElfSymbolBindings));
3972   Fields[6].Str =
3973       printEnum(Symbol->getVisibility(), makeArrayRef(ElfSymbolVisibilities));
3974   Fields[7].Str = getSymbolSectionNdx(*Symbol, SymIndex, ShndxTable);
3975   Fields[8].Str =
3976       this->getFullSymbolName(*Symbol, SymIndex, ShndxTable, StrTable, true);
3977 
3978   for (const Field &Entry : Fields)
3979     printField(Entry);
3980   OS << "\n";
3981 }
3982 
3983 template <class ELFT>
3984 void GNUELFDumper<ELFT>::printSymbols(bool PrintSymbols,
3985                                       bool PrintDynamicSymbols) {
3986   if (!PrintSymbols && !PrintDynamicSymbols)
3987     return;
3988   // GNU readelf prints both the .dynsym and .symtab with --symbols.
3989   this->printSymbolsHelper(true);
3990   if (PrintSymbols)
3991     this->printSymbolsHelper(false);
3992 }
3993 
3994 template <class ELFT>
3995 void GNUELFDumper<ELFT>::printHashTableSymbols(const Elf_Hash &SysVHash) {
3996   if (this->DynamicStringTable.empty())
3997     return;
3998 
3999   if (ELFT::Is64Bits)
4000     OS << "  Num Buc:    Value          Size   Type   Bind Vis      Ndx Name";
4001   else
4002     OS << "  Num Buc:    Value  Size   Type   Bind Vis      Ndx Name";
4003   OS << "\n";
4004 
4005   Elf_Sym_Range DynSyms = this->dynamic_symbols();
4006   const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
4007   if (!FirstSym) {
4008     this->reportUniqueWarning(
4009         Twine("unable to print symbols for the .hash table: the "
4010               "dynamic symbol table ") +
4011         (this->DynSymRegion ? "is empty" : "was not found"));
4012     return;
4013   }
4014 
4015   DataRegion<Elf_Word> ShndxTable(
4016       (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
4017   auto Buckets = SysVHash.buckets();
4018   auto Chains = SysVHash.chains();
4019   for (uint32_t Buc = 0; Buc < SysVHash.nbucket; Buc++) {
4020     if (Buckets[Buc] == ELF::STN_UNDEF)
4021       continue;
4022     std::vector<bool> Visited(SysVHash.nchain);
4023     for (uint32_t Ch = Buckets[Buc]; Ch < SysVHash.nchain; Ch = Chains[Ch]) {
4024       if (Ch == ELF::STN_UNDEF)
4025         break;
4026 
4027       if (Visited[Ch]) {
4028         this->reportUniqueWarning(".hash section is invalid: bucket " +
4029                                   Twine(Ch) +
4030                                   ": a cycle was detected in the linked chain");
4031         break;
4032       }
4033 
4034       printHashedSymbol(FirstSym + Ch, Ch, ShndxTable, this->DynamicStringTable,
4035                         Buc);
4036       Visited[Ch] = true;
4037     }
4038   }
4039 }
4040 
4041 template <class ELFT>
4042 void GNUELFDumper<ELFT>::printGnuHashTableSymbols(const Elf_GnuHash &GnuHash) {
4043   if (this->DynamicStringTable.empty())
4044     return;
4045 
4046   Elf_Sym_Range DynSyms = this->dynamic_symbols();
4047   const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
4048   if (!FirstSym) {
4049     this->reportUniqueWarning(
4050         Twine("unable to print symbols for the .gnu.hash table: the "
4051               "dynamic symbol table ") +
4052         (this->DynSymRegion ? "is empty" : "was not found"));
4053     return;
4054   }
4055 
4056   auto GetSymbol = [&](uint64_t SymIndex,
4057                        uint64_t SymsTotal) -> const Elf_Sym * {
4058     if (SymIndex >= SymsTotal) {
4059       this->reportUniqueWarning(
4060           "unable to print hashed symbol with index " + Twine(SymIndex) +
4061           ", which is greater than or equal to the number of dynamic symbols "
4062           "(" +
4063           Twine::utohexstr(SymsTotal) + ")");
4064       return nullptr;
4065     }
4066     return FirstSym + SymIndex;
4067   };
4068 
4069   Expected<ArrayRef<Elf_Word>> ValuesOrErr =
4070       getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHash);
4071   ArrayRef<Elf_Word> Values;
4072   if (!ValuesOrErr)
4073     this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH "
4074                               "section: " +
4075                               toString(ValuesOrErr.takeError()));
4076   else
4077     Values = *ValuesOrErr;
4078 
4079   DataRegion<Elf_Word> ShndxTable(
4080       (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
4081   ArrayRef<Elf_Word> Buckets = GnuHash.buckets();
4082   for (uint32_t Buc = 0; Buc < GnuHash.nbuckets; Buc++) {
4083     if (Buckets[Buc] == ELF::STN_UNDEF)
4084       continue;
4085     uint32_t Index = Buckets[Buc];
4086     // Print whole chain.
4087     while (true) {
4088       uint32_t SymIndex = Index++;
4089       if (const Elf_Sym *Sym = GetSymbol(SymIndex, DynSyms.size()))
4090         printHashedSymbol(Sym, SymIndex, ShndxTable, this->DynamicStringTable,
4091                           Buc);
4092       else
4093         break;
4094 
4095       if (SymIndex < GnuHash.symndx) {
4096         this->reportUniqueWarning(
4097             "unable to read the hash value for symbol with index " +
4098             Twine(SymIndex) +
4099             ", which is less than the index of the first hashed symbol (" +
4100             Twine(GnuHash.symndx) + ")");
4101         break;
4102       }
4103 
4104        // Chain ends at symbol with stopper bit.
4105       if ((Values[SymIndex - GnuHash.symndx] & 1) == 1)
4106         break;
4107     }
4108   }
4109 }
4110 
4111 template <class ELFT> void GNUELFDumper<ELFT>::printHashSymbols() {
4112   if (this->HashTable) {
4113     OS << "\n Symbol table of .hash for image:\n";
4114     if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
4115       this->reportUniqueWarning(std::move(E));
4116     else
4117       printHashTableSymbols(*this->HashTable);
4118   }
4119 
4120   // Try printing the .gnu.hash table.
4121   if (this->GnuHashTable) {
4122     OS << "\n Symbol table of .gnu.hash for image:\n";
4123     if (ELFT::Is64Bits)
4124       OS << "  Num Buc:    Value          Size   Type   Bind Vis      Ndx Name";
4125     else
4126       OS << "  Num Buc:    Value  Size   Type   Bind Vis      Ndx Name";
4127     OS << "\n";
4128 
4129     if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
4130       this->reportUniqueWarning(std::move(E));
4131     else
4132       printGnuHashTableSymbols(*this->GnuHashTable);
4133   }
4134 }
4135 
4136 template <class ELFT> void GNUELFDumper<ELFT>::printSectionDetails() {
4137   ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
4138   OS << "There are " << to_string(Sections.size())
4139      << " section headers, starting at offset "
4140      << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n";
4141 
4142   OS << "Section Headers:\n";
4143 
4144   auto PrintFields = [&](ArrayRef<Field> V) {
4145     for (const Field &F : V)
4146       printField(F);
4147     OS << "\n";
4148   };
4149 
4150   PrintFields({{"[Nr]", 2}, {"Name", 7}});
4151 
4152   constexpr bool Is64 = ELFT::Is64Bits;
4153   PrintFields({{"Type", 7},
4154                {Is64 ? "Address" : "Addr", 23},
4155                {"Off", Is64 ? 40 : 32},
4156                {"Size", Is64 ? 47 : 39},
4157                {"ES", Is64 ? 54 : 46},
4158                {"Lk", Is64 ? 59 : 51},
4159                {"Inf", Is64 ? 62 : 54},
4160                {"Al", Is64 ? 66 : 57}});
4161   PrintFields({{"Flags", 7}});
4162 
4163   StringRef SecStrTable;
4164   if (Expected<StringRef> SecStrTableOrErr =
4165           this->Obj.getSectionStringTable(Sections, this->WarningHandler))
4166     SecStrTable = *SecStrTableOrErr;
4167   else
4168     this->reportUniqueWarning(SecStrTableOrErr.takeError());
4169 
4170   size_t SectionIndex = 0;
4171   const unsigned AddrSize = Is64 ? 16 : 8;
4172   for (const Elf_Shdr &S : Sections) {
4173     StringRef Name = "<?>";
4174     if (Expected<StringRef> NameOrErr =
4175             this->Obj.getSectionName(S, SecStrTable))
4176       Name = *NameOrErr;
4177     else
4178       this->reportUniqueWarning(NameOrErr.takeError());
4179 
4180     OS.PadToColumn(2);
4181     OS << "[" << right_justify(to_string(SectionIndex), 2) << "]";
4182     PrintFields({{Name, 7}});
4183     PrintFields(
4184         {{getSectionTypeString(this->Obj.getHeader().e_machine, S.sh_type), 7},
4185          {to_string(format_hex_no_prefix(S.sh_addr, AddrSize)), 23},
4186          {to_string(format_hex_no_prefix(S.sh_offset, 6)), Is64 ? 39 : 32},
4187          {to_string(format_hex_no_prefix(S.sh_size, 6)), Is64 ? 47 : 39},
4188          {to_string(format_hex_no_prefix(S.sh_entsize, 2)), Is64 ? 54 : 46},
4189          {to_string(S.sh_link), Is64 ? 59 : 51},
4190          {to_string(S.sh_info), Is64 ? 63 : 55},
4191          {to_string(S.sh_addralign), Is64 ? 66 : 58}});
4192 
4193     OS.PadToColumn(7);
4194     OS << "[" << to_string(format_hex_no_prefix(S.sh_flags, AddrSize)) << "]: ";
4195 
4196     DenseMap<unsigned, StringRef> FlagToName = {
4197         {SHF_WRITE, "WRITE"},           {SHF_ALLOC, "ALLOC"},
4198         {SHF_EXECINSTR, "EXEC"},        {SHF_MERGE, "MERGE"},
4199         {SHF_STRINGS, "STRINGS"},       {SHF_INFO_LINK, "INFO LINK"},
4200         {SHF_LINK_ORDER, "LINK ORDER"}, {SHF_OS_NONCONFORMING, "OS NONCONF"},
4201         {SHF_GROUP, "GROUP"},           {SHF_TLS, "TLS"},
4202         {SHF_COMPRESSED, "COMPRESSED"}, {SHF_EXCLUDE, "EXCLUDE"}};
4203 
4204     uint64_t Flags = S.sh_flags;
4205     uint64_t UnknownFlags = 0;
4206     bool NeedsComma = false;
4207     while (Flags) {
4208       // Take the least significant bit as a flag.
4209       uint64_t Flag = Flags & -Flags;
4210       Flags -= Flag;
4211 
4212       auto It = FlagToName.find(Flag);
4213       if (It != FlagToName.end()) {
4214         if (NeedsComma)
4215           OS << ", ";
4216         NeedsComma = true;
4217         OS << It->second;
4218       } else {
4219         UnknownFlags |= Flag;
4220       }
4221     }
4222 
4223     auto PrintUnknownFlags = [&](uint64_t Mask, StringRef Name) {
4224       uint64_t FlagsToPrint = UnknownFlags & Mask;
4225       if (!FlagsToPrint)
4226         return;
4227 
4228       if (NeedsComma)
4229         OS << ", ";
4230       OS << Name << " ("
4231          << to_string(format_hex_no_prefix(FlagsToPrint, AddrSize)) << ")";
4232       UnknownFlags &= ~Mask;
4233       NeedsComma = true;
4234     };
4235 
4236     PrintUnknownFlags(SHF_MASKOS, "OS");
4237     PrintUnknownFlags(SHF_MASKPROC, "PROC");
4238     PrintUnknownFlags(uint64_t(-1), "UNKNOWN");
4239 
4240     OS << "\n";
4241     ++SectionIndex;
4242   }
4243 }
4244 
4245 static inline std::string printPhdrFlags(unsigned Flag) {
4246   std::string Str;
4247   Str = (Flag & PF_R) ? "R" : " ";
4248   Str += (Flag & PF_W) ? "W" : " ";
4249   Str += (Flag & PF_X) ? "E" : " ";
4250   return Str;
4251 }
4252 
4253 template <class ELFT>
4254 static bool checkTLSSections(const typename ELFT::Phdr &Phdr,
4255                              const typename ELFT::Shdr &Sec) {
4256   if (Sec.sh_flags & ELF::SHF_TLS) {
4257     // .tbss must only be shown in the PT_TLS segment.
4258     if (Sec.sh_type == ELF::SHT_NOBITS)
4259       return Phdr.p_type == ELF::PT_TLS;
4260 
4261     // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO
4262     // segments.
4263     return (Phdr.p_type == ELF::PT_TLS) || (Phdr.p_type == ELF::PT_LOAD) ||
4264            (Phdr.p_type == ELF::PT_GNU_RELRO);
4265   }
4266 
4267   // PT_TLS must only have SHF_TLS sections.
4268   return Phdr.p_type != ELF::PT_TLS;
4269 }
4270 
4271 template <class ELFT>
4272 static bool checkOffsets(const typename ELFT::Phdr &Phdr,
4273                          const typename ELFT::Shdr &Sec) {
4274   // SHT_NOBITS sections don't need to have an offset inside the segment.
4275   if (Sec.sh_type == ELF::SHT_NOBITS)
4276     return true;
4277 
4278   if (Sec.sh_offset < Phdr.p_offset)
4279     return false;
4280 
4281   // Only non-empty sections can be at the end of a segment.
4282   if (Sec.sh_size == 0)
4283     return (Sec.sh_offset + 1 <= Phdr.p_offset + Phdr.p_filesz);
4284   return Sec.sh_offset + Sec.sh_size <= Phdr.p_offset + Phdr.p_filesz;
4285 }
4286 
4287 // Check that an allocatable section belongs to a virtual address
4288 // space of a segment.
4289 template <class ELFT>
4290 static bool checkVMA(const typename ELFT::Phdr &Phdr,
4291                      const typename ELFT::Shdr &Sec) {
4292   if (!(Sec.sh_flags & ELF::SHF_ALLOC))
4293     return true;
4294 
4295   if (Sec.sh_addr < Phdr.p_vaddr)
4296     return false;
4297 
4298   bool IsTbss =
4299       (Sec.sh_type == ELF::SHT_NOBITS) && ((Sec.sh_flags & ELF::SHF_TLS) != 0);
4300   // .tbss is special, it only has memory in PT_TLS and has NOBITS properties.
4301   bool IsTbssInNonTLS = IsTbss && Phdr.p_type != ELF::PT_TLS;
4302   // Only non-empty sections can be at the end of a segment.
4303   if (Sec.sh_size == 0 || IsTbssInNonTLS)
4304     return Sec.sh_addr + 1 <= Phdr.p_vaddr + Phdr.p_memsz;
4305   return Sec.sh_addr + Sec.sh_size <= Phdr.p_vaddr + Phdr.p_memsz;
4306 }
4307 
4308 template <class ELFT>
4309 static bool checkPTDynamic(const typename ELFT::Phdr &Phdr,
4310                            const typename ELFT::Shdr &Sec) {
4311   if (Phdr.p_type != ELF::PT_DYNAMIC || Phdr.p_memsz == 0 || Sec.sh_size != 0)
4312     return true;
4313 
4314   // We get here when we have an empty section. Only non-empty sections can be
4315   // at the start or at the end of PT_DYNAMIC.
4316   // Is section within the phdr both based on offset and VMA?
4317   bool CheckOffset = (Sec.sh_type == ELF::SHT_NOBITS) ||
4318                      (Sec.sh_offset > Phdr.p_offset &&
4319                       Sec.sh_offset < Phdr.p_offset + Phdr.p_filesz);
4320   bool CheckVA = !(Sec.sh_flags & ELF::SHF_ALLOC) ||
4321                  (Sec.sh_addr > Phdr.p_vaddr && Sec.sh_addr < Phdr.p_memsz);
4322   return CheckOffset && CheckVA;
4323 }
4324 
4325 template <class ELFT>
4326 void GNUELFDumper<ELFT>::printProgramHeaders(
4327     bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
4328   if (PrintProgramHeaders)
4329     printProgramHeaders();
4330 
4331   // Display the section mapping along with the program headers, unless
4332   // -section-mapping is explicitly set to false.
4333   if (PrintSectionMapping != cl::BOU_FALSE)
4334     printSectionMapping();
4335 }
4336 
4337 template <class ELFT> void GNUELFDumper<ELFT>::printProgramHeaders() {
4338   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4339   const Elf_Ehdr &Header = this->Obj.getHeader();
4340   Field Fields[8] = {2,         17,        26,        37 + Bias,
4341                      48 + Bias, 56 + Bias, 64 + Bias, 68 + Bias};
4342   OS << "\nElf file type is "
4343      << printEnum(Header.e_type, makeArrayRef(ElfObjectFileType)) << "\n"
4344      << "Entry point " << format_hex(Header.e_entry, 3) << "\n"
4345      << "There are " << Header.e_phnum << " program headers,"
4346      << " starting at offset " << Header.e_phoff << "\n\n"
4347      << "Program Headers:\n";
4348   if (ELFT::Is64Bits)
4349     OS << "  Type           Offset   VirtAddr           PhysAddr         "
4350        << "  FileSiz  MemSiz   Flg Align\n";
4351   else
4352     OS << "  Type           Offset   VirtAddr   PhysAddr   FileSiz "
4353        << "MemSiz  Flg Align\n";
4354 
4355   unsigned Width = ELFT::Is64Bits ? 18 : 10;
4356   unsigned SizeWidth = ELFT::Is64Bits ? 8 : 7;
4357 
4358   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4359   if (!PhdrsOrErr) {
4360     this->reportUniqueWarning("unable to dump program headers: " +
4361                               toString(PhdrsOrErr.takeError()));
4362     return;
4363   }
4364 
4365   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4366     Fields[0].Str = getGNUPtType(Header.e_machine, Phdr.p_type);
4367     Fields[1].Str = to_string(format_hex(Phdr.p_offset, 8));
4368     Fields[2].Str = to_string(format_hex(Phdr.p_vaddr, Width));
4369     Fields[3].Str = to_string(format_hex(Phdr.p_paddr, Width));
4370     Fields[4].Str = to_string(format_hex(Phdr.p_filesz, SizeWidth));
4371     Fields[5].Str = to_string(format_hex(Phdr.p_memsz, SizeWidth));
4372     Fields[6].Str = printPhdrFlags(Phdr.p_flags);
4373     Fields[7].Str = to_string(format_hex(Phdr.p_align, 1));
4374     for (const Field &F : Fields)
4375       printField(F);
4376     if (Phdr.p_type == ELF::PT_INTERP) {
4377       OS << "\n";
4378       auto ReportBadInterp = [&](const Twine &Msg) {
4379         this->reportUniqueWarning(
4380             "unable to read program interpreter name at offset 0x" +
4381             Twine::utohexstr(Phdr.p_offset) + ": " + Msg);
4382       };
4383 
4384       if (Phdr.p_offset >= this->Obj.getBufSize()) {
4385         ReportBadInterp("it goes past the end of the file (0x" +
4386                         Twine::utohexstr(this->Obj.getBufSize()) + ")");
4387         continue;
4388       }
4389 
4390       const char *Data =
4391           reinterpret_cast<const char *>(this->Obj.base()) + Phdr.p_offset;
4392       size_t MaxSize = this->Obj.getBufSize() - Phdr.p_offset;
4393       size_t Len = strnlen(Data, MaxSize);
4394       if (Len == MaxSize) {
4395         ReportBadInterp("it is not null-terminated");
4396         continue;
4397       }
4398 
4399       OS << "      [Requesting program interpreter: ";
4400       OS << StringRef(Data, Len) << "]";
4401     }
4402     OS << "\n";
4403   }
4404 }
4405 
4406 template <class ELFT> void GNUELFDumper<ELFT>::printSectionMapping() {
4407   OS << "\n Section to Segment mapping:\n  Segment Sections...\n";
4408   DenseSet<const Elf_Shdr *> BelongsToSegment;
4409   int Phnum = 0;
4410 
4411   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4412   if (!PhdrsOrErr) {
4413     this->reportUniqueWarning(
4414         "can't read program headers to build section to segment mapping: " +
4415         toString(PhdrsOrErr.takeError()));
4416     return;
4417   }
4418 
4419   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4420     std::string Sections;
4421     OS << format("   %2.2d     ", Phnum++);
4422     // Check if each section is in a segment and then print mapping.
4423     for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4424       if (Sec.sh_type == ELF::SHT_NULL)
4425         continue;
4426 
4427       // readelf additionally makes sure it does not print zero sized sections
4428       // at end of segments and for PT_DYNAMIC both start and end of section
4429       // .tbss must only be shown in PT_TLS section.
4430       if (checkTLSSections<ELFT>(Phdr, Sec) && checkOffsets<ELFT>(Phdr, Sec) &&
4431           checkVMA<ELFT>(Phdr, Sec) && checkPTDynamic<ELFT>(Phdr, Sec)) {
4432         Sections +=
4433             unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4434             " ";
4435         BelongsToSegment.insert(&Sec);
4436       }
4437     }
4438     OS << Sections << "\n";
4439     OS.flush();
4440   }
4441 
4442   // Display sections that do not belong to a segment.
4443   std::string Sections;
4444   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4445     if (BelongsToSegment.find(&Sec) == BelongsToSegment.end())
4446       Sections +=
4447           unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4448           ' ';
4449   }
4450   if (!Sections.empty()) {
4451     OS << "   None  " << Sections << '\n';
4452     OS.flush();
4453   }
4454 }
4455 
4456 namespace {
4457 
4458 template <class ELFT>
4459 RelSymbol<ELFT> getSymbolForReloc(const ELFDumper<ELFT> &Dumper,
4460                                   const Relocation<ELFT> &Reloc) {
4461   using Elf_Sym = typename ELFT::Sym;
4462   auto WarnAndReturn = [&](const Elf_Sym *Sym,
4463                            const Twine &Reason) -> RelSymbol<ELFT> {
4464     Dumper.reportUniqueWarning(
4465         "unable to get name of the dynamic symbol with index " +
4466         Twine(Reloc.Symbol) + ": " + Reason);
4467     return {Sym, "<corrupt>"};
4468   };
4469 
4470   ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols();
4471   const Elf_Sym *FirstSym = Symbols.begin();
4472   if (!FirstSym)
4473     return WarnAndReturn(nullptr, "no dynamic symbol table found");
4474 
4475   // We might have an object without a section header. In this case the size of
4476   // Symbols is zero, because there is no way to know the size of the dynamic
4477   // table. We should allow this case and not print a warning.
4478   if (!Symbols.empty() && Reloc.Symbol >= Symbols.size())
4479     return WarnAndReturn(
4480         nullptr,
4481         "index is greater than or equal to the number of dynamic symbols (" +
4482             Twine(Symbols.size()) + ")");
4483 
4484   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
4485   const uint64_t FileSize = Obj.getBufSize();
4486   const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) +
4487                              (uint64_t)Reloc.Symbol * sizeof(Elf_Sym);
4488   if (SymOffset + sizeof(Elf_Sym) > FileSize)
4489     return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(SymOffset) +
4490                                       " goes past the end of the file (0x" +
4491                                       Twine::utohexstr(FileSize) + ")");
4492 
4493   const Elf_Sym *Sym = FirstSym + Reloc.Symbol;
4494   Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable());
4495   if (!ErrOrName)
4496     return WarnAndReturn(Sym, toString(ErrOrName.takeError()));
4497 
4498   return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(*ErrOrName)};
4499 }
4500 } // namespace
4501 
4502 template <class ELFT>
4503 static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj,
4504                                    typename ELFT::DynRange Tags) {
4505   size_t Max = 0;
4506   for (const typename ELFT::Dyn &Dyn : Tags)
4507     Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size());
4508   return Max;
4509 }
4510 
4511 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicTable() {
4512   Elf_Dyn_Range Table = this->dynamic_table();
4513   if (Table.empty())
4514     return;
4515 
4516   OS << "Dynamic section at offset "
4517      << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable.Addr) -
4518                        this->Obj.base(),
4519                    1)
4520      << " contains " << Table.size() << " entries:\n";
4521 
4522   // The type name is surrounded with round brackets, hence add 2.
4523   size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2;
4524   // The "Name/Value" column should be indented from the "Type" column by N
4525   // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
4526   // space (1) = 3.
4527   OS << "  Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type"
4528      << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
4529 
4530   std::string ValueFmt = " %-" + std::to_string(MaxTagSize) + "s ";
4531   for (auto Entry : Table) {
4532     uintX_t Tag = Entry.getTag();
4533     std::string Type =
4534         std::string("(") + this->Obj.getDynamicTagAsString(Tag).c_str() + ")";
4535     std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
4536     OS << "  " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10)
4537        << format(ValueFmt.c_str(), Type.c_str()) << Value << "\n";
4538   }
4539 }
4540 
4541 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicRelocations() {
4542   this->printDynamicRelocationsHelper();
4543 }
4544 
4545 template <class ELFT>
4546 void ELFDumper<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) {
4547   printRelRelaReloc(R, getSymbolForReloc(*this, R));
4548 }
4549 
4550 template <class ELFT>
4551 void ELFDumper<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) {
4552   this->forEachRelocationDo(
4553       Sec, opts::RawRelr,
4554       [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
4555           const Elf_Shdr *SymTab) { printReloc(R, Ndx, Sec, SymTab); },
4556       [&](const Elf_Relr &R) { printRelrReloc(R); });
4557 }
4558 
4559 template <class ELFT> void ELFDumper<ELFT>::printDynamicRelocationsHelper() {
4560   const bool IsMips64EL = this->Obj.isMips64EL();
4561   if (this->DynRelaRegion.Size > 0) {
4562     printDynamicRelocHeader(ELF::SHT_RELA, "RELA", this->DynRelaRegion);
4563     for (const Elf_Rela &Rela :
4564          this->DynRelaRegion.template getAsArrayRef<Elf_Rela>())
4565       printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
4566   }
4567 
4568   if (this->DynRelRegion.Size > 0) {
4569     printDynamicRelocHeader(ELF::SHT_REL, "REL", this->DynRelRegion);
4570     for (const Elf_Rel &Rel :
4571          this->DynRelRegion.template getAsArrayRef<Elf_Rel>())
4572       printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4573   }
4574 
4575   if (this->DynRelrRegion.Size > 0) {
4576     printDynamicRelocHeader(ELF::SHT_REL, "RELR", this->DynRelrRegion);
4577     Elf_Relr_Range Relrs =
4578         this->DynRelrRegion.template getAsArrayRef<Elf_Relr>();
4579     for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs))
4580       printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4581   }
4582 
4583   if (this->DynPLTRelRegion.Size) {
4584     if (this->DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) {
4585       printDynamicRelocHeader(ELF::SHT_RELA, "PLT", this->DynPLTRelRegion);
4586       for (const Elf_Rela &Rela :
4587            this->DynPLTRelRegion.template getAsArrayRef<Elf_Rela>())
4588         printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
4589     } else {
4590       printDynamicRelocHeader(ELF::SHT_REL, "PLT", this->DynPLTRelRegion);
4591       for (const Elf_Rel &Rel :
4592            this->DynPLTRelRegion.template getAsArrayRef<Elf_Rel>())
4593         printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4594     }
4595   }
4596 }
4597 
4598 template <class ELFT>
4599 void GNUELFDumper<ELFT>::printGNUVersionSectionProlog(
4600     const typename ELFT::Shdr &Sec, const Twine &Label, unsigned EntriesNum) {
4601   // Don't inline the SecName, because it might report a warning to stderr and
4602   // corrupt the output.
4603   StringRef SecName = this->getPrintableSectionName(Sec);
4604   OS << Label << " section '" << SecName << "' "
4605      << "contains " << EntriesNum << " entries:\n";
4606 
4607   StringRef LinkedSecName = "<corrupt>";
4608   if (Expected<const typename ELFT::Shdr *> LinkedSecOrErr =
4609           this->Obj.getSection(Sec.sh_link))
4610     LinkedSecName = this->getPrintableSectionName(**LinkedSecOrErr);
4611   else
4612     this->reportUniqueWarning("invalid section linked to " +
4613                               this->describe(Sec) + ": " +
4614                               toString(LinkedSecOrErr.takeError()));
4615 
4616   OS << " Addr: " << format_hex_no_prefix(Sec.sh_addr, 16)
4617      << "  Offset: " << format_hex(Sec.sh_offset, 8)
4618      << "  Link: " << Sec.sh_link << " (" << LinkedSecName << ")\n";
4619 }
4620 
4621 template <class ELFT>
4622 void GNUELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
4623   if (!Sec)
4624     return;
4625 
4626   printGNUVersionSectionProlog(*Sec, "Version symbols",
4627                                Sec->sh_size / sizeof(Elf_Versym));
4628   Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
4629       this->getVersionTable(*Sec, /*SymTab=*/nullptr,
4630                             /*StrTab=*/nullptr, /*SymTabSec=*/nullptr);
4631   if (!VerTableOrErr) {
4632     this->reportUniqueWarning(VerTableOrErr.takeError());
4633     return;
4634   }
4635 
4636   ArrayRef<Elf_Versym> VerTable = *VerTableOrErr;
4637   std::vector<StringRef> Versions;
4638   for (size_t I = 0, E = VerTable.size(); I < E; ++I) {
4639     unsigned Ndx = VerTable[I].vs_index;
4640     if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) {
4641       Versions.emplace_back(Ndx == VER_NDX_LOCAL ? "*local*" : "*global*");
4642       continue;
4643     }
4644 
4645     bool IsDefault;
4646     Expected<StringRef> NameOrErr =
4647         this->getSymbolVersionByIndex(Ndx, IsDefault);
4648     if (!NameOrErr) {
4649       this->reportUniqueWarning("unable to get a version for entry " +
4650                                 Twine(I) + " of " + this->describe(*Sec) +
4651                                 ": " + toString(NameOrErr.takeError()));
4652       Versions.emplace_back("<corrupt>");
4653       continue;
4654     }
4655     Versions.emplace_back(*NameOrErr);
4656   }
4657 
4658   // readelf prints 4 entries per line.
4659   uint64_t Entries = VerTable.size();
4660   for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) {
4661     OS << "  " << format_hex_no_prefix(VersymRow, 3) << ":";
4662     for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) {
4663       unsigned Ndx = VerTable[VersymRow + I].vs_index;
4664       OS << format("%4x%c", Ndx & VERSYM_VERSION,
4665                    Ndx & VERSYM_HIDDEN ? 'h' : ' ');
4666       OS << left_justify("(" + std::string(Versions[VersymRow + I]) + ")", 13);
4667     }
4668     OS << '\n';
4669   }
4670   OS << '\n';
4671 }
4672 
4673 static std::string versionFlagToString(unsigned Flags) {
4674   if (Flags == 0)
4675     return "none";
4676 
4677   std::string Ret;
4678   auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) {
4679     if (!(Flags & Flag))
4680       return;
4681     if (!Ret.empty())
4682       Ret += " | ";
4683     Ret += Name;
4684     Flags &= ~Flag;
4685   };
4686 
4687   AddFlag(VER_FLG_BASE, "BASE");
4688   AddFlag(VER_FLG_WEAK, "WEAK");
4689   AddFlag(VER_FLG_INFO, "INFO");
4690   AddFlag(~0, "<unknown>");
4691   return Ret;
4692 }
4693 
4694 template <class ELFT>
4695 void GNUELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
4696   if (!Sec)
4697     return;
4698 
4699   printGNUVersionSectionProlog(*Sec, "Version definition", Sec->sh_info);
4700 
4701   Expected<std::vector<VerDef>> V = this->getVersionDefinitions(*Sec);
4702   if (!V) {
4703     this->reportUniqueWarning(V.takeError());
4704     return;
4705   }
4706 
4707   for (const VerDef &Def : *V) {
4708     OS << format("  0x%04x: Rev: %u  Flags: %s  Index: %u  Cnt: %u  Name: %s\n",
4709                  Def.Offset, Def.Version,
4710                  versionFlagToString(Def.Flags).c_str(), Def.Ndx, Def.Cnt,
4711                  Def.Name.data());
4712     unsigned I = 0;
4713     for (const VerdAux &Aux : Def.AuxV)
4714       OS << format("  0x%04x: Parent %u: %s\n", Aux.Offset, ++I,
4715                    Aux.Name.data());
4716   }
4717 
4718   OS << '\n';
4719 }
4720 
4721 template <class ELFT>
4722 void GNUELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
4723   if (!Sec)
4724     return;
4725 
4726   unsigned VerneedNum = Sec->sh_info;
4727   printGNUVersionSectionProlog(*Sec, "Version needs", VerneedNum);
4728 
4729   Expected<std::vector<VerNeed>> V = this->getVersionDependencies(*Sec);
4730   if (!V) {
4731     this->reportUniqueWarning(V.takeError());
4732     return;
4733   }
4734 
4735   for (const VerNeed &VN : *V) {
4736     OS << format("  0x%04x: Version: %u  File: %s  Cnt: %u\n", VN.Offset,
4737                  VN.Version, VN.File.data(), VN.Cnt);
4738     for (const VernAux &Aux : VN.AuxV)
4739       OS << format("  0x%04x:   Name: %s  Flags: %s  Version: %u\n", Aux.Offset,
4740                    Aux.Name.data(), versionFlagToString(Aux.Flags).c_str(),
4741                    Aux.Other);
4742   }
4743   OS << '\n';
4744 }
4745 
4746 template <class ELFT>
4747 void GNUELFDumper<ELFT>::printHashHistogram(const Elf_Hash &HashTable) {
4748   size_t NBucket = HashTable.nbucket;
4749   size_t NChain = HashTable.nchain;
4750   ArrayRef<Elf_Word> Buckets = HashTable.buckets();
4751   ArrayRef<Elf_Word> Chains = HashTable.chains();
4752   size_t TotalSyms = 0;
4753   // If hash table is correct, we have at least chains with 0 length
4754   size_t MaxChain = 1;
4755   size_t CumulativeNonZero = 0;
4756 
4757   if (NChain == 0 || NBucket == 0)
4758     return;
4759 
4760   std::vector<size_t> ChainLen(NBucket, 0);
4761   // Go over all buckets and and note chain lengths of each bucket (total
4762   // unique chain lengths).
4763   for (size_t B = 0; B < NBucket; B++) {
4764     std::vector<bool> Visited(NChain);
4765     for (size_t C = Buckets[B]; C < NChain; C = Chains[C]) {
4766       if (C == ELF::STN_UNDEF)
4767         break;
4768       if (Visited[C]) {
4769         this->reportUniqueWarning(".hash section is invalid: bucket " +
4770                                   Twine(C) +
4771                                   ": a cycle was detected in the linked chain");
4772         break;
4773       }
4774       Visited[C] = true;
4775       if (MaxChain <= ++ChainLen[B])
4776         MaxChain++;
4777     }
4778     TotalSyms += ChainLen[B];
4779   }
4780 
4781   if (!TotalSyms)
4782     return;
4783 
4784   std::vector<size_t> Count(MaxChain, 0);
4785   // Count how long is the chain for each bucket
4786   for (size_t B = 0; B < NBucket; B++)
4787     ++Count[ChainLen[B]];
4788   // Print Number of buckets with each chain lengths and their cumulative
4789   // coverage of the symbols
4790   OS << "Histogram for bucket list length (total of " << NBucket
4791      << " buckets)\n"
4792      << " Length  Number     % of total  Coverage\n";
4793   for (size_t I = 0; I < MaxChain; I++) {
4794     CumulativeNonZero += Count[I] * I;
4795     OS << format("%7lu  %-10lu (%5.1f%%)     %5.1f%%\n", I, Count[I],
4796                  (Count[I] * 100.0) / NBucket,
4797                  (CumulativeNonZero * 100.0) / TotalSyms);
4798   }
4799 }
4800 
4801 template <class ELFT>
4802 void GNUELFDumper<ELFT>::printGnuHashHistogram(
4803     const Elf_GnuHash &GnuHashTable) {
4804   Expected<ArrayRef<Elf_Word>> ChainsOrErr =
4805       getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHashTable);
4806   if (!ChainsOrErr) {
4807     this->reportUniqueWarning("unable to print the GNU hash table histogram: " +
4808                               toString(ChainsOrErr.takeError()));
4809     return;
4810   }
4811 
4812   ArrayRef<Elf_Word> Chains = *ChainsOrErr;
4813   size_t Symndx = GnuHashTable.symndx;
4814   size_t TotalSyms = 0;
4815   size_t MaxChain = 1;
4816   size_t CumulativeNonZero = 0;
4817 
4818   size_t NBucket = GnuHashTable.nbuckets;
4819   if (Chains.empty() || NBucket == 0)
4820     return;
4821 
4822   ArrayRef<Elf_Word> Buckets = GnuHashTable.buckets();
4823   std::vector<size_t> ChainLen(NBucket, 0);
4824   for (size_t B = 0; B < NBucket; B++) {
4825     if (!Buckets[B])
4826       continue;
4827     size_t Len = 1;
4828     for (size_t C = Buckets[B] - Symndx;
4829          C < Chains.size() && (Chains[C] & 1) == 0; C++)
4830       if (MaxChain < ++Len)
4831         MaxChain++;
4832     ChainLen[B] = Len;
4833     TotalSyms += Len;
4834   }
4835   MaxChain++;
4836 
4837   if (!TotalSyms)
4838     return;
4839 
4840   std::vector<size_t> Count(MaxChain, 0);
4841   for (size_t B = 0; B < NBucket; B++)
4842     ++Count[ChainLen[B]];
4843   // Print Number of buckets with each chain lengths and their cumulative
4844   // coverage of the symbols
4845   OS << "Histogram for `.gnu.hash' bucket list length (total of " << NBucket
4846      << " buckets)\n"
4847      << " Length  Number     % of total  Coverage\n";
4848   for (size_t I = 0; I < MaxChain; I++) {
4849     CumulativeNonZero += Count[I] * I;
4850     OS << format("%7lu  %-10lu (%5.1f%%)     %5.1f%%\n", I, Count[I],
4851                  (Count[I] * 100.0) / NBucket,
4852                  (CumulativeNonZero * 100.0) / TotalSyms);
4853   }
4854 }
4855 
4856 // Hash histogram shows statistics of how efficient the hash was for the
4857 // dynamic symbol table. The table shows the number of hash buckets for
4858 // different lengths of chains as an absolute number and percentage of the total
4859 // buckets, and the cumulative coverage of symbols for each set of buckets.
4860 template <class ELFT> void GNUELFDumper<ELFT>::printHashHistograms() {
4861   // Print histogram for the .hash section.
4862   if (this->HashTable) {
4863     if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
4864       this->reportUniqueWarning(std::move(E));
4865     else
4866       printHashHistogram(*this->HashTable);
4867   }
4868 
4869   // Print histogram for the .gnu.hash section.
4870   if (this->GnuHashTable) {
4871     if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
4872       this->reportUniqueWarning(std::move(E));
4873     else
4874       printGnuHashHistogram(*this->GnuHashTable);
4875   }
4876 }
4877 
4878 template <class ELFT> void GNUELFDumper<ELFT>::printCGProfile() {
4879   OS << "GNUStyle::printCGProfile not implemented\n";
4880 }
4881 
4882 static Expected<std::vector<uint64_t>> toULEB128Array(ArrayRef<uint8_t> Data) {
4883   std::vector<uint64_t> Ret;
4884   const uint8_t *Cur = Data.begin();
4885   const uint8_t *End = Data.end();
4886   while (Cur != End) {
4887     unsigned Size;
4888     const char *Err;
4889     Ret.push_back(decodeULEB128(Cur, &Size, End, &Err));
4890     if (Err)
4891       return createError(Err);
4892     Cur += Size;
4893   }
4894   return Ret;
4895 }
4896 
4897 template <class ELFT>
4898 static Expected<std::vector<uint64_t>>
4899 decodeAddrsigSection(const ELFFile<ELFT> &Obj, const typename ELFT::Shdr &Sec) {
4900   Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Sec);
4901   if (!ContentsOrErr)
4902     return ContentsOrErr.takeError();
4903 
4904   if (Expected<std::vector<uint64_t>> SymsOrErr =
4905           toULEB128Array(*ContentsOrErr))
4906     return *SymsOrErr;
4907   else
4908     return createError("unable to decode " + describe(Obj, Sec) + ": " +
4909                        toString(SymsOrErr.takeError()));
4910 }
4911 
4912 template <class ELFT> void GNUELFDumper<ELFT>::printAddrsig() {
4913   if (!this->DotAddrsigSec)
4914     return;
4915 
4916   Expected<std::vector<uint64_t>> SymsOrErr =
4917       decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
4918   if (!SymsOrErr) {
4919     this->reportUniqueWarning(SymsOrErr.takeError());
4920     return;
4921   }
4922 
4923   StringRef Name = this->getPrintableSectionName(*this->DotAddrsigSec);
4924   OS << "\nAddress-significant symbols section '" << Name << "'"
4925      << " contains " << SymsOrErr->size() << " entries:\n";
4926   OS << "   Num: Name\n";
4927 
4928   Field Fields[2] = {0, 8};
4929   size_t SymIndex = 0;
4930   for (uint64_t Sym : *SymsOrErr) {
4931     Fields[0].Str = to_string(format_decimal(++SymIndex, 6)) + ":";
4932     Fields[1].Str = this->getStaticSymbolName(Sym);
4933     for (const Field &Entry : Fields)
4934       printField(Entry);
4935     OS << "\n";
4936   }
4937 }
4938 
4939 template <typename ELFT>
4940 static std::string getGNUProperty(uint32_t Type, uint32_t DataSize,
4941                                   ArrayRef<uint8_t> Data) {
4942   std::string str;
4943   raw_string_ostream OS(str);
4944   uint32_t PrData;
4945   auto DumpBit = [&](uint32_t Flag, StringRef Name) {
4946     if (PrData & Flag) {
4947       PrData &= ~Flag;
4948       OS << Name;
4949       if (PrData)
4950         OS << ", ";
4951     }
4952   };
4953 
4954   switch (Type) {
4955   default:
4956     OS << format("<application-specific type 0x%x>", Type);
4957     return OS.str();
4958   case GNU_PROPERTY_STACK_SIZE: {
4959     OS << "stack size: ";
4960     if (DataSize == sizeof(typename ELFT::uint))
4961       OS << formatv("{0:x}",
4962                     (uint64_t)(*(const typename ELFT::Addr *)Data.data()));
4963     else
4964       OS << format("<corrupt length: 0x%x>", DataSize);
4965     return OS.str();
4966   }
4967   case GNU_PROPERTY_NO_COPY_ON_PROTECTED:
4968     OS << "no copy on protected";
4969     if (DataSize)
4970       OS << format(" <corrupt length: 0x%x>", DataSize);
4971     return OS.str();
4972   case GNU_PROPERTY_AARCH64_FEATURE_1_AND:
4973   case GNU_PROPERTY_X86_FEATURE_1_AND:
4974     OS << ((Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) ? "aarch64 feature: "
4975                                                         : "x86 feature: ");
4976     if (DataSize != 4) {
4977       OS << format("<corrupt length: 0x%x>", DataSize);
4978       return OS.str();
4979     }
4980     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
4981     if (PrData == 0) {
4982       OS << "<None>";
4983       return OS.str();
4984     }
4985     if (Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) {
4986       DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI, "BTI");
4987       DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC, "PAC");
4988     } else {
4989       DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT, "IBT");
4990       DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK, "SHSTK");
4991     }
4992     if (PrData)
4993       OS << format("<unknown flags: 0x%x>", PrData);
4994     return OS.str();
4995   case GNU_PROPERTY_X86_ISA_1_NEEDED:
4996   case GNU_PROPERTY_X86_ISA_1_USED:
4997     OS << "x86 ISA "
4998        << (Type == GNU_PROPERTY_X86_ISA_1_NEEDED ? "needed: " : "used: ");
4999     if (DataSize != 4) {
5000       OS << format("<corrupt length: 0x%x>", DataSize);
5001       return OS.str();
5002     }
5003     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
5004     if (PrData == 0) {
5005       OS << "<None>";
5006       return OS.str();
5007     }
5008     DumpBit(GNU_PROPERTY_X86_ISA_1_CMOV, "CMOV");
5009     DumpBit(GNU_PROPERTY_X86_ISA_1_SSE, "SSE");
5010     DumpBit(GNU_PROPERTY_X86_ISA_1_SSE2, "SSE2");
5011     DumpBit(GNU_PROPERTY_X86_ISA_1_SSE3, "SSE3");
5012     DumpBit(GNU_PROPERTY_X86_ISA_1_SSSE3, "SSSE3");
5013     DumpBit(GNU_PROPERTY_X86_ISA_1_SSE4_1, "SSE4_1");
5014     DumpBit(GNU_PROPERTY_X86_ISA_1_SSE4_2, "SSE4_2");
5015     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX, "AVX");
5016     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX2, "AVX2");
5017     DumpBit(GNU_PROPERTY_X86_ISA_1_FMA, "FMA");
5018     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512F, "AVX512F");
5019     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512CD, "AVX512CD");
5020     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512ER, "AVX512ER");
5021     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512PF, "AVX512PF");
5022     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512VL, "AVX512VL");
5023     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512DQ, "AVX512DQ");
5024     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512BW, "AVX512BW");
5025     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_4FMAPS, "AVX512_4FMAPS");
5026     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_4VNNIW, "AVX512_4VNNIW");
5027     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_BITALG, "AVX512_BITALG");
5028     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_IFMA, "AVX512_IFMA");
5029     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_VBMI, "AVX512_VBMI");
5030     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_VBMI2, "AVX512_VBMI2");
5031     DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_VNNI, "AVX512_VNNI");
5032     if (PrData)
5033       OS << format("<unknown flags: 0x%x>", PrData);
5034     return OS.str();
5035     break;
5036   case GNU_PROPERTY_X86_FEATURE_2_NEEDED:
5037   case GNU_PROPERTY_X86_FEATURE_2_USED:
5038     OS << "x86 feature "
5039        << (Type == GNU_PROPERTY_X86_FEATURE_2_NEEDED ? "needed: " : "used: ");
5040     if (DataSize != 4) {
5041       OS << format("<corrupt length: 0x%x>", DataSize);
5042       return OS.str();
5043     }
5044     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
5045     if (PrData == 0) {
5046       OS << "<None>";
5047       return OS.str();
5048     }
5049     DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86, "x86");
5050     DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87, "x87");
5051     DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX, "MMX");
5052     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM, "XMM");
5053     DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM, "YMM");
5054     DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM, "ZMM");
5055     DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR, "FXSR");
5056     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE, "XSAVE");
5057     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT, "XSAVEOPT");
5058     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC, "XSAVEC");
5059     if (PrData)
5060       OS << format("<unknown flags: 0x%x>", PrData);
5061     return OS.str();
5062   }
5063 }
5064 
5065 template <typename ELFT>
5066 static SmallVector<std::string, 4> getGNUPropertyList(ArrayRef<uint8_t> Arr) {
5067   using Elf_Word = typename ELFT::Word;
5068 
5069   SmallVector<std::string, 4> Properties;
5070   while (Arr.size() >= 8) {
5071     uint32_t Type = *reinterpret_cast<const Elf_Word *>(Arr.data());
5072     uint32_t DataSize = *reinterpret_cast<const Elf_Word *>(Arr.data() + 4);
5073     Arr = Arr.drop_front(8);
5074 
5075     // Take padding size into account if present.
5076     uint64_t PaddedSize = alignTo(DataSize, sizeof(typename ELFT::uint));
5077     std::string str;
5078     raw_string_ostream OS(str);
5079     if (Arr.size() < PaddedSize) {
5080       OS << format("<corrupt type (0x%x) datasz: 0x%x>", Type, DataSize);
5081       Properties.push_back(OS.str());
5082       break;
5083     }
5084     Properties.push_back(
5085         getGNUProperty<ELFT>(Type, DataSize, Arr.take_front(PaddedSize)));
5086     Arr = Arr.drop_front(PaddedSize);
5087   }
5088 
5089   if (!Arr.empty())
5090     Properties.push_back("<corrupted GNU_PROPERTY_TYPE_0>");
5091 
5092   return Properties;
5093 }
5094 
5095 struct GNUAbiTag {
5096   std::string OSName;
5097   std::string ABI;
5098   bool IsValid;
5099 };
5100 
5101 template <typename ELFT> static GNUAbiTag getGNUAbiTag(ArrayRef<uint8_t> Desc) {
5102   typedef typename ELFT::Word Elf_Word;
5103 
5104   ArrayRef<Elf_Word> Words(reinterpret_cast<const Elf_Word *>(Desc.begin()),
5105                            reinterpret_cast<const Elf_Word *>(Desc.end()));
5106 
5107   if (Words.size() < 4)
5108     return {"", "", /*IsValid=*/false};
5109 
5110   static const char *OSNames[] = {
5111       "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable", "NaCl",
5112   };
5113   StringRef OSName = "Unknown";
5114   if (Words[0] < array_lengthof(OSNames))
5115     OSName = OSNames[Words[0]];
5116   uint32_t Major = Words[1], Minor = Words[2], Patch = Words[3];
5117   std::string str;
5118   raw_string_ostream ABI(str);
5119   ABI << Major << "." << Minor << "." << Patch;
5120   return {std::string(OSName), ABI.str(), /*IsValid=*/true};
5121 }
5122 
5123 static std::string getGNUBuildId(ArrayRef<uint8_t> Desc) {
5124   std::string str;
5125   raw_string_ostream OS(str);
5126   for (uint8_t B : Desc)
5127     OS << format_hex_no_prefix(B, 2);
5128   return OS.str();
5129 }
5130 
5131 static StringRef getGNUGoldVersion(ArrayRef<uint8_t> Desc) {
5132   return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
5133 }
5134 
5135 template <typename ELFT>
5136 static void printGNUNote(raw_ostream &OS, uint32_t NoteType,
5137                          ArrayRef<uint8_t> Desc) {
5138   switch (NoteType) {
5139   default:
5140     return;
5141   case ELF::NT_GNU_ABI_TAG: {
5142     const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
5143     if (!AbiTag.IsValid)
5144       OS << "    <corrupt GNU_ABI_TAG>";
5145     else
5146       OS << "    OS: " << AbiTag.OSName << ", ABI: " << AbiTag.ABI;
5147     break;
5148   }
5149   case ELF::NT_GNU_BUILD_ID: {
5150     OS << "    Build ID: " << getGNUBuildId(Desc);
5151     break;
5152   }
5153   case ELF::NT_GNU_GOLD_VERSION:
5154     OS << "    Version: " << getGNUGoldVersion(Desc);
5155     break;
5156   case ELF::NT_GNU_PROPERTY_TYPE_0:
5157     OS << "    Properties:";
5158     for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
5159       OS << "    " << Property << "\n";
5160     break;
5161   }
5162   OS << '\n';
5163 }
5164 
5165 struct AMDNote {
5166   std::string Type;
5167   std::string Value;
5168 };
5169 
5170 template <typename ELFT>
5171 static AMDNote getAMDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
5172   switch (NoteType) {
5173   default:
5174     return {"", ""};
5175   case ELF::NT_AMD_AMDGPU_HSA_METADATA:
5176     return {
5177         "HSA Metadata",
5178         std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
5179   case ELF::NT_AMD_AMDGPU_ISA:
5180     return {
5181         "ISA Version",
5182         std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
5183   }
5184 }
5185 
5186 struct AMDGPUNote {
5187   std::string Type;
5188   std::string Value;
5189 };
5190 
5191 template <typename ELFT>
5192 static AMDGPUNote getAMDGPUNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
5193   switch (NoteType) {
5194   default:
5195     return {"", ""};
5196   case ELF::NT_AMDGPU_METADATA: {
5197     StringRef MsgPackString =
5198         StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
5199     msgpack::Document MsgPackDoc;
5200     if (!MsgPackDoc.readFromBlob(MsgPackString, /*Multi=*/false))
5201       return {"AMDGPU Metadata", "Invalid AMDGPU Metadata"};
5202 
5203     AMDGPU::HSAMD::V3::MetadataVerifier Verifier(true);
5204     std::string HSAMetadataString;
5205     if (!Verifier.verify(MsgPackDoc.getRoot()))
5206       HSAMetadataString = "Invalid AMDGPU Metadata\n";
5207 
5208     raw_string_ostream StrOS(HSAMetadataString);
5209     MsgPackDoc.toYAML(StrOS);
5210 
5211     return {"AMDGPU Metadata", StrOS.str()};
5212   }
5213   }
5214 }
5215 
5216 struct CoreFileMapping {
5217   uint64_t Start, End, Offset;
5218   StringRef Filename;
5219 };
5220 
5221 struct CoreNote {
5222   uint64_t PageSize;
5223   std::vector<CoreFileMapping> Mappings;
5224 };
5225 
5226 static Expected<CoreNote> readCoreNote(DataExtractor Desc) {
5227   // Expected format of the NT_FILE note description:
5228   // 1. # of file mappings (call it N)
5229   // 2. Page size
5230   // 3. N (start, end, offset) triples
5231   // 4. N packed filenames (null delimited)
5232   // Each field is an Elf_Addr, except for filenames which are char* strings.
5233 
5234   CoreNote Ret;
5235   const int Bytes = Desc.getAddressSize();
5236 
5237   if (!Desc.isValidOffsetForAddress(2))
5238     return createError("the note of size 0x" + Twine::utohexstr(Desc.size()) +
5239                        " is too short, expected at least 0x" +
5240                        Twine::utohexstr(Bytes * 2));
5241   if (Desc.getData().back() != 0)
5242     return createError("the note is not NUL terminated");
5243 
5244   uint64_t DescOffset = 0;
5245   uint64_t FileCount = Desc.getAddress(&DescOffset);
5246   Ret.PageSize = Desc.getAddress(&DescOffset);
5247 
5248   if (!Desc.isValidOffsetForAddress(3 * FileCount * Bytes))
5249     return createError("unable to read file mappings (found " +
5250                        Twine(FileCount) + "): the note of size 0x" +
5251                        Twine::utohexstr(Desc.size()) + " is too short");
5252 
5253   uint64_t FilenamesOffset = 0;
5254   DataExtractor Filenames(
5255       Desc.getData().drop_front(DescOffset + 3 * FileCount * Bytes),
5256       Desc.isLittleEndian(), Desc.getAddressSize());
5257 
5258   Ret.Mappings.resize(FileCount);
5259   size_t I = 0;
5260   for (CoreFileMapping &Mapping : Ret.Mappings) {
5261     ++I;
5262     if (!Filenames.isValidOffsetForDataOfSize(FilenamesOffset, 1))
5263       return createError(
5264           "unable to read the file name for the mapping with index " +
5265           Twine(I) + ": the note of size 0x" + Twine::utohexstr(Desc.size()) +
5266           " is truncated");
5267     Mapping.Start = Desc.getAddress(&DescOffset);
5268     Mapping.End = Desc.getAddress(&DescOffset);
5269     Mapping.Offset = Desc.getAddress(&DescOffset);
5270     Mapping.Filename = Filenames.getCStrRef(&FilenamesOffset);
5271   }
5272 
5273   return Ret;
5274 }
5275 
5276 template <typename ELFT>
5277 static void printCoreNote(raw_ostream &OS, const CoreNote &Note) {
5278   // Length of "0x<address>" string.
5279   const int FieldWidth = ELFT::Is64Bits ? 18 : 10;
5280 
5281   OS << "    Page size: " << format_decimal(Note.PageSize, 0) << '\n';
5282   OS << "    " << right_justify("Start", FieldWidth) << "  "
5283      << right_justify("End", FieldWidth) << "  "
5284      << right_justify("Page Offset", FieldWidth) << '\n';
5285   for (const CoreFileMapping &Mapping : Note.Mappings) {
5286     OS << "    " << format_hex(Mapping.Start, FieldWidth) << "  "
5287        << format_hex(Mapping.End, FieldWidth) << "  "
5288        << format_hex(Mapping.Offset, FieldWidth) << "\n        "
5289        << Mapping.Filename << '\n';
5290   }
5291 }
5292 
5293 static const NoteType GenericNoteTypes[] = {
5294     {ELF::NT_VERSION, "NT_VERSION (version)"},
5295     {ELF::NT_ARCH, "NT_ARCH (architecture)"},
5296     {ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN, "OPEN"},
5297     {ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC, "func"},
5298 };
5299 
5300 static const NoteType GNUNoteTypes[] = {
5301     {ELF::NT_GNU_ABI_TAG, "NT_GNU_ABI_TAG (ABI version tag)"},
5302     {ELF::NT_GNU_HWCAP, "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"},
5303     {ELF::NT_GNU_BUILD_ID, "NT_GNU_BUILD_ID (unique build ID bitstring)"},
5304     {ELF::NT_GNU_GOLD_VERSION, "NT_GNU_GOLD_VERSION (gold version)"},
5305     {ELF::NT_GNU_PROPERTY_TYPE_0, "NT_GNU_PROPERTY_TYPE_0 (property note)"},
5306 };
5307 
5308 static const NoteType FreeBSDNoteTypes[] = {
5309     {ELF::NT_FREEBSD_THRMISC, "NT_THRMISC (thrmisc structure)"},
5310     {ELF::NT_FREEBSD_PROCSTAT_PROC, "NT_PROCSTAT_PROC (proc data)"},
5311     {ELF::NT_FREEBSD_PROCSTAT_FILES, "NT_PROCSTAT_FILES (files data)"},
5312     {ELF::NT_FREEBSD_PROCSTAT_VMMAP, "NT_PROCSTAT_VMMAP (vmmap data)"},
5313     {ELF::NT_FREEBSD_PROCSTAT_GROUPS, "NT_PROCSTAT_GROUPS (groups data)"},
5314     {ELF::NT_FREEBSD_PROCSTAT_UMASK, "NT_PROCSTAT_UMASK (umask data)"},
5315     {ELF::NT_FREEBSD_PROCSTAT_RLIMIT, "NT_PROCSTAT_RLIMIT (rlimit data)"},
5316     {ELF::NT_FREEBSD_PROCSTAT_OSREL, "NT_PROCSTAT_OSREL (osreldate data)"},
5317     {ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS,
5318      "NT_PROCSTAT_PSSTRINGS (ps_strings data)"},
5319     {ELF::NT_FREEBSD_PROCSTAT_AUXV, "NT_PROCSTAT_AUXV (auxv data)"},
5320 };
5321 
5322 static const NoteType AMDNoteTypes[] = {
5323     {ELF::NT_AMD_AMDGPU_HSA_METADATA,
5324      "NT_AMD_AMDGPU_HSA_METADATA (HSA Metadata)"},
5325     {ELF::NT_AMD_AMDGPU_ISA, "NT_AMD_AMDGPU_ISA (ISA Version)"},
5326     {ELF::NT_AMD_AMDGPU_PAL_METADATA,
5327      "NT_AMD_AMDGPU_PAL_METADATA (PAL Metadata)"},
5328 };
5329 
5330 static const NoteType AMDGPUNoteTypes[] = {
5331     {ELF::NT_AMDGPU_METADATA, "NT_AMDGPU_METADATA (AMDGPU Metadata)"},
5332 };
5333 
5334 static const NoteType CoreNoteTypes[] = {
5335     {ELF::NT_PRSTATUS, "NT_PRSTATUS (prstatus structure)"},
5336     {ELF::NT_FPREGSET, "NT_FPREGSET (floating point registers)"},
5337     {ELF::NT_PRPSINFO, "NT_PRPSINFO (prpsinfo structure)"},
5338     {ELF::NT_TASKSTRUCT, "NT_TASKSTRUCT (task structure)"},
5339     {ELF::NT_AUXV, "NT_AUXV (auxiliary vector)"},
5340     {ELF::NT_PSTATUS, "NT_PSTATUS (pstatus structure)"},
5341     {ELF::NT_FPREGS, "NT_FPREGS (floating point registers)"},
5342     {ELF::NT_PSINFO, "NT_PSINFO (psinfo structure)"},
5343     {ELF::NT_LWPSTATUS, "NT_LWPSTATUS (lwpstatus_t structure)"},
5344     {ELF::NT_LWPSINFO, "NT_LWPSINFO (lwpsinfo_t structure)"},
5345     {ELF::NT_WIN32PSTATUS, "NT_WIN32PSTATUS (win32_pstatus structure)"},
5346 
5347     {ELF::NT_PPC_VMX, "NT_PPC_VMX (ppc Altivec registers)"},
5348     {ELF::NT_PPC_VSX, "NT_PPC_VSX (ppc VSX registers)"},
5349     {ELF::NT_PPC_TAR, "NT_PPC_TAR (ppc TAR register)"},
5350     {ELF::NT_PPC_PPR, "NT_PPC_PPR (ppc PPR register)"},
5351     {ELF::NT_PPC_DSCR, "NT_PPC_DSCR (ppc DSCR register)"},
5352     {ELF::NT_PPC_EBB, "NT_PPC_EBB (ppc EBB registers)"},
5353     {ELF::NT_PPC_PMU, "NT_PPC_PMU (ppc PMU registers)"},
5354     {ELF::NT_PPC_TM_CGPR, "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"},
5355     {ELF::NT_PPC_TM_CFPR,
5356      "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"},
5357     {ELF::NT_PPC_TM_CVMX,
5358      "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"},
5359     {ELF::NT_PPC_TM_CVSX, "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"},
5360     {ELF::NT_PPC_TM_SPR, "NT_PPC_TM_SPR (ppc TM special purpose registers)"},
5361     {ELF::NT_PPC_TM_CTAR, "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"},
5362     {ELF::NT_PPC_TM_CPPR, "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"},
5363     {ELF::NT_PPC_TM_CDSCR, "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"},
5364 
5365     {ELF::NT_386_TLS, "NT_386_TLS (x86 TLS information)"},
5366     {ELF::NT_386_IOPERM, "NT_386_IOPERM (x86 I/O permissions)"},
5367     {ELF::NT_X86_XSTATE, "NT_X86_XSTATE (x86 XSAVE extended state)"},
5368 
5369     {ELF::NT_S390_HIGH_GPRS, "NT_S390_HIGH_GPRS (s390 upper register halves)"},
5370     {ELF::NT_S390_TIMER, "NT_S390_TIMER (s390 timer register)"},
5371     {ELF::NT_S390_TODCMP, "NT_S390_TODCMP (s390 TOD comparator register)"},
5372     {ELF::NT_S390_TODPREG, "NT_S390_TODPREG (s390 TOD programmable register)"},
5373     {ELF::NT_S390_CTRS, "NT_S390_CTRS (s390 control registers)"},
5374     {ELF::NT_S390_PREFIX, "NT_S390_PREFIX (s390 prefix register)"},
5375     {ELF::NT_S390_LAST_BREAK,
5376      "NT_S390_LAST_BREAK (s390 last breaking event address)"},
5377     {ELF::NT_S390_SYSTEM_CALL,
5378      "NT_S390_SYSTEM_CALL (s390 system call restart data)"},
5379     {ELF::NT_S390_TDB, "NT_S390_TDB (s390 transaction diagnostic block)"},
5380     {ELF::NT_S390_VXRS_LOW,
5381      "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"},
5382     {ELF::NT_S390_VXRS_HIGH, "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"},
5383     {ELF::NT_S390_GS_CB, "NT_S390_GS_CB (s390 guarded-storage registers)"},
5384     {ELF::NT_S390_GS_BC,
5385      "NT_S390_GS_BC (s390 guarded-storage broadcast control)"},
5386 
5387     {ELF::NT_ARM_VFP, "NT_ARM_VFP (arm VFP registers)"},
5388     {ELF::NT_ARM_TLS, "NT_ARM_TLS (AArch TLS registers)"},
5389     {ELF::NT_ARM_HW_BREAK,
5390      "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"},
5391     {ELF::NT_ARM_HW_WATCH,
5392      "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"},
5393 
5394     {ELF::NT_FILE, "NT_FILE (mapped files)"},
5395     {ELF::NT_PRXFPREG, "NT_PRXFPREG (user_xfpregs structure)"},
5396     {ELF::NT_SIGINFO, "NT_SIGINFO (siginfo_t data)"},
5397 };
5398 
5399 template <class ELFT>
5400 const StringRef getNoteTypeName(const typename ELFT::Note &Note,
5401                                 unsigned ELFType) {
5402   uint32_t Type = Note.getType();
5403   auto FindNote = [&](ArrayRef<NoteType> V) -> StringRef {
5404     for (const NoteType &N : V)
5405       if (N.ID == Type)
5406         return N.Name;
5407     return "";
5408   };
5409 
5410   StringRef Name = Note.getName();
5411   if (Name == "GNU")
5412     return FindNote(GNUNoteTypes);
5413   if (Name == "FreeBSD")
5414     return FindNote(FreeBSDNoteTypes);
5415   if (Name == "AMD")
5416     return FindNote(AMDNoteTypes);
5417   if (Name == "AMDGPU")
5418     return FindNote(AMDGPUNoteTypes);
5419 
5420   if (ELFType == ELF::ET_CORE)
5421     return FindNote(CoreNoteTypes);
5422   return FindNote(GenericNoteTypes);
5423 }
5424 
5425 template <class ELFT>
5426 static void printNotesHelper(
5427     const ELFDumper<ELFT> &Dumper,
5428     llvm::function_ref<void(Optional<StringRef>, typename ELFT::Off,
5429                             typename ELFT::Addr)>
5430         StartNotesFn,
5431     llvm::function_ref<Error(const typename ELFT::Note &)> ProcessNoteFn,
5432     llvm::function_ref<void()> FinishNotesFn) {
5433   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
5434 
5435   ArrayRef<typename ELFT::Shdr> Sections = cantFail(Obj.sections());
5436   if (Obj.getHeader().e_type != ELF::ET_CORE && !Sections.empty()) {
5437     for (const typename ELFT::Shdr &S : Sections) {
5438       if (S.sh_type != SHT_NOTE)
5439         continue;
5440       StartNotesFn(expectedToOptional(Obj.getSectionName(S)), S.sh_offset,
5441                    S.sh_size);
5442       Error Err = Error::success();
5443       size_t I = 0;
5444       for (const typename ELFT::Note Note : Obj.notes(S, Err)) {
5445         if (Error E = ProcessNoteFn(Note))
5446           Dumper.reportUniqueWarning(
5447               "unable to read note with index " + Twine(I) + " from the " +
5448               describe(Obj, S) + ": " + toString(std::move(E)));
5449         ++I;
5450       }
5451       if (Err)
5452         Dumper.reportUniqueWarning("unable to read notes from the " +
5453                                    describe(Obj, S) + ": " +
5454                                    toString(std::move(Err)));
5455       FinishNotesFn();
5456     }
5457     return;
5458   }
5459 
5460   Expected<ArrayRef<typename ELFT::Phdr>> PhdrsOrErr = Obj.program_headers();
5461   if (!PhdrsOrErr) {
5462     Dumper.reportUniqueWarning(
5463         "unable to read program headers to locate the PT_NOTE segment: " +
5464         toString(PhdrsOrErr.takeError()));
5465     return;
5466   }
5467 
5468   for (size_t I = 0, E = (*PhdrsOrErr).size(); I != E; ++I) {
5469     const typename ELFT::Phdr &P = (*PhdrsOrErr)[I];
5470     if (P.p_type != PT_NOTE)
5471       continue;
5472     StartNotesFn(/*SecName=*/None, P.p_offset, P.p_filesz);
5473     Error Err = Error::success();
5474     size_t Index = 0;
5475     for (const typename ELFT::Note Note : Obj.notes(P, Err)) {
5476       if (Error E = ProcessNoteFn(Note))
5477         Dumper.reportUniqueWarning("unable to read note with index " +
5478                                    Twine(Index) +
5479                                    " from the PT_NOTE segment with index " +
5480                                    Twine(I) + ": " + toString(std::move(E)));
5481       ++Index;
5482     }
5483     if (Err)
5484       Dumper.reportUniqueWarning(
5485           "unable to read notes from the PT_NOTE segment with index " +
5486           Twine(I) + ": " + toString(std::move(Err)));
5487     FinishNotesFn();
5488   }
5489 }
5490 
5491 template <class ELFT> void GNUELFDumper<ELFT>::printNotes() {
5492   auto PrintHeader = [&](Optional<StringRef> SecName,
5493                          const typename ELFT::Off Offset,
5494                          const typename ELFT::Addr Size) {
5495     OS << "Displaying notes found ";
5496 
5497     if (SecName)
5498       OS << "in: " << *SecName << "\n";
5499     else
5500       OS << "at file offset " << format_hex(Offset, 10) << " with length "
5501          << format_hex(Size, 10) << ":\n";
5502 
5503     OS << "  Owner                Data size \tDescription\n";
5504   };
5505 
5506   auto ProcessNote = [&](const Elf_Note &Note) -> Error {
5507     StringRef Name = Note.getName();
5508     ArrayRef<uint8_t> Descriptor = Note.getDesc();
5509     Elf_Word Type = Note.getType();
5510 
5511     // Print the note owner/type.
5512     OS << "  " << left_justify(Name, 20) << ' '
5513        << format_hex(Descriptor.size(), 10) << '\t';
5514 
5515     StringRef NoteType =
5516         getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
5517     if (!NoteType.empty())
5518       OS << NoteType << '\n';
5519     else
5520       OS << "Unknown note type: (" << format_hex(Type, 10) << ")\n";
5521 
5522     // Print the description, or fallback to printing raw bytes for unknown
5523     // owners.
5524     if (Name == "GNU") {
5525       printGNUNote<ELFT>(OS, Type, Descriptor);
5526     } else if (Name == "AMD") {
5527       const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
5528       if (!N.Type.empty())
5529         OS << "    " << N.Type << ":\n        " << N.Value << '\n';
5530     } else if (Name == "AMDGPU") {
5531       const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
5532       if (!N.Type.empty())
5533         OS << "    " << N.Type << ":\n        " << N.Value << '\n';
5534     } else if (Name == "CORE") {
5535       if (Type == ELF::NT_FILE) {
5536         DataExtractor DescExtractor(Descriptor,
5537                                     ELFT::TargetEndianness == support::little,
5538                                     sizeof(Elf_Addr));
5539         if (Expected<CoreNote> NoteOrErr = readCoreNote(DescExtractor))
5540           printCoreNote<ELFT>(OS, *NoteOrErr);
5541         else
5542           return NoteOrErr.takeError();
5543       }
5544     } else if (!Descriptor.empty()) {
5545       OS << "   description data:";
5546       for (uint8_t B : Descriptor)
5547         OS << " " << format("%02x", B);
5548       OS << '\n';
5549     }
5550     return Error::success();
5551   };
5552 
5553   printNotesHelper(*this, PrintHeader, ProcessNote, []() {});
5554 }
5555 
5556 template <class ELFT> void GNUELFDumper<ELFT>::printELFLinkerOptions() {
5557   OS << "printELFLinkerOptions not implemented!\n";
5558 }
5559 
5560 template <class ELFT>
5561 void ELFDumper<ELFT>::printDependentLibsHelper(
5562     function_ref<void(const Elf_Shdr &)> OnSectionStart,
5563     function_ref<void(StringRef, uint64_t)> OnLibEntry) {
5564   auto Warn = [this](unsigned SecNdx, StringRef Msg) {
5565     this->reportUniqueWarning("SHT_LLVM_DEPENDENT_LIBRARIES section at index " +
5566                               Twine(SecNdx) + " is broken: " + Msg);
5567   };
5568 
5569   unsigned I = -1;
5570   for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
5571     ++I;
5572     if (Shdr.sh_type != ELF::SHT_LLVM_DEPENDENT_LIBRARIES)
5573       continue;
5574 
5575     OnSectionStart(Shdr);
5576 
5577     Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Shdr);
5578     if (!ContentsOrErr) {
5579       Warn(I, toString(ContentsOrErr.takeError()));
5580       continue;
5581     }
5582 
5583     ArrayRef<uint8_t> Contents = *ContentsOrErr;
5584     if (!Contents.empty() && Contents.back() != 0) {
5585       Warn(I, "the content is not null-terminated");
5586       continue;
5587     }
5588 
5589     for (const uint8_t *I = Contents.begin(), *E = Contents.end(); I < E;) {
5590       StringRef Lib((const char *)I);
5591       OnLibEntry(Lib, I - Contents.begin());
5592       I += Lib.size() + 1;
5593     }
5594   }
5595 }
5596 
5597 template <class ELFT>
5598 void ELFDumper<ELFT>::forEachRelocationDo(
5599     const Elf_Shdr &Sec, bool RawRelr,
5600     llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
5601                             const Elf_Shdr &, const Elf_Shdr *)>
5602         RelRelaFn,
5603     llvm::function_ref<void(const Elf_Relr &)> RelrFn) {
5604   auto Warn = [&](Error &&E,
5605                   const Twine &Prefix = "unable to read relocations from") {
5606     this->reportUniqueWarning(Prefix + " " + describe(Sec) + ": " +
5607                               toString(std::move(E)));
5608   };
5609 
5610   // SHT_RELR/SHT_ANDROID_RELR sections do not have an associated symbol table.
5611   // For them we should not treat the value of the sh_link field as an index of
5612   // a symbol table.
5613   const Elf_Shdr *SymTab;
5614   if (Sec.sh_type != ELF::SHT_RELR && Sec.sh_type != ELF::SHT_ANDROID_RELR) {
5615     Expected<const Elf_Shdr *> SymTabOrErr = Obj.getSection(Sec.sh_link);
5616     if (!SymTabOrErr) {
5617       Warn(SymTabOrErr.takeError(), "unable to locate a symbol table for");
5618       return;
5619     }
5620     SymTab = *SymTabOrErr;
5621   }
5622 
5623   unsigned RelNdx = 0;
5624   const bool IsMips64EL = this->Obj.isMips64EL();
5625   switch (Sec.sh_type) {
5626   case ELF::SHT_REL:
5627     if (Expected<Elf_Rel_Range> RangeOrErr = Obj.rels(Sec)) {
5628       for (const Elf_Rel &R : *RangeOrErr)
5629         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5630     } else {
5631       Warn(RangeOrErr.takeError());
5632     }
5633     break;
5634   case ELF::SHT_RELA:
5635     if (Expected<Elf_Rela_Range> RangeOrErr = Obj.relas(Sec)) {
5636       for (const Elf_Rela &R : *RangeOrErr)
5637         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5638     } else {
5639       Warn(RangeOrErr.takeError());
5640     }
5641     break;
5642   case ELF::SHT_RELR:
5643   case ELF::SHT_ANDROID_RELR: {
5644     Expected<Elf_Relr_Range> RangeOrErr = Obj.relrs(Sec);
5645     if (!RangeOrErr) {
5646       Warn(RangeOrErr.takeError());
5647       break;
5648     }
5649     if (RawRelr) {
5650       for (const Elf_Relr &R : *RangeOrErr)
5651         RelrFn(R);
5652       break;
5653     }
5654 
5655     for (const Elf_Rel &R : Obj.decode_relrs(*RangeOrErr))
5656       RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec,
5657                 /*SymTab=*/nullptr);
5658     break;
5659   }
5660   case ELF::SHT_ANDROID_REL:
5661   case ELF::SHT_ANDROID_RELA:
5662     if (Expected<std::vector<Elf_Rela>> RelasOrErr = Obj.android_relas(Sec)) {
5663       for (const Elf_Rela &R : *RelasOrErr)
5664         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5665     } else {
5666       Warn(RelasOrErr.takeError());
5667     }
5668     break;
5669   }
5670 }
5671 
5672 template <class ELFT>
5673 StringRef ELFDumper<ELFT>::getPrintableSectionName(const Elf_Shdr &Sec) const {
5674   StringRef Name = "<?>";
5675   if (Expected<StringRef> SecNameOrErr =
5676           Obj.getSectionName(Sec, this->WarningHandler))
5677     Name = *SecNameOrErr;
5678   else
5679     this->reportUniqueWarning("unable to get the name of " + describe(Sec) +
5680                               ": " + toString(SecNameOrErr.takeError()));
5681   return Name;
5682 }
5683 
5684 template <class ELFT> void GNUELFDumper<ELFT>::printDependentLibs() {
5685   bool SectionStarted = false;
5686   struct NameOffset {
5687     StringRef Name;
5688     uint64_t Offset;
5689   };
5690   std::vector<NameOffset> SecEntries;
5691   NameOffset Current;
5692   auto PrintSection = [&]() {
5693     OS << "Dependent libraries section " << Current.Name << " at offset "
5694        << format_hex(Current.Offset, 1) << " contains " << SecEntries.size()
5695        << " entries:\n";
5696     for (NameOffset Entry : SecEntries)
5697       OS << "  [" << format("%6" PRIx64, Entry.Offset) << "]  " << Entry.Name
5698          << "\n";
5699     OS << "\n";
5700     SecEntries.clear();
5701   };
5702 
5703   auto OnSectionStart = [&](const Elf_Shdr &Shdr) {
5704     if (SectionStarted)
5705       PrintSection();
5706     SectionStarted = true;
5707     Current.Offset = Shdr.sh_offset;
5708     Current.Name = this->getPrintableSectionName(Shdr);
5709   };
5710   auto OnLibEntry = [&](StringRef Lib, uint64_t Offset) {
5711     SecEntries.push_back(NameOffset{Lib, Offset});
5712   };
5713 
5714   this->printDependentLibsHelper(OnSectionStart, OnLibEntry);
5715   if (SectionStarted)
5716     PrintSection();
5717 }
5718 
5719 template <class ELFT>
5720 bool ELFDumper<ELFT>::printFunctionStackSize(
5721     uint64_t SymValue, Optional<const Elf_Shdr *> FunctionSec,
5722     const Elf_Shdr &StackSizeSec, DataExtractor Data, uint64_t *Offset) {
5723   uint32_t FuncSymIndex = 0;
5724   if (this->DotSymtabSec) {
5725     if (Expected<Elf_Sym_Range> SymsOrError = Obj.symbols(this->DotSymtabSec)) {
5726       uint32_t Index = (uint32_t)-1;
5727       for (const Elf_Sym &Sym : *SymsOrError) {
5728         ++Index;
5729 
5730         if (Sym.st_shndx == ELF::SHN_UNDEF || Sym.getType() != ELF::STT_FUNC)
5731           continue;
5732 
5733         if (Expected<uint64_t> SymAddrOrErr =
5734                 ObjF.toSymbolRef(this->DotSymtabSec, Index).getAddress()) {
5735           if (SymValue != *SymAddrOrErr)
5736             continue;
5737         } else {
5738           std::string Name = this->getStaticSymbolName(Index);
5739           reportUniqueWarning("unable to get address of symbol '" + Name +
5740                               "': " + toString(SymAddrOrErr.takeError()));
5741           break;
5742         }
5743 
5744         // Check if the symbol is in the right section. FunctionSec == None
5745         // means "any section".
5746         if (FunctionSec) {
5747           if (Expected<const Elf_Shdr *> SecOrErr =
5748                   Obj.getSection(Sym, this->DotSymtabSec,
5749                                  this->getShndxTable(this->DotSymtabSec))) {
5750             if (*FunctionSec != *SecOrErr)
5751               continue;
5752           } else {
5753             std::string Name = this->getStaticSymbolName(Index);
5754             // Note: it is impossible to trigger this error currently, it is
5755             // untested.
5756             reportUniqueWarning("unable to get section of symbol '" + Name +
5757                                 "': " + toString(SecOrErr.takeError()));
5758             break;
5759           }
5760         }
5761 
5762         FuncSymIndex = Index;
5763         break;
5764       }
5765     } else {
5766       reportUniqueWarning("unable to read the symbol table: " +
5767                           toString(SymsOrError.takeError()));
5768     }
5769   }
5770 
5771   std::string FuncName = "?";
5772   if (!FuncSymIndex)
5773     reportUniqueWarning(
5774         "could not identify function symbol for stack size entry in " +
5775         describe(StackSizeSec));
5776   else
5777     FuncName = this->getStaticSymbolName(FuncSymIndex);
5778 
5779   // Extract the size. The expectation is that Offset is pointing to the right
5780   // place, i.e. past the function address.
5781   Error Err = Error::success();
5782   uint64_t StackSize = Data.getULEB128(Offset, &Err);
5783   if (Err) {
5784     reportUniqueWarning("could not extract a valid stack size from " +
5785                         describe(StackSizeSec) + ": " +
5786                         toString(std::move(Err)));
5787     return false;
5788   }
5789   printStackSizeEntry(StackSize, FuncName);
5790   return true;
5791 }
5792 
5793 template <class ELFT>
5794 void GNUELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
5795                                              StringRef FuncName) {
5796   OS.PadToColumn(2);
5797   OS << format_decimal(Size, 11);
5798   OS.PadToColumn(18);
5799   OS << FuncName << "\n";
5800 }
5801 
5802 template <class ELFT>
5803 void ELFDumper<ELFT>::printStackSize(const Relocation<ELFT> &R,
5804                                      const Elf_Shdr &RelocSec, unsigned Ndx,
5805                                      const Elf_Shdr *SymTab,
5806                                      const Elf_Shdr *FunctionSec,
5807                                      const Elf_Shdr &StackSizeSec,
5808                                      const RelocationResolver &Resolver,
5809                                      DataExtractor Data) {
5810   // This function ignores potentially erroneous input, unless it is directly
5811   // related to stack size reporting.
5812   const Elf_Sym *Sym = nullptr;
5813   Expected<RelSymbol<ELFT>> TargetOrErr = this->getRelocationTarget(R, SymTab);
5814   if (!TargetOrErr)
5815     reportUniqueWarning("unable to get the target of relocation with index " +
5816                         Twine(Ndx) + " in " + describe(RelocSec) + ": " +
5817                         toString(TargetOrErr.takeError()));
5818   else
5819     Sym = TargetOrErr->Sym;
5820 
5821   uint64_t RelocSymValue = 0;
5822   if (Sym) {
5823     Expected<const Elf_Shdr *> SectionOrErr =
5824         this->Obj.getSection(*Sym, SymTab, this->getShndxTable(SymTab));
5825     if (!SectionOrErr) {
5826       reportUniqueWarning(
5827           "cannot identify the section for relocation symbol '" +
5828           (*TargetOrErr).Name + "': " + toString(SectionOrErr.takeError()));
5829     } else if (*SectionOrErr != FunctionSec) {
5830       reportUniqueWarning("relocation symbol '" + (*TargetOrErr).Name +
5831                           "' is not in the expected section");
5832       // Pretend that the symbol is in the correct section and report its
5833       // stack size anyway.
5834       FunctionSec = *SectionOrErr;
5835     }
5836 
5837     RelocSymValue = Sym->st_value;
5838   }
5839 
5840   uint64_t Offset = R.Offset;
5841   if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
5842     reportUniqueWarning("found invalid relocation offset (0x" +
5843                         Twine::utohexstr(Offset) + ") into " +
5844                         describe(StackSizeSec) +
5845                         " while trying to extract a stack size entry");
5846     return;
5847   }
5848 
5849   uint64_t SymValue =
5850       Resolver(R.Type, Offset, RelocSymValue, Data.getAddress(&Offset),
5851                R.Addend.getValueOr(0));
5852   this->printFunctionStackSize(SymValue, FunctionSec, StackSizeSec, Data,
5853                                &Offset);
5854 }
5855 
5856 template <class ELFT>
5857 void ELFDumper<ELFT>::printNonRelocatableStackSizes(
5858     std::function<void()> PrintHeader) {
5859   // This function ignores potentially erroneous input, unless it is directly
5860   // related to stack size reporting.
5861   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
5862     if (this->getPrintableSectionName(Sec) != ".stack_sizes")
5863       continue;
5864     PrintHeader();
5865     ArrayRef<uint8_t> Contents =
5866         unwrapOrError(this->FileName, Obj.getSectionContents(Sec));
5867     DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
5868     uint64_t Offset = 0;
5869     while (Offset < Contents.size()) {
5870       // The function address is followed by a ULEB representing the stack
5871       // size. Check for an extra byte before we try to process the entry.
5872       if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
5873         reportUniqueWarning(
5874             describe(Sec) +
5875             " ended while trying to extract a stack size entry");
5876         break;
5877       }
5878       uint64_t SymValue = Data.getAddress(&Offset);
5879       if (!printFunctionStackSize(SymValue, /*FunctionSec=*/None, Sec, Data,
5880                                   &Offset))
5881         break;
5882     }
5883   }
5884 }
5885 
5886 template <class ELFT>
5887 void ELFDumper<ELFT>::printRelocatableStackSizes(
5888     std::function<void()> PrintHeader) {
5889   // Build a map between stack size sections and their corresponding relocation
5890   // sections.
5891   llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> StackSizeRelocMap;
5892   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
5893     StringRef SectionName;
5894     if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec))
5895       SectionName = *NameOrErr;
5896     else
5897       consumeError(NameOrErr.takeError());
5898 
5899     // A stack size section that we haven't encountered yet is mapped to the
5900     // null section until we find its corresponding relocation section.
5901     if (SectionName == ".stack_sizes")
5902       if (StackSizeRelocMap
5903               .insert(std::make_pair(&Sec, (const Elf_Shdr *)nullptr))
5904               .second)
5905         continue;
5906 
5907     // Check relocation sections if they are relocating contents of a
5908     // stack sizes section.
5909     if (Sec.sh_type != ELF::SHT_RELA && Sec.sh_type != ELF::SHT_REL)
5910       continue;
5911 
5912     Expected<const Elf_Shdr *> RelSecOrErr = Obj.getSection(Sec.sh_info);
5913     if (!RelSecOrErr) {
5914       reportUniqueWarning(describe(Sec) +
5915                           ": failed to get a relocated section: " +
5916                           toString(RelSecOrErr.takeError()));
5917       continue;
5918     }
5919 
5920     const Elf_Shdr *ContentsSec = *RelSecOrErr;
5921     if (this->getPrintableSectionName(**RelSecOrErr) != ".stack_sizes")
5922       continue;
5923 
5924     // Insert a mapping from the stack sizes section to its relocation section.
5925     StackSizeRelocMap[ContentsSec] = &Sec;
5926   }
5927 
5928   for (const auto &StackSizeMapEntry : StackSizeRelocMap) {
5929     PrintHeader();
5930     const Elf_Shdr *StackSizesELFSec = StackSizeMapEntry.first;
5931     const Elf_Shdr *RelocSec = StackSizeMapEntry.second;
5932 
5933     // Warn about stack size sections without a relocation section.
5934     if (!RelocSec) {
5935       reportWarning(createError(".stack_sizes (" + describe(*StackSizesELFSec) +
5936                                 ") does not have a corresponding "
5937                                 "relocation section"),
5938                     FileName);
5939       continue;
5940     }
5941 
5942     // A .stack_sizes section header's sh_link field is supposed to point
5943     // to the section that contains the functions whose stack sizes are
5944     // described in it.
5945     const Elf_Shdr *FunctionSec = unwrapOrError(
5946         this->FileName, Obj.getSection(StackSizesELFSec->sh_link));
5947 
5948     SupportsRelocation IsSupportedFn;
5949     RelocationResolver Resolver;
5950     std::tie(IsSupportedFn, Resolver) = getRelocationResolver(this->ObjF);
5951     ArrayRef<uint8_t> Contents =
5952         unwrapOrError(this->FileName, Obj.getSectionContents(*StackSizesELFSec));
5953     DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
5954 
5955     forEachRelocationDo(
5956         *RelocSec, /*RawRelr=*/false,
5957         [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
5958             const Elf_Shdr *SymTab) {
5959           if (!IsSupportedFn || !IsSupportedFn(R.Type)) {
5960             reportUniqueWarning(
5961                 describe(*RelocSec) +
5962                 " contains an unsupported relocation with index " + Twine(Ndx) +
5963                 ": " + Obj.getRelocationTypeName(R.Type));
5964             return;
5965           }
5966 
5967           this->printStackSize(R, *RelocSec, Ndx, SymTab, FunctionSec,
5968                                *StackSizesELFSec, Resolver, Data);
5969         },
5970         [](const Elf_Relr &) {
5971           llvm_unreachable("can't get here, because we only support "
5972                            "SHT_REL/SHT_RELA sections");
5973         });
5974   }
5975 }
5976 
5977 template <class ELFT>
5978 void GNUELFDumper<ELFT>::printStackSizes() {
5979   bool HeaderHasBeenPrinted = false;
5980   auto PrintHeader = [&]() {
5981     if (HeaderHasBeenPrinted)
5982       return;
5983     OS << "\nStack Sizes:\n";
5984     OS.PadToColumn(9);
5985     OS << "Size";
5986     OS.PadToColumn(18);
5987     OS << "Function\n";
5988     HeaderHasBeenPrinted = true;
5989   };
5990 
5991   // For non-relocatable objects, look directly for sections whose name starts
5992   // with .stack_sizes and process the contents.
5993   if (this->Obj.getHeader().e_type == ELF::ET_REL)
5994     this->printRelocatableStackSizes(PrintHeader);
5995   else
5996     this->printNonRelocatableStackSizes(PrintHeader);
5997 }
5998 
5999 template <class ELFT>
6000 void GNUELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
6001   size_t Bias = ELFT::Is64Bits ? 8 : 0;
6002   auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
6003     OS.PadToColumn(2);
6004     OS << format_hex_no_prefix(Parser.getGotAddress(E), 8 + Bias);
6005     OS.PadToColumn(11 + Bias);
6006     OS << format_decimal(Parser.getGotOffset(E), 6) << "(gp)";
6007     OS.PadToColumn(22 + Bias);
6008     OS << format_hex_no_prefix(*E, 8 + Bias);
6009     OS.PadToColumn(31 + 2 * Bias);
6010     OS << Purpose << "\n";
6011   };
6012 
6013   OS << (Parser.IsStatic ? "Static GOT:\n" : "Primary GOT:\n");
6014   OS << " Canonical gp value: "
6015      << format_hex_no_prefix(Parser.getGp(), 8 + Bias) << "\n\n";
6016 
6017   OS << " Reserved entries:\n";
6018   if (ELFT::Is64Bits)
6019     OS << "           Address     Access          Initial Purpose\n";
6020   else
6021     OS << "   Address     Access  Initial Purpose\n";
6022   PrintEntry(Parser.getGotLazyResolver(), "Lazy resolver");
6023   if (Parser.getGotModulePointer())
6024     PrintEntry(Parser.getGotModulePointer(), "Module pointer (GNU extension)");
6025 
6026   if (!Parser.getLocalEntries().empty()) {
6027     OS << "\n";
6028     OS << " Local entries:\n";
6029     if (ELFT::Is64Bits)
6030       OS << "           Address     Access          Initial\n";
6031     else
6032       OS << "   Address     Access  Initial\n";
6033     for (auto &E : Parser.getLocalEntries())
6034       PrintEntry(&E, "");
6035   }
6036 
6037   if (Parser.IsStatic)
6038     return;
6039 
6040   if (!Parser.getGlobalEntries().empty()) {
6041     OS << "\n";
6042     OS << " Global entries:\n";
6043     if (ELFT::Is64Bits)
6044       OS << "           Address     Access          Initial         Sym.Val."
6045          << " Type    Ndx Name\n";
6046     else
6047       OS << "   Address     Access  Initial Sym.Val. Type    Ndx Name\n";
6048 
6049     DataRegion<Elf_Word> ShndxTable(
6050         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6051     for (auto &E : Parser.getGlobalEntries()) {
6052       const Elf_Sym &Sym = *Parser.getGotSym(&E);
6053       const Elf_Sym &FirstSym = this->dynamic_symbols()[0];
6054       std::string SymName = this->getFullSymbolName(
6055           Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
6056 
6057       OS.PadToColumn(2);
6058       OS << to_string(format_hex_no_prefix(Parser.getGotAddress(&E), 8 + Bias));
6059       OS.PadToColumn(11 + Bias);
6060       OS << to_string(format_decimal(Parser.getGotOffset(&E), 6)) + "(gp)";
6061       OS.PadToColumn(22 + Bias);
6062       OS << to_string(format_hex_no_prefix(E, 8 + Bias));
6063       OS.PadToColumn(31 + 2 * Bias);
6064       OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
6065       OS.PadToColumn(40 + 3 * Bias);
6066       OS << printEnum(Sym.getType(), makeArrayRef(ElfSymbolTypes));
6067       OS.PadToColumn(48 + 3 * Bias);
6068       OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
6069                                 ShndxTable);
6070       OS.PadToColumn(52 + 3 * Bias);
6071       OS << SymName << "\n";
6072     }
6073   }
6074 
6075   if (!Parser.getOtherEntries().empty())
6076     OS << "\n Number of TLS and multi-GOT entries "
6077        << Parser.getOtherEntries().size() << "\n";
6078 }
6079 
6080 template <class ELFT>
6081 void GNUELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
6082   size_t Bias = ELFT::Is64Bits ? 8 : 0;
6083   auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
6084     OS.PadToColumn(2);
6085     OS << format_hex_no_prefix(Parser.getPltAddress(E), 8 + Bias);
6086     OS.PadToColumn(11 + Bias);
6087     OS << format_hex_no_prefix(*E, 8 + Bias);
6088     OS.PadToColumn(20 + 2 * Bias);
6089     OS << Purpose << "\n";
6090   };
6091 
6092   OS << "PLT GOT:\n\n";
6093 
6094   OS << " Reserved entries:\n";
6095   OS << "   Address  Initial Purpose\n";
6096   PrintEntry(Parser.getPltLazyResolver(), "PLT lazy resolver");
6097   if (Parser.getPltModulePointer())
6098     PrintEntry(Parser.getPltModulePointer(), "Module pointer");
6099 
6100   if (!Parser.getPltEntries().empty()) {
6101     OS << "\n";
6102     OS << " Entries:\n";
6103     OS << "   Address  Initial Sym.Val. Type    Ndx Name\n";
6104     DataRegion<Elf_Word> ShndxTable(
6105         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6106     for (auto &E : Parser.getPltEntries()) {
6107       const Elf_Sym &Sym = *Parser.getPltSym(&E);
6108       const Elf_Sym &FirstSym = *cantFail(
6109           this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
6110       std::string SymName = this->getFullSymbolName(
6111           Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
6112 
6113       OS.PadToColumn(2);
6114       OS << to_string(format_hex_no_prefix(Parser.getPltAddress(&E), 8 + Bias));
6115       OS.PadToColumn(11 + Bias);
6116       OS << to_string(format_hex_no_prefix(E, 8 + Bias));
6117       OS.PadToColumn(20 + 2 * Bias);
6118       OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
6119       OS.PadToColumn(29 + 3 * Bias);
6120       OS << printEnum(Sym.getType(), makeArrayRef(ElfSymbolTypes));
6121       OS.PadToColumn(37 + 3 * Bias);
6122       OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
6123                                 ShndxTable);
6124       OS.PadToColumn(41 + 3 * Bias);
6125       OS << SymName << "\n";
6126     }
6127   }
6128 }
6129 
6130 template <class ELFT>
6131 Expected<const Elf_Mips_ABIFlags<ELFT> *>
6132 getMipsAbiFlagsSection(const ELFDumper<ELFT> &Dumper) {
6133   const typename ELFT::Shdr *Sec = Dumper.findSectionByName(".MIPS.abiflags");
6134   if (Sec == nullptr)
6135     return nullptr;
6136 
6137   constexpr StringRef ErrPrefix = "unable to read the .MIPS.abiflags section: ";
6138   Expected<ArrayRef<uint8_t>> DataOrErr =
6139       Dumper.getElfObject().getELFFile().getSectionContents(*Sec);
6140   if (!DataOrErr)
6141     return createError(ErrPrefix + toString(DataOrErr.takeError()));
6142 
6143   if (DataOrErr->size() != sizeof(Elf_Mips_ABIFlags<ELFT>))
6144     return createError(ErrPrefix + "it has a wrong size (" +
6145         Twine(DataOrErr->size()) + ")");
6146   return reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(DataOrErr->data());
6147 }
6148 
6149 template <class ELFT> void GNUELFDumper<ELFT>::printMipsABIFlags() {
6150   const Elf_Mips_ABIFlags<ELFT> *Flags = nullptr;
6151   if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
6152           getMipsAbiFlagsSection(*this))
6153     Flags = *SecOrErr;
6154   else
6155     this->reportUniqueWarning(SecOrErr.takeError());
6156   if (!Flags)
6157     return;
6158 
6159   OS << "MIPS ABI Flags Version: " << Flags->version << "\n\n";
6160   OS << "ISA: MIPS" << int(Flags->isa_level);
6161   if (Flags->isa_rev > 1)
6162     OS << "r" << int(Flags->isa_rev);
6163   OS << "\n";
6164   OS << "GPR size: " << getMipsRegisterSize(Flags->gpr_size) << "\n";
6165   OS << "CPR1 size: " << getMipsRegisterSize(Flags->cpr1_size) << "\n";
6166   OS << "CPR2 size: " << getMipsRegisterSize(Flags->cpr2_size) << "\n";
6167   OS << "FP ABI: " << printEnum(Flags->fp_abi, makeArrayRef(ElfMipsFpABIType))
6168      << "\n";
6169   OS << "ISA Extension: "
6170      << printEnum(Flags->isa_ext, makeArrayRef(ElfMipsISAExtType)) << "\n";
6171   if (Flags->ases == 0)
6172     OS << "ASEs: None\n";
6173   else
6174     // FIXME: Print each flag on a separate line.
6175     OS << "ASEs: " << printFlags(Flags->ases, makeArrayRef(ElfMipsASEFlags))
6176        << "\n";
6177   OS << "FLAGS 1: " << format_hex_no_prefix(Flags->flags1, 8, false) << "\n";
6178   OS << "FLAGS 2: " << format_hex_no_prefix(Flags->flags2, 8, false) << "\n";
6179   OS << "\n";
6180 }
6181 
6182 template <class ELFT> void LLVMELFDumper<ELFT>::printFileHeaders() {
6183   const Elf_Ehdr &E = this->Obj.getHeader();
6184   {
6185     DictScope D(W, "ElfHeader");
6186     {
6187       DictScope D(W, "Ident");
6188       W.printBinary("Magic", makeArrayRef(E.e_ident).slice(ELF::EI_MAG0, 4));
6189       W.printEnum("Class", E.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass));
6190       W.printEnum("DataEncoding", E.e_ident[ELF::EI_DATA],
6191                   makeArrayRef(ElfDataEncoding));
6192       W.printNumber("FileVersion", E.e_ident[ELF::EI_VERSION]);
6193 
6194       auto OSABI = makeArrayRef(ElfOSABI);
6195       if (E.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH &&
6196           E.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) {
6197         switch (E.e_machine) {
6198         case ELF::EM_AMDGPU:
6199           OSABI = makeArrayRef(AMDGPUElfOSABI);
6200           break;
6201         case ELF::EM_ARM:
6202           OSABI = makeArrayRef(ARMElfOSABI);
6203           break;
6204         case ELF::EM_TI_C6000:
6205           OSABI = makeArrayRef(C6000ElfOSABI);
6206           break;
6207         }
6208       }
6209       W.printEnum("OS/ABI", E.e_ident[ELF::EI_OSABI], OSABI);
6210       W.printNumber("ABIVersion", E.e_ident[ELF::EI_ABIVERSION]);
6211       W.printBinary("Unused", makeArrayRef(E.e_ident).slice(ELF::EI_PAD));
6212     }
6213 
6214     std::string TypeStr;
6215     if (const EnumEntry<unsigned> *Ent = getObjectFileEnumEntry(E.e_type)) {
6216       TypeStr = Ent->Name.str();
6217     } else {
6218       if (E.e_type >= ET_LOPROC)
6219         TypeStr = "Processor Specific";
6220       else if (E.e_type >= ET_LOOS)
6221         TypeStr = "OS Specific";
6222       else
6223         TypeStr = "Unknown";
6224     }
6225     W.printString("Type", TypeStr + " (0x" + to_hexString(E.e_type) + ")");
6226 
6227     W.printEnum("Machine", E.e_machine, makeArrayRef(ElfMachineType));
6228     W.printNumber("Version", E.e_version);
6229     W.printHex("Entry", E.e_entry);
6230     W.printHex("ProgramHeaderOffset", E.e_phoff);
6231     W.printHex("SectionHeaderOffset", E.e_shoff);
6232     if (E.e_machine == EM_MIPS)
6233       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderMipsFlags),
6234                    unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
6235                    unsigned(ELF::EF_MIPS_MACH));
6236     else if (E.e_machine == EM_AMDGPU)
6237       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderAMDGPUFlags),
6238                    unsigned(ELF::EF_AMDGPU_MACH));
6239     else if (E.e_machine == EM_RISCV)
6240       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderRISCVFlags));
6241     else
6242       W.printFlags("Flags", E.e_flags);
6243     W.printNumber("HeaderSize", E.e_ehsize);
6244     W.printNumber("ProgramHeaderEntrySize", E.e_phentsize);
6245     W.printNumber("ProgramHeaderCount", E.e_phnum);
6246     W.printNumber("SectionHeaderEntrySize", E.e_shentsize);
6247     W.printString("SectionHeaderCount",
6248                   getSectionHeadersNumString(this->Obj, this->FileName));
6249     W.printString("StringTableSectionIndex",
6250                   getSectionHeaderTableIndexString(this->Obj, this->FileName));
6251   }
6252 }
6253 
6254 template <class ELFT> void LLVMELFDumper<ELFT>::printGroupSections() {
6255   DictScope Lists(W, "Groups");
6256   std::vector<GroupSection> V = this->getGroups();
6257   DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
6258   for (const GroupSection &G : V) {
6259     DictScope D(W, "Group");
6260     W.printNumber("Name", G.Name, G.ShName);
6261     W.printNumber("Index", G.Index);
6262     W.printNumber("Link", G.Link);
6263     W.printNumber("Info", G.Info);
6264     W.printHex("Type", getGroupType(G.Type), G.Type);
6265     W.startLine() << "Signature: " << G.Signature << "\n";
6266 
6267     ListScope L(W, "Section(s) in group");
6268     for (const GroupMember &GM : G.Members) {
6269       const GroupSection *MainGroup = Map[GM.Index];
6270       if (MainGroup != &G)
6271         this->reportUniqueWarning(
6272             "section with index " + Twine(GM.Index) +
6273             ", included in the group section with index " +
6274             Twine(MainGroup->Index) +
6275             ", was also found in the group section with index " +
6276             Twine(G.Index));
6277       W.startLine() << GM.Name << " (" << GM.Index << ")\n";
6278     }
6279   }
6280 
6281   if (V.empty())
6282     W.startLine() << "There are no group sections in the file.\n";
6283 }
6284 
6285 template <class ELFT> void LLVMELFDumper<ELFT>::printRelocations() {
6286   ListScope D(W, "Relocations");
6287 
6288   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6289     if (!isRelocationSec<ELFT>(Sec))
6290       continue;
6291 
6292     StringRef Name = this->getPrintableSectionName(Sec);
6293     unsigned SecNdx = &Sec - &cantFail(this->Obj.sections()).front();
6294     W.startLine() << "Section (" << SecNdx << ") " << Name << " {\n";
6295     W.indent();
6296     this->printRelocationsHelper(Sec);
6297     W.unindent();
6298     W.startLine() << "}\n";
6299   }
6300 }
6301 
6302 template <class ELFT>
6303 void LLVMELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
6304   W.startLine() << W.hex(R) << "\n";
6305 }
6306 
6307 template <class ELFT>
6308 void LLVMELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
6309                                             const RelSymbol<ELFT> &RelSym) {
6310   StringRef SymbolName = RelSym.Name;
6311   SmallString<32> RelocName;
6312   this->Obj.getRelocationTypeName(R.Type, RelocName);
6313 
6314   if (opts::ExpandRelocs) {
6315     DictScope Group(W, "Relocation");
6316     W.printHex("Offset", R.Offset);
6317     W.printNumber("Type", RelocName, R.Type);
6318     W.printNumber("Symbol", !SymbolName.empty() ? SymbolName : "-", R.Symbol);
6319     if (R.Addend)
6320       W.printHex("Addend", (uintX_t)*R.Addend);
6321   } else {
6322     raw_ostream &OS = W.startLine();
6323     OS << W.hex(R.Offset) << " " << RelocName << " "
6324        << (!SymbolName.empty() ? SymbolName : "-");
6325     if (R.Addend)
6326       OS << " " << W.hex((uintX_t)*R.Addend);
6327     OS << "\n";
6328   }
6329 }
6330 
6331 template <class ELFT> void LLVMELFDumper<ELFT>::printSectionHeaders() {
6332   ListScope SectionsD(W, "Sections");
6333 
6334   int SectionIndex = -1;
6335   std::vector<EnumEntry<unsigned>> FlagsList =
6336       getSectionFlagsForTarget(this->Obj.getHeader().e_machine);
6337   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6338     DictScope SectionD(W, "Section");
6339     W.printNumber("Index", ++SectionIndex);
6340     W.printNumber("Name", this->getPrintableSectionName(Sec), Sec.sh_name);
6341     W.printHex("Type",
6342                object::getELFSectionTypeName(this->Obj.getHeader().e_machine,
6343                                              Sec.sh_type),
6344                Sec.sh_type);
6345     W.printFlags("Flags", Sec.sh_flags, makeArrayRef(FlagsList));
6346     W.printHex("Address", Sec.sh_addr);
6347     W.printHex("Offset", Sec.sh_offset);
6348     W.printNumber("Size", Sec.sh_size);
6349     W.printNumber("Link", Sec.sh_link);
6350     W.printNumber("Info", Sec.sh_info);
6351     W.printNumber("AddressAlignment", Sec.sh_addralign);
6352     W.printNumber("EntrySize", Sec.sh_entsize);
6353 
6354     if (opts::SectionRelocations) {
6355       ListScope D(W, "Relocations");
6356       this->printRelocationsHelper(Sec);
6357     }
6358 
6359     if (opts::SectionSymbols) {
6360       ListScope D(W, "Symbols");
6361       if (this->DotSymtabSec) {
6362         StringRef StrTable = unwrapOrError(
6363             this->FileName,
6364             this->Obj.getStringTableForSymtab(*this->DotSymtabSec));
6365         ArrayRef<Elf_Word> ShndxTable = this->getShndxTable(this->DotSymtabSec);
6366 
6367         typename ELFT::SymRange Symbols = unwrapOrError(
6368             this->FileName, this->Obj.symbols(this->DotSymtabSec));
6369         for (const Elf_Sym &Sym : Symbols) {
6370           const Elf_Shdr *SymSec = unwrapOrError(
6371               this->FileName,
6372               this->Obj.getSection(Sym, this->DotSymtabSec, ShndxTable));
6373           if (SymSec == &Sec)
6374             printSymbol(Sym, &Sym - &Symbols[0], ShndxTable, StrTable, false,
6375                         false);
6376         }
6377       }
6378     }
6379 
6380     if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) {
6381       ArrayRef<uint8_t> Data =
6382           unwrapOrError(this->FileName, this->Obj.getSectionContents(Sec));
6383       W.printBinaryBlock(
6384           "SectionData",
6385           StringRef(reinterpret_cast<const char *>(Data.data()), Data.size()));
6386     }
6387   }
6388 }
6389 
6390 template <class ELFT>
6391 void LLVMELFDumper<ELFT>::printSymbolSection(
6392     const Elf_Sym &Symbol, unsigned SymIndex,
6393     DataRegion<Elf_Word> ShndxTable) const {
6394   auto GetSectionSpecialType = [&]() -> Optional<StringRef> {
6395     if (Symbol.isUndefined())
6396       return StringRef("Undefined");
6397     if (Symbol.isProcessorSpecific())
6398       return StringRef("Processor Specific");
6399     if (Symbol.isOSSpecific())
6400       return StringRef("Operating System Specific");
6401     if (Symbol.isAbsolute())
6402       return StringRef("Absolute");
6403     if (Symbol.isCommon())
6404       return StringRef("Common");
6405     if (Symbol.isReserved() && Symbol.st_shndx != SHN_XINDEX)
6406       return StringRef("Reserved");
6407     return None;
6408   };
6409 
6410   if (Optional<StringRef> Type = GetSectionSpecialType()) {
6411     W.printHex("Section", *Type, Symbol.st_shndx);
6412     return;
6413   }
6414 
6415   Expected<unsigned> SectionIndex =
6416       this->getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
6417   if (!SectionIndex) {
6418     assert(Symbol.st_shndx == SHN_XINDEX &&
6419            "getSymbolSectionIndex should only fail due to an invalid "
6420            "SHT_SYMTAB_SHNDX table/reference");
6421     this->reportUniqueWarning(SectionIndex.takeError());
6422     W.printHex("Section", "Reserved", SHN_XINDEX);
6423     return;
6424   }
6425 
6426   Expected<StringRef> SectionName =
6427       this->getSymbolSectionName(Symbol, *SectionIndex);
6428   if (!SectionName) {
6429     // Don't report an invalid section name if the section headers are missing.
6430     // In such situations, all sections will be "invalid".
6431     if (!this->ObjF.sections().empty())
6432       this->reportUniqueWarning(SectionName.takeError());
6433     else
6434       consumeError(SectionName.takeError());
6435     W.printHex("Section", "<?>", *SectionIndex);
6436   } else {
6437     W.printHex("Section", *SectionName, *SectionIndex);
6438   }
6439 }
6440 
6441 template <class ELFT>
6442 void LLVMELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
6443                                       DataRegion<Elf_Word> ShndxTable,
6444                                       Optional<StringRef> StrTable,
6445                                       bool IsDynamic,
6446                                       bool /*NonVisibilityBitsUsed*/) const {
6447   std::string FullSymbolName = this->getFullSymbolName(
6448       Symbol, SymIndex, ShndxTable, StrTable, IsDynamic);
6449   unsigned char SymbolType = Symbol.getType();
6450 
6451   DictScope D(W, "Symbol");
6452   W.printNumber("Name", FullSymbolName, Symbol.st_name);
6453   W.printHex("Value", Symbol.st_value);
6454   W.printNumber("Size", Symbol.st_size);
6455   W.printEnum("Binding", Symbol.getBinding(), makeArrayRef(ElfSymbolBindings));
6456   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
6457       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
6458     W.printEnum("Type", SymbolType, makeArrayRef(AMDGPUSymbolTypes));
6459   else
6460     W.printEnum("Type", SymbolType, makeArrayRef(ElfSymbolTypes));
6461   if (Symbol.st_other == 0)
6462     // Usually st_other flag is zero. Do not pollute the output
6463     // by flags enumeration in that case.
6464     W.printNumber("Other", 0);
6465   else {
6466     std::vector<EnumEntry<unsigned>> SymOtherFlags(std::begin(ElfSymOtherFlags),
6467                                                    std::end(ElfSymOtherFlags));
6468     if (this->Obj.getHeader().e_machine == EM_MIPS) {
6469       // Someones in their infinite wisdom decided to make STO_MIPS_MIPS16
6470       // flag overlapped with other ST_MIPS_xxx flags. So consider both
6471       // cases separately.
6472       if ((Symbol.st_other & STO_MIPS_MIPS16) == STO_MIPS_MIPS16)
6473         SymOtherFlags.insert(SymOtherFlags.end(),
6474                              std::begin(ElfMips16SymOtherFlags),
6475                              std::end(ElfMips16SymOtherFlags));
6476       else
6477         SymOtherFlags.insert(SymOtherFlags.end(),
6478                              std::begin(ElfMipsSymOtherFlags),
6479                              std::end(ElfMipsSymOtherFlags));
6480     } else if (this->Obj.getHeader().e_machine == EM_AARCH64) {
6481       SymOtherFlags.insert(SymOtherFlags.end(),
6482                            std::begin(ElfAArch64SymOtherFlags),
6483                            std::end(ElfAArch64SymOtherFlags));
6484     }
6485     W.printFlags("Other", Symbol.st_other, makeArrayRef(SymOtherFlags), 0x3u);
6486   }
6487   printSymbolSection(Symbol, SymIndex, ShndxTable);
6488 }
6489 
6490 template <class ELFT>
6491 void LLVMELFDumper<ELFT>::printSymbols(bool PrintSymbols,
6492                                        bool PrintDynamicSymbols) {
6493   if (PrintSymbols) {
6494     ListScope Group(W, "Symbols");
6495     this->printSymbolsHelper(false);
6496   }
6497   if (PrintDynamicSymbols) {
6498     ListScope Group(W, "DynamicSymbols");
6499     this->printSymbolsHelper(true);
6500   }
6501 }
6502 
6503 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicTable() {
6504   Elf_Dyn_Range Table = this->dynamic_table();
6505   if (Table.empty())
6506     return;
6507 
6508   W.startLine() << "DynamicSection [ (" << Table.size() << " entries)\n";
6509 
6510   size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table);
6511   // The "Name/Value" column should be indented from the "Type" column by N
6512   // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
6513   // space (1) = -3.
6514   W.startLine() << "  Tag" << std::string(ELFT::Is64Bits ? 16 : 8, ' ')
6515                 << "Type" << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
6516 
6517   std::string ValueFmt = "%-" + std::to_string(MaxTagSize) + "s ";
6518   for (auto Entry : Table) {
6519     uintX_t Tag = Entry.getTag();
6520     std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
6521     W.startLine() << "  " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10, true)
6522                   << " "
6523                   << format(ValueFmt.c_str(),
6524                             this->Obj.getDynamicTagAsString(Tag).c_str())
6525                   << Value << "\n";
6526   }
6527   W.startLine() << "]\n";
6528 }
6529 
6530 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicRelocations() {
6531   W.startLine() << "Dynamic Relocations {\n";
6532   W.indent();
6533   this->printDynamicRelocationsHelper();
6534   W.unindent();
6535   W.startLine() << "}\n";
6536 }
6537 
6538 template <class ELFT>
6539 void LLVMELFDumper<ELFT>::printProgramHeaders(
6540     bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
6541   if (PrintProgramHeaders)
6542     printProgramHeaders();
6543   if (PrintSectionMapping == cl::BOU_TRUE)
6544     printSectionMapping();
6545 }
6546 
6547 template <class ELFT> void LLVMELFDumper<ELFT>::printProgramHeaders() {
6548   ListScope L(W, "ProgramHeaders");
6549 
6550   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
6551   if (!PhdrsOrErr) {
6552     this->reportUniqueWarning("unable to dump program headers: " +
6553                               toString(PhdrsOrErr.takeError()));
6554     return;
6555   }
6556 
6557   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
6558     DictScope P(W, "ProgramHeader");
6559     StringRef Type =
6560         segmentTypeToString(this->Obj.getHeader().e_machine, Phdr.p_type);
6561 
6562     W.printHex("Type", Type.empty() ? "Unknown" : Type, Phdr.p_type);
6563     W.printHex("Offset", Phdr.p_offset);
6564     W.printHex("VirtualAddress", Phdr.p_vaddr);
6565     W.printHex("PhysicalAddress", Phdr.p_paddr);
6566     W.printNumber("FileSize", Phdr.p_filesz);
6567     W.printNumber("MemSize", Phdr.p_memsz);
6568     W.printFlags("Flags", Phdr.p_flags, makeArrayRef(ElfSegmentFlags));
6569     W.printNumber("Alignment", Phdr.p_align);
6570   }
6571 }
6572 
6573 template <class ELFT>
6574 void LLVMELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
6575   ListScope SS(W, "VersionSymbols");
6576   if (!Sec)
6577     return;
6578 
6579   StringRef StrTable;
6580   ArrayRef<Elf_Sym> Syms;
6581   const Elf_Shdr *SymTabSec;
6582   Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
6583       this->getVersionTable(*Sec, &Syms, &StrTable, &SymTabSec);
6584   if (!VerTableOrErr) {
6585     this->reportUniqueWarning(VerTableOrErr.takeError());
6586     return;
6587   }
6588 
6589   if (StrTable.empty() || Syms.empty() || Syms.size() != VerTableOrErr->size())
6590     return;
6591 
6592   ArrayRef<Elf_Word> ShNdxTable = this->getShndxTable(SymTabSec);
6593   for (size_t I = 0, E = Syms.size(); I < E; ++I) {
6594     DictScope S(W, "Symbol");
6595     W.printNumber("Version", (*VerTableOrErr)[I].vs_index & VERSYM_VERSION);
6596     W.printString("Name",
6597                   this->getFullSymbolName(Syms[I], I, ShNdxTable, StrTable,
6598                                           /*IsDynamic=*/true));
6599   }
6600 }
6601 
6602 static const EnumEntry<unsigned> SymVersionFlags[] = {
6603     {"Base", "BASE", VER_FLG_BASE},
6604     {"Weak", "WEAK", VER_FLG_WEAK},
6605     {"Info", "INFO", VER_FLG_INFO}};
6606 
6607 template <class ELFT>
6608 void LLVMELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
6609   ListScope SD(W, "VersionDefinitions");
6610   if (!Sec)
6611     return;
6612 
6613   Expected<std::vector<VerDef>> V = this->getVersionDefinitions(*Sec);
6614   if (!V) {
6615     this->reportUniqueWarning(V.takeError());
6616     return;
6617   }
6618 
6619   for (const VerDef &D : *V) {
6620     DictScope Def(W, "Definition");
6621     W.printNumber("Version", D.Version);
6622     W.printFlags("Flags", D.Flags, makeArrayRef(SymVersionFlags));
6623     W.printNumber("Index", D.Ndx);
6624     W.printNumber("Hash", D.Hash);
6625     W.printString("Name", D.Name.c_str());
6626     W.printList(
6627         "Predecessors", D.AuxV,
6628         [](raw_ostream &OS, const VerdAux &Aux) { OS << Aux.Name.c_str(); });
6629   }
6630 }
6631 
6632 template <class ELFT>
6633 void LLVMELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
6634   ListScope SD(W, "VersionRequirements");
6635   if (!Sec)
6636     return;
6637 
6638   Expected<std::vector<VerNeed>> V = this->getVersionDependencies(*Sec);
6639   if (!V) {
6640     this->reportUniqueWarning(V.takeError());
6641     return;
6642   }
6643 
6644   for (const VerNeed &VN : *V) {
6645     DictScope Entry(W, "Dependency");
6646     W.printNumber("Version", VN.Version);
6647     W.printNumber("Count", VN.Cnt);
6648     W.printString("FileName", VN.File.c_str());
6649 
6650     ListScope L(W, "Entries");
6651     for (const VernAux &Aux : VN.AuxV) {
6652       DictScope Entry(W, "Entry");
6653       W.printNumber("Hash", Aux.Hash);
6654       W.printFlags("Flags", Aux.Flags, makeArrayRef(SymVersionFlags));
6655       W.printNumber("Index", Aux.Other);
6656       W.printString("Name", Aux.Name.c_str());
6657     }
6658   }
6659 }
6660 
6661 template <class ELFT> void LLVMELFDumper<ELFT>::printHashHistograms() {
6662   W.startLine() << "Hash Histogram not implemented!\n";
6663 }
6664 
6665 template <class ELFT> void LLVMELFDumper<ELFT>::printCGProfile() {
6666   ListScope L(W, "CGProfile");
6667   if (!this->DotCGProfileSec)
6668     return;
6669 
6670   Expected<ArrayRef<Elf_CGProfile>> CGProfileOrErr =
6671       this->Obj.template getSectionContentsAsArray<Elf_CGProfile>(
6672           *this->DotCGProfileSec);
6673   if (!CGProfileOrErr) {
6674     this->reportUniqueWarning(
6675         "unable to dump the SHT_LLVM_CALL_GRAPH_PROFILE section: " +
6676         toString(CGProfileOrErr.takeError()));
6677     return;
6678   }
6679 
6680   for (const Elf_CGProfile &CGPE : *CGProfileOrErr) {
6681     DictScope D(W, "CGProfileEntry");
6682     W.printNumber("From", this->getStaticSymbolName(CGPE.cgp_from),
6683                   CGPE.cgp_from);
6684     W.printNumber("To", this->getStaticSymbolName(CGPE.cgp_to),
6685                   CGPE.cgp_to);
6686     W.printNumber("Weight", CGPE.cgp_weight);
6687   }
6688 }
6689 
6690 template <class ELFT> void LLVMELFDumper<ELFT>::printAddrsig() {
6691   ListScope L(W, "Addrsig");
6692   if (!this->DotAddrsigSec)
6693     return;
6694 
6695   Expected<std::vector<uint64_t>> SymsOrErr =
6696       decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
6697   if (!SymsOrErr) {
6698     this->reportUniqueWarning(SymsOrErr.takeError());
6699     return;
6700   }
6701 
6702   for (uint64_t Sym : *SymsOrErr)
6703     W.printNumber("Sym", this->getStaticSymbolName(Sym), Sym);
6704 }
6705 
6706 template <typename ELFT>
6707 static void printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
6708                                   ScopedPrinter &W) {
6709   switch (NoteType) {
6710   default:
6711     return;
6712   case ELF::NT_GNU_ABI_TAG: {
6713     const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
6714     if (!AbiTag.IsValid) {
6715       W.printString("ABI", "<corrupt GNU_ABI_TAG>");
6716     } else {
6717       W.printString("OS", AbiTag.OSName);
6718       W.printString("ABI", AbiTag.ABI);
6719     }
6720     break;
6721   }
6722   case ELF::NT_GNU_BUILD_ID: {
6723     W.printString("Build ID", getGNUBuildId(Desc));
6724     break;
6725   }
6726   case ELF::NT_GNU_GOLD_VERSION:
6727     W.printString("Version", getGNUGoldVersion(Desc));
6728     break;
6729   case ELF::NT_GNU_PROPERTY_TYPE_0:
6730     ListScope D(W, "Property");
6731     for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
6732       W.printString(Property);
6733     break;
6734   }
6735 }
6736 
6737 static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) {
6738   W.printNumber("Page Size", Note.PageSize);
6739   for (const CoreFileMapping &Mapping : Note.Mappings) {
6740     ListScope D(W, "Mapping");
6741     W.printHex("Start", Mapping.Start);
6742     W.printHex("End", Mapping.End);
6743     W.printHex("Offset", Mapping.Offset);
6744     W.printString("Filename", Mapping.Filename);
6745   }
6746 }
6747 
6748 template <class ELFT> void LLVMELFDumper<ELFT>::printNotes() {
6749   ListScope L(W, "Notes");
6750 
6751   std::unique_ptr<DictScope> NoteScope;
6752   auto StartNotes = [&](Optional<StringRef> SecName,
6753                         const typename ELFT::Off Offset,
6754                         const typename ELFT::Addr Size) {
6755     NoteScope = std::make_unique<DictScope>(W, "NoteSection");
6756     W.printString("Name", SecName ? *SecName : "<?>");
6757     W.printHex("Offset", Offset);
6758     W.printHex("Size", Size);
6759   };
6760 
6761   auto EndNotes = [&] { NoteScope.reset(); };
6762 
6763   auto ProcessNote = [&](const Elf_Note &Note) -> Error {
6764     DictScope D2(W, "Note");
6765     StringRef Name = Note.getName();
6766     ArrayRef<uint8_t> Descriptor = Note.getDesc();
6767     Elf_Word Type = Note.getType();
6768 
6769     // Print the note owner/type.
6770     W.printString("Owner", Name);
6771     W.printHex("Data size", Descriptor.size());
6772 
6773     StringRef NoteType =
6774         getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
6775     if (!NoteType.empty())
6776       W.printString("Type", NoteType);
6777     else
6778       W.printString("Type",
6779                     "Unknown (" + to_string(format_hex(Type, 10)) + ")");
6780 
6781     // Print the description, or fallback to printing raw bytes for unknown
6782     // owners.
6783     if (Name == "GNU") {
6784       printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W);
6785     } else if (Name == "AMD") {
6786       const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
6787       if (!N.Type.empty())
6788         W.printString(N.Type, N.Value);
6789     } else if (Name == "AMDGPU") {
6790       const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
6791       if (!N.Type.empty())
6792         W.printString(N.Type, N.Value);
6793     } else if (Name == "CORE") {
6794       if (Type == ELF::NT_FILE) {
6795         DataExtractor DescExtractor(Descriptor,
6796                                     ELFT::TargetEndianness == support::little,
6797                                     sizeof(Elf_Addr));
6798         if (Expected<CoreNote> Note = readCoreNote(DescExtractor))
6799           printCoreNoteLLVMStyle(*Note, W);
6800         else
6801           return Note.takeError();
6802       }
6803     } else if (!Descriptor.empty()) {
6804       W.printBinaryBlock("Description data", Descriptor);
6805     }
6806     return Error::success();
6807   };
6808 
6809   printNotesHelper(*this, StartNotes, ProcessNote, EndNotes);
6810 }
6811 
6812 template <class ELFT> void LLVMELFDumper<ELFT>::printELFLinkerOptions() {
6813   ListScope L(W, "LinkerOptions");
6814 
6815   unsigned I = -1;
6816   for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) {
6817     ++I;
6818     if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS)
6819       continue;
6820 
6821     Expected<ArrayRef<uint8_t>> ContentsOrErr =
6822         this->Obj.getSectionContents(Shdr);
6823     if (!ContentsOrErr) {
6824       this->reportUniqueWarning("unable to read the content of the "
6825                                 "SHT_LLVM_LINKER_OPTIONS section: " +
6826                                 toString(ContentsOrErr.takeError()));
6827       continue;
6828     }
6829     if (ContentsOrErr->empty())
6830       continue;
6831 
6832     if (ContentsOrErr->back() != 0) {
6833       this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " +
6834                                 Twine(I) +
6835                                 " is broken: the "
6836                                 "content is not null-terminated");
6837       continue;
6838     }
6839 
6840     SmallVector<StringRef, 16> Strings;
6841     toStringRef(ContentsOrErr->drop_back()).split(Strings, '\0');
6842     if (Strings.size() % 2 != 0) {
6843       this->reportUniqueWarning(
6844           "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) +
6845           " is broken: an incomplete "
6846           "key-value pair was found. The last possible key was: \"" +
6847           Strings.back() + "\"");
6848       continue;
6849     }
6850 
6851     for (size_t I = 0; I < Strings.size(); I += 2)
6852       W.printString(Strings[I], Strings[I + 1]);
6853   }
6854 }
6855 
6856 template <class ELFT> void LLVMELFDumper<ELFT>::printDependentLibs() {
6857   ListScope L(W, "DependentLibs");
6858   this->printDependentLibsHelper(
6859       [](const Elf_Shdr &) {},
6860       [this](StringRef Lib, uint64_t) { W.printString(Lib); });
6861 }
6862 
6863 template <class ELFT> void LLVMELFDumper<ELFT>::printStackSizes() {
6864   ListScope L(W, "StackSizes");
6865   if (this->Obj.getHeader().e_type == ELF::ET_REL)
6866     this->printRelocatableStackSizes([]() {});
6867   else
6868     this->printNonRelocatableStackSizes([]() {});
6869 }
6870 
6871 template <class ELFT>
6872 void LLVMELFDumper<ELFT>::printStackSizeEntry(uint64_t Size, StringRef FuncName) {
6873   DictScope D(W, "Entry");
6874   W.printString("Function", FuncName);
6875   W.printHex("Size", Size);
6876 }
6877 
6878 template <class ELFT>
6879 void LLVMELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
6880   auto PrintEntry = [&](const Elf_Addr *E) {
6881     W.printHex("Address", Parser.getGotAddress(E));
6882     W.printNumber("Access", Parser.getGotOffset(E));
6883     W.printHex("Initial", *E);
6884   };
6885 
6886   DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT");
6887 
6888   W.printHex("Canonical gp value", Parser.getGp());
6889   {
6890     ListScope RS(W, "Reserved entries");
6891     {
6892       DictScope D(W, "Entry");
6893       PrintEntry(Parser.getGotLazyResolver());
6894       W.printString("Purpose", StringRef("Lazy resolver"));
6895     }
6896 
6897     if (Parser.getGotModulePointer()) {
6898       DictScope D(W, "Entry");
6899       PrintEntry(Parser.getGotModulePointer());
6900       W.printString("Purpose", StringRef("Module pointer (GNU extension)"));
6901     }
6902   }
6903   {
6904     ListScope LS(W, "Local entries");
6905     for (auto &E : Parser.getLocalEntries()) {
6906       DictScope D(W, "Entry");
6907       PrintEntry(&E);
6908     }
6909   }
6910 
6911   if (Parser.IsStatic)
6912     return;
6913 
6914   {
6915     ListScope GS(W, "Global entries");
6916     for (auto &E : Parser.getGlobalEntries()) {
6917       DictScope D(W, "Entry");
6918 
6919       PrintEntry(&E);
6920 
6921       const Elf_Sym &Sym = *Parser.getGotSym(&E);
6922       W.printHex("Value", Sym.st_value);
6923       W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes));
6924 
6925       const unsigned SymIndex = &Sym - this->dynamic_symbols().begin();
6926       DataRegion<Elf_Word> ShndxTable(
6927           (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6928       printSymbolSection(Sym, SymIndex, ShndxTable);
6929 
6930       std::string SymName = this->getFullSymbolName(
6931           Sym, SymIndex, ShndxTable, this->DynamicStringTable, true);
6932       W.printNumber("Name", SymName, Sym.st_name);
6933     }
6934   }
6935 
6936   W.printNumber("Number of TLS and multi-GOT entries",
6937                 uint64_t(Parser.getOtherEntries().size()));
6938 }
6939 
6940 template <class ELFT>
6941 void LLVMELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
6942   auto PrintEntry = [&](const Elf_Addr *E) {
6943     W.printHex("Address", Parser.getPltAddress(E));
6944     W.printHex("Initial", *E);
6945   };
6946 
6947   DictScope GS(W, "PLT GOT");
6948 
6949   {
6950     ListScope RS(W, "Reserved entries");
6951     {
6952       DictScope D(W, "Entry");
6953       PrintEntry(Parser.getPltLazyResolver());
6954       W.printString("Purpose", StringRef("PLT lazy resolver"));
6955     }
6956 
6957     if (auto E = Parser.getPltModulePointer()) {
6958       DictScope D(W, "Entry");
6959       PrintEntry(E);
6960       W.printString("Purpose", StringRef("Module pointer"));
6961     }
6962   }
6963   {
6964     ListScope LS(W, "Entries");
6965     DataRegion<Elf_Word> ShndxTable(
6966         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6967     for (auto &E : Parser.getPltEntries()) {
6968       DictScope D(W, "Entry");
6969       PrintEntry(&E);
6970 
6971       const Elf_Sym &Sym = *Parser.getPltSym(&E);
6972       W.printHex("Value", Sym.st_value);
6973       W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes));
6974       printSymbolSection(Sym, &Sym - this->dynamic_symbols().begin(),
6975                          ShndxTable);
6976 
6977       const Elf_Sym *FirstSym = cantFail(
6978           this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
6979       std::string SymName = this->getFullSymbolName(
6980           Sym, &Sym - FirstSym, ShndxTable, Parser.getPltStrTable(), true);
6981       W.printNumber("Name", SymName, Sym.st_name);
6982     }
6983   }
6984 }
6985 
6986 template <class ELFT> void LLVMELFDumper<ELFT>::printMipsABIFlags() {
6987   const Elf_Mips_ABIFlags<ELFT> *Flags;
6988   if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
6989           getMipsAbiFlagsSection(*this)) {
6990     Flags = *SecOrErr;
6991     if (!Flags) {
6992       W.startLine() << "There is no .MIPS.abiflags section in the file.\n";
6993       return;
6994     }
6995   } else {
6996     this->reportUniqueWarning(SecOrErr.takeError());
6997     return;
6998   }
6999 
7000   raw_ostream &OS = W.getOStream();
7001   DictScope GS(W, "MIPS ABI Flags");
7002 
7003   W.printNumber("Version", Flags->version);
7004   W.startLine() << "ISA: ";
7005   if (Flags->isa_rev <= 1)
7006     OS << format("MIPS%u", Flags->isa_level);
7007   else
7008     OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev);
7009   OS << "\n";
7010   W.printEnum("ISA Extension", Flags->isa_ext, makeArrayRef(ElfMipsISAExtType));
7011   W.printFlags("ASEs", Flags->ases, makeArrayRef(ElfMipsASEFlags));
7012   W.printEnum("FP ABI", Flags->fp_abi, makeArrayRef(ElfMipsFpABIType));
7013   W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size));
7014   W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size));
7015   W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size));
7016   W.printFlags("Flags 1", Flags->flags1, makeArrayRef(ElfMipsFlags1));
7017   W.printHex("Flags 2", Flags->flags2);
7018 }
7019