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