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