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