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