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