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