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