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