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