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