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