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> ElfHeaderAMDGPUFlags[] = {
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_XNACK),
1481   LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_SRAM_ECC)
1482 };
1483 
1484 static const EnumEntry<unsigned> ElfHeaderRISCVFlags[] = {
1485   ENUM_ENT(EF_RISCV_RVC, "RVC"),
1486   ENUM_ENT(EF_RISCV_FLOAT_ABI_SINGLE, "single-float ABI"),
1487   ENUM_ENT(EF_RISCV_FLOAT_ABI_DOUBLE, "double-float ABI"),
1488   ENUM_ENT(EF_RISCV_FLOAT_ABI_QUAD, "quad-float ABI"),
1489   ENUM_ENT(EF_RISCV_RVE, "RVE")
1490 };
1491 
1492 static const EnumEntry<unsigned> ElfSymOtherFlags[] = {
1493   LLVM_READOBJ_ENUM_ENT(ELF, STV_INTERNAL),
1494   LLVM_READOBJ_ENUM_ENT(ELF, STV_HIDDEN),
1495   LLVM_READOBJ_ENUM_ENT(ELF, STV_PROTECTED)
1496 };
1497 
1498 static const EnumEntry<unsigned> ElfMipsSymOtherFlags[] = {
1499   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL),
1500   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT),
1501   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PIC),
1502   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MICROMIPS)
1503 };
1504 
1505 static const EnumEntry<unsigned> ElfAArch64SymOtherFlags[] = {
1506   LLVM_READOBJ_ENUM_ENT(ELF, STO_AARCH64_VARIANT_PCS)
1507 };
1508 
1509 static const EnumEntry<unsigned> ElfMips16SymOtherFlags[] = {
1510   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL),
1511   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT),
1512   LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MIPS16)
1513 };
1514 
1515 static const char *getElfMipsOptionsOdkType(unsigned Odk) {
1516   switch (Odk) {
1517   LLVM_READOBJ_ENUM_CASE(ELF, ODK_NULL);
1518   LLVM_READOBJ_ENUM_CASE(ELF, ODK_REGINFO);
1519   LLVM_READOBJ_ENUM_CASE(ELF, ODK_EXCEPTIONS);
1520   LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAD);
1521   LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWPATCH);
1522   LLVM_READOBJ_ENUM_CASE(ELF, ODK_FILL);
1523   LLVM_READOBJ_ENUM_CASE(ELF, ODK_TAGS);
1524   LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWAND);
1525   LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWOR);
1526   LLVM_READOBJ_ENUM_CASE(ELF, ODK_GP_GROUP);
1527   LLVM_READOBJ_ENUM_CASE(ELF, ODK_IDENT);
1528   LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAGESIZE);
1529   default:
1530     return "Unknown";
1531   }
1532 }
1533 
1534 template <typename ELFT>
1535 std::pair<const typename ELFT::Phdr *, const typename ELFT::Shdr *>
1536 ELFDumper<ELFT>::findDynamic() {
1537   // Try to locate the PT_DYNAMIC header.
1538   const Elf_Phdr *DynamicPhdr = nullptr;
1539   if (Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = Obj.program_headers()) {
1540     for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
1541       if (Phdr.p_type != ELF::PT_DYNAMIC)
1542         continue;
1543       DynamicPhdr = &Phdr;
1544       break;
1545     }
1546   } else {
1547     reportUniqueWarning(
1548         "unable to read program headers to locate the PT_DYNAMIC segment: " +
1549         toString(PhdrsOrErr.takeError()));
1550   }
1551 
1552   // Try to locate the .dynamic section in the sections header table.
1553   const Elf_Shdr *DynamicSec = nullptr;
1554   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
1555     if (Sec.sh_type != ELF::SHT_DYNAMIC)
1556       continue;
1557     DynamicSec = &Sec;
1558     break;
1559   }
1560 
1561   if (DynamicPhdr && ((DynamicPhdr->p_offset + DynamicPhdr->p_filesz >
1562                        ObjF.getMemoryBufferRef().getBufferSize()) ||
1563                       (DynamicPhdr->p_offset + DynamicPhdr->p_filesz <
1564                        DynamicPhdr->p_offset))) {
1565     reportUniqueWarning(
1566         "PT_DYNAMIC segment offset (0x" +
1567         Twine::utohexstr(DynamicPhdr->p_offset) + ") + file size (0x" +
1568         Twine::utohexstr(DynamicPhdr->p_filesz) +
1569         ") exceeds the size of the file (0x" +
1570         Twine::utohexstr(ObjF.getMemoryBufferRef().getBufferSize()) + ")");
1571     // Don't use the broken dynamic header.
1572     DynamicPhdr = nullptr;
1573   }
1574 
1575   if (DynamicPhdr && DynamicSec) {
1576     if (DynamicSec->sh_addr + DynamicSec->sh_size >
1577             DynamicPhdr->p_vaddr + DynamicPhdr->p_memsz ||
1578         DynamicSec->sh_addr < DynamicPhdr->p_vaddr)
1579       reportUniqueWarning(describe(*DynamicSec) +
1580                           " is not contained within the "
1581                           "PT_DYNAMIC segment");
1582 
1583     if (DynamicSec->sh_addr != DynamicPhdr->p_vaddr)
1584       reportUniqueWarning(describe(*DynamicSec) + " is not at the start of "
1585                                                   "PT_DYNAMIC segment");
1586   }
1587 
1588   return std::make_pair(DynamicPhdr, DynamicSec);
1589 }
1590 
1591 template <typename ELFT>
1592 void ELFDumper<ELFT>::loadDynamicTable() {
1593   const Elf_Phdr *DynamicPhdr;
1594   const Elf_Shdr *DynamicSec;
1595   std::tie(DynamicPhdr, DynamicSec) = findDynamic();
1596   if (!DynamicPhdr && !DynamicSec)
1597     return;
1598 
1599   DynRegionInfo FromPhdr(ObjF, *this);
1600   bool IsPhdrTableValid = false;
1601   if (DynamicPhdr) {
1602     // Use cantFail(), because p_offset/p_filesz fields of a PT_DYNAMIC are
1603     // validated in findDynamic() and so createDRI() is not expected to fail.
1604     FromPhdr = cantFail(createDRI(DynamicPhdr->p_offset, DynamicPhdr->p_filesz,
1605                                   sizeof(Elf_Dyn)));
1606     FromPhdr.SizePrintName = "PT_DYNAMIC size";
1607     FromPhdr.EntSizePrintName = "";
1608     IsPhdrTableValid = !FromPhdr.template getAsArrayRef<Elf_Dyn>().empty();
1609   }
1610 
1611   // Locate the dynamic table described in a section header.
1612   // Ignore sh_entsize and use the expected value for entry size explicitly.
1613   // This allows us to dump dynamic sections with a broken sh_entsize
1614   // field.
1615   DynRegionInfo FromSec(ObjF, *this);
1616   bool IsSecTableValid = false;
1617   if (DynamicSec) {
1618     Expected<DynRegionInfo> RegOrErr =
1619         createDRI(DynamicSec->sh_offset, DynamicSec->sh_size, sizeof(Elf_Dyn));
1620     if (RegOrErr) {
1621       FromSec = *RegOrErr;
1622       FromSec.Context = describe(*DynamicSec);
1623       FromSec.EntSizePrintName = "";
1624       IsSecTableValid = !FromSec.template getAsArrayRef<Elf_Dyn>().empty();
1625     } else {
1626       reportUniqueWarning("unable to read the dynamic table from " +
1627                           describe(*DynamicSec) + ": " +
1628                           toString(RegOrErr.takeError()));
1629     }
1630   }
1631 
1632   // When we only have information from one of the SHT_DYNAMIC section header or
1633   // PT_DYNAMIC program header, just use that.
1634   if (!DynamicPhdr || !DynamicSec) {
1635     if ((DynamicPhdr && IsPhdrTableValid) || (DynamicSec && IsSecTableValid)) {
1636       DynamicTable = DynamicPhdr ? FromPhdr : FromSec;
1637       parseDynamicTable();
1638     } else {
1639       reportUniqueWarning("no valid dynamic table was found");
1640     }
1641     return;
1642   }
1643 
1644   // At this point we have tables found from the section header and from the
1645   // dynamic segment. Usually they match, but we have to do sanity checks to
1646   // verify that.
1647 
1648   if (FromPhdr.Addr != FromSec.Addr)
1649     reportUniqueWarning("SHT_DYNAMIC section header and PT_DYNAMIC "
1650                         "program header disagree about "
1651                         "the location of the dynamic table");
1652 
1653   if (!IsPhdrTableValid && !IsSecTableValid) {
1654     reportUniqueWarning("no valid dynamic table was found");
1655     return;
1656   }
1657 
1658   // Information in the PT_DYNAMIC program header has priority over the
1659   // information in a section header.
1660   if (IsPhdrTableValid) {
1661     if (!IsSecTableValid)
1662       reportUniqueWarning(
1663           "SHT_DYNAMIC dynamic table is invalid: PT_DYNAMIC will be used");
1664     DynamicTable = FromPhdr;
1665   } else {
1666     reportUniqueWarning(
1667         "PT_DYNAMIC dynamic table is invalid: SHT_DYNAMIC will be used");
1668     DynamicTable = FromSec;
1669   }
1670 
1671   parseDynamicTable();
1672 }
1673 
1674 template <typename ELFT>
1675 ELFDumper<ELFT>::ELFDumper(const object::ELFObjectFile<ELFT> &O,
1676                            ScopedPrinter &Writer)
1677     : ObjDumper(Writer, O.getFileName()), ObjF(O), Obj(O.getELFFile()),
1678       FileName(O.getFileName()), DynRelRegion(O, *this),
1679       DynRelaRegion(O, *this), DynRelrRegion(O, *this),
1680       DynPLTRelRegion(O, *this), DynSymTabShndxRegion(O, *this),
1681       DynamicTable(O, *this) {
1682   if (!O.IsContentValid())
1683     return;
1684 
1685   typename ELFT::ShdrRange Sections = cantFail(Obj.sections());
1686   for (const Elf_Shdr &Sec : Sections) {
1687     switch (Sec.sh_type) {
1688     case ELF::SHT_SYMTAB:
1689       if (!DotSymtabSec)
1690         DotSymtabSec = &Sec;
1691       break;
1692     case ELF::SHT_DYNSYM:
1693       if (!DotDynsymSec)
1694         DotDynsymSec = &Sec;
1695 
1696       if (!DynSymRegion) {
1697         Expected<DynRegionInfo> RegOrErr =
1698             createDRI(Sec.sh_offset, Sec.sh_size, Sec.sh_entsize);
1699         if (RegOrErr) {
1700           DynSymRegion = *RegOrErr;
1701           DynSymRegion->Context = describe(Sec);
1702 
1703           if (Expected<StringRef> E = Obj.getStringTableForSymtab(Sec))
1704             DynamicStringTable = *E;
1705           else
1706             reportUniqueWarning("unable to get the string table for the " +
1707                                 describe(Sec) + ": " + toString(E.takeError()));
1708         } else {
1709           reportUniqueWarning("unable to read dynamic symbols from " +
1710                               describe(Sec) + ": " +
1711                               toString(RegOrErr.takeError()));
1712         }
1713       }
1714       break;
1715     case ELF::SHT_SYMTAB_SHNDX: {
1716       uint32_t SymtabNdx = Sec.sh_link;
1717       if (SymtabNdx >= Sections.size()) {
1718         reportUniqueWarning(
1719             "unable to get the associated symbol table for " + describe(Sec) +
1720             ": sh_link (" + Twine(SymtabNdx) +
1721             ") is greater than or equal to the total number of sections (" +
1722             Twine(Sections.size()) + ")");
1723         continue;
1724       }
1725 
1726       if (Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
1727               Obj.getSHNDXTable(Sec)) {
1728         if (!ShndxTables.insert({&Sections[SymtabNdx], *ShndxTableOrErr})
1729                  .second)
1730           reportUniqueWarning(
1731               "multiple SHT_SYMTAB_SHNDX sections are linked to " +
1732               describe(Sec));
1733       } else {
1734         reportUniqueWarning(ShndxTableOrErr.takeError());
1735       }
1736       break;
1737     }
1738     case ELF::SHT_GNU_versym:
1739       if (!SymbolVersionSection)
1740         SymbolVersionSection = &Sec;
1741       break;
1742     case ELF::SHT_GNU_verdef:
1743       if (!SymbolVersionDefSection)
1744         SymbolVersionDefSection = &Sec;
1745       break;
1746     case ELF::SHT_GNU_verneed:
1747       if (!SymbolVersionNeedSection)
1748         SymbolVersionNeedSection = &Sec;
1749       break;
1750     case ELF::SHT_LLVM_CALL_GRAPH_PROFILE:
1751       if (!DotCGProfileSec)
1752         DotCGProfileSec = &Sec;
1753       break;
1754     case ELF::SHT_LLVM_ADDRSIG:
1755       if (!DotAddrsigSec)
1756         DotAddrsigSec = &Sec;
1757       break;
1758     }
1759   }
1760 
1761   loadDynamicTable();
1762 }
1763 
1764 template <typename ELFT> void ELFDumper<ELFT>::parseDynamicTable() {
1765   auto toMappedAddr = [&](uint64_t Tag, uint64_t VAddr) -> const uint8_t * {
1766     auto MappedAddrOrError = Obj.toMappedAddr(VAddr, [&](const Twine &Msg) {
1767       this->reportUniqueWarning(Msg);
1768       return Error::success();
1769     });
1770     if (!MappedAddrOrError) {
1771       this->reportUniqueWarning("unable to parse DT_" +
1772                                 Obj.getDynamicTagAsString(Tag) + ": " +
1773                                 llvm::toString(MappedAddrOrError.takeError()));
1774       return nullptr;
1775     }
1776     return MappedAddrOrError.get();
1777   };
1778 
1779   const char *StringTableBegin = nullptr;
1780   uint64_t StringTableSize = 0;
1781   Optional<DynRegionInfo> DynSymFromTable;
1782   for (const Elf_Dyn &Dyn : dynamic_table()) {
1783     switch (Dyn.d_tag) {
1784     case ELF::DT_HASH:
1785       HashTable = reinterpret_cast<const Elf_Hash *>(
1786           toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
1787       break;
1788     case ELF::DT_GNU_HASH:
1789       GnuHashTable = reinterpret_cast<const Elf_GnuHash *>(
1790           toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
1791       break;
1792     case ELF::DT_STRTAB:
1793       StringTableBegin = reinterpret_cast<const char *>(
1794           toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
1795       break;
1796     case ELF::DT_STRSZ:
1797       StringTableSize = Dyn.getVal();
1798       break;
1799     case ELF::DT_SYMTAB: {
1800       // If we can't map the DT_SYMTAB value to an address (e.g. when there are
1801       // no program headers), we ignore its value.
1802       if (const uint8_t *VA = toMappedAddr(Dyn.getTag(), Dyn.getPtr())) {
1803         DynSymFromTable.emplace(ObjF, *this);
1804         DynSymFromTable->Addr = VA;
1805         DynSymFromTable->EntSize = sizeof(Elf_Sym);
1806         DynSymFromTable->EntSizePrintName = "";
1807       }
1808       break;
1809     }
1810     case ELF::DT_SYMENT: {
1811       uint64_t Val = Dyn.getVal();
1812       if (Val != sizeof(Elf_Sym))
1813         this->reportUniqueWarning("DT_SYMENT value of 0x" +
1814                                   Twine::utohexstr(Val) +
1815                                   " is not the size of a symbol (0x" +
1816                                   Twine::utohexstr(sizeof(Elf_Sym)) + ")");
1817       break;
1818     }
1819     case ELF::DT_RELA:
1820       DynRelaRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
1821       break;
1822     case ELF::DT_RELASZ:
1823       DynRelaRegion.Size = Dyn.getVal();
1824       DynRelaRegion.SizePrintName = "DT_RELASZ value";
1825       break;
1826     case ELF::DT_RELAENT:
1827       DynRelaRegion.EntSize = Dyn.getVal();
1828       DynRelaRegion.EntSizePrintName = "DT_RELAENT value";
1829       break;
1830     case ELF::DT_SONAME:
1831       SONameOffset = Dyn.getVal();
1832       break;
1833     case ELF::DT_REL:
1834       DynRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
1835       break;
1836     case ELF::DT_RELSZ:
1837       DynRelRegion.Size = Dyn.getVal();
1838       DynRelRegion.SizePrintName = "DT_RELSZ value";
1839       break;
1840     case ELF::DT_RELENT:
1841       DynRelRegion.EntSize = Dyn.getVal();
1842       DynRelRegion.EntSizePrintName = "DT_RELENT value";
1843       break;
1844     case ELF::DT_RELR:
1845     case ELF::DT_ANDROID_RELR:
1846       DynRelrRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
1847       break;
1848     case ELF::DT_RELRSZ:
1849     case ELF::DT_ANDROID_RELRSZ:
1850       DynRelrRegion.Size = Dyn.getVal();
1851       DynRelrRegion.SizePrintName = Dyn.d_tag == ELF::DT_RELRSZ
1852                                         ? "DT_RELRSZ value"
1853                                         : "DT_ANDROID_RELRSZ value";
1854       break;
1855     case ELF::DT_RELRENT:
1856     case ELF::DT_ANDROID_RELRENT:
1857       DynRelrRegion.EntSize = Dyn.getVal();
1858       DynRelrRegion.EntSizePrintName = Dyn.d_tag == ELF::DT_RELRENT
1859                                            ? "DT_RELRENT value"
1860                                            : "DT_ANDROID_RELRENT value";
1861       break;
1862     case ELF::DT_PLTREL:
1863       if (Dyn.getVal() == DT_REL)
1864         DynPLTRelRegion.EntSize = sizeof(Elf_Rel);
1865       else if (Dyn.getVal() == DT_RELA)
1866         DynPLTRelRegion.EntSize = sizeof(Elf_Rela);
1867       else
1868         reportUniqueWarning(Twine("unknown DT_PLTREL value of ") +
1869                             Twine((uint64_t)Dyn.getVal()));
1870       DynPLTRelRegion.EntSizePrintName = "PLTREL entry size";
1871       break;
1872     case ELF::DT_JMPREL:
1873       DynPLTRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
1874       break;
1875     case ELF::DT_PLTRELSZ:
1876       DynPLTRelRegion.Size = Dyn.getVal();
1877       DynPLTRelRegion.SizePrintName = "DT_PLTRELSZ value";
1878       break;
1879     case ELF::DT_SYMTAB_SHNDX:
1880       DynSymTabShndxRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
1881       DynSymTabShndxRegion.EntSize = sizeof(Elf_Word);
1882       break;
1883     }
1884   }
1885 
1886   if (StringTableBegin) {
1887     const uint64_t FileSize = Obj.getBufSize();
1888     const uint64_t Offset = (const uint8_t *)StringTableBegin - Obj.base();
1889     if (StringTableSize > FileSize - Offset)
1890       reportUniqueWarning(
1891           "the dynamic string table at 0x" + Twine::utohexstr(Offset) +
1892           " goes past the end of the file (0x" + Twine::utohexstr(FileSize) +
1893           ") with DT_STRSZ = 0x" + Twine::utohexstr(StringTableSize));
1894     else
1895       DynamicStringTable = StringRef(StringTableBegin, StringTableSize);
1896   }
1897 
1898   const bool IsHashTableSupported = getHashTableEntSize() == 4;
1899   if (DynSymRegion) {
1900     // Often we find the information about the dynamic symbol table
1901     // location in the SHT_DYNSYM section header. However, the value in
1902     // DT_SYMTAB has priority, because it is used by dynamic loaders to
1903     // locate .dynsym at runtime. The location we find in the section header
1904     // and the location we find here should match.
1905     if (DynSymFromTable && DynSymFromTable->Addr != DynSymRegion->Addr)
1906       reportUniqueWarning(
1907           createError("SHT_DYNSYM section header and DT_SYMTAB disagree about "
1908                       "the location of the dynamic symbol table"));
1909 
1910     // According to the ELF gABI: "The number of symbol table entries should
1911     // equal nchain". Check to see if the DT_HASH hash table nchain value
1912     // conflicts with the number of symbols in the dynamic symbol table
1913     // according to the section header.
1914     if (HashTable && IsHashTableSupported) {
1915       if (DynSymRegion->EntSize == 0)
1916         reportUniqueWarning("SHT_DYNSYM section has sh_entsize == 0");
1917       else if (HashTable->nchain != DynSymRegion->Size / DynSymRegion->EntSize)
1918         reportUniqueWarning(
1919             "hash table nchain (" + Twine(HashTable->nchain) +
1920             ") differs from symbol count derived from SHT_DYNSYM section "
1921             "header (" +
1922             Twine(DynSymRegion->Size / DynSymRegion->EntSize) + ")");
1923     }
1924   }
1925 
1926   // Delay the creation of the actual dynamic symbol table until now, so that
1927   // checks can always be made against the section header-based properties,
1928   // without worrying about tag order.
1929   if (DynSymFromTable) {
1930     if (!DynSymRegion) {
1931       DynSymRegion = DynSymFromTable;
1932     } else {
1933       DynSymRegion->Addr = DynSymFromTable->Addr;
1934       DynSymRegion->EntSize = DynSymFromTable->EntSize;
1935       DynSymRegion->EntSizePrintName = DynSymFromTable->EntSizePrintName;
1936     }
1937   }
1938 
1939   // Derive the dynamic symbol table size from the DT_HASH hash table, if
1940   // present.
1941   if (HashTable && IsHashTableSupported && DynSymRegion) {
1942     const uint64_t FileSize = Obj.getBufSize();
1943     const uint64_t DerivedSize =
1944         (uint64_t)HashTable->nchain * DynSymRegion->EntSize;
1945     const uint64_t Offset = (const uint8_t *)DynSymRegion->Addr - Obj.base();
1946     if (DerivedSize > FileSize - Offset)
1947       reportUniqueWarning(
1948           "the size (0x" + Twine::utohexstr(DerivedSize) +
1949           ") of the dynamic symbol table at 0x" + Twine::utohexstr(Offset) +
1950           ", derived from the hash table, goes past the end of the file (0x" +
1951           Twine::utohexstr(FileSize) + ") and will be ignored");
1952     else
1953       DynSymRegion->Size = HashTable->nchain * DynSymRegion->EntSize;
1954   }
1955 }
1956 
1957 template <typename ELFT> void ELFDumper<ELFT>::printVersionInfo() {
1958   // Dump version symbol section.
1959   printVersionSymbolSection(SymbolVersionSection);
1960 
1961   // Dump version definition section.
1962   printVersionDefinitionSection(SymbolVersionDefSection);
1963 
1964   // Dump version dependency section.
1965   printVersionDependencySection(SymbolVersionNeedSection);
1966 }
1967 
1968 #define LLVM_READOBJ_DT_FLAG_ENT(prefix, enum)                                 \
1969   { #enum, prefix##_##enum }
1970 
1971 static const EnumEntry<unsigned> ElfDynamicDTFlags[] = {
1972   LLVM_READOBJ_DT_FLAG_ENT(DF, ORIGIN),
1973   LLVM_READOBJ_DT_FLAG_ENT(DF, SYMBOLIC),
1974   LLVM_READOBJ_DT_FLAG_ENT(DF, TEXTREL),
1975   LLVM_READOBJ_DT_FLAG_ENT(DF, BIND_NOW),
1976   LLVM_READOBJ_DT_FLAG_ENT(DF, STATIC_TLS)
1977 };
1978 
1979 static const EnumEntry<unsigned> ElfDynamicDTFlags1[] = {
1980   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOW),
1981   LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAL),
1982   LLVM_READOBJ_DT_FLAG_ENT(DF_1, GROUP),
1983   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODELETE),
1984   LLVM_READOBJ_DT_FLAG_ENT(DF_1, LOADFLTR),
1985   LLVM_READOBJ_DT_FLAG_ENT(DF_1, INITFIRST),
1986   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOOPEN),
1987   LLVM_READOBJ_DT_FLAG_ENT(DF_1, ORIGIN),
1988   LLVM_READOBJ_DT_FLAG_ENT(DF_1, DIRECT),
1989   LLVM_READOBJ_DT_FLAG_ENT(DF_1, TRANS),
1990   LLVM_READOBJ_DT_FLAG_ENT(DF_1, INTERPOSE),
1991   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODEFLIB),
1992   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODUMP),
1993   LLVM_READOBJ_DT_FLAG_ENT(DF_1, CONFALT),
1994   LLVM_READOBJ_DT_FLAG_ENT(DF_1, ENDFILTEE),
1995   LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELDNE),
1996   LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELPND),
1997   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODIRECT),
1998   LLVM_READOBJ_DT_FLAG_ENT(DF_1, IGNMULDEF),
1999   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOKSYMS),
2000   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOHDR),
2001   LLVM_READOBJ_DT_FLAG_ENT(DF_1, EDITED),
2002   LLVM_READOBJ_DT_FLAG_ENT(DF_1, NORELOC),
2003   LLVM_READOBJ_DT_FLAG_ENT(DF_1, SYMINTPOSE),
2004   LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAUDIT),
2005   LLVM_READOBJ_DT_FLAG_ENT(DF_1, SINGLETON),
2006   LLVM_READOBJ_DT_FLAG_ENT(DF_1, PIE),
2007 };
2008 
2009 static const EnumEntry<unsigned> ElfDynamicDTMipsFlags[] = {
2010   LLVM_READOBJ_DT_FLAG_ENT(RHF, NONE),
2011   LLVM_READOBJ_DT_FLAG_ENT(RHF, QUICKSTART),
2012   LLVM_READOBJ_DT_FLAG_ENT(RHF, NOTPOT),
2013   LLVM_READOBJ_DT_FLAG_ENT(RHS, NO_LIBRARY_REPLACEMENT),
2014   LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_MOVE),
2015   LLVM_READOBJ_DT_FLAG_ENT(RHF, SGI_ONLY),
2016   LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_INIT),
2017   LLVM_READOBJ_DT_FLAG_ENT(RHF, DELTA_C_PLUS_PLUS),
2018   LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_START_INIT),
2019   LLVM_READOBJ_DT_FLAG_ENT(RHF, PIXIE),
2020   LLVM_READOBJ_DT_FLAG_ENT(RHF, DEFAULT_DELAY_LOAD),
2021   LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTART),
2022   LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTARTED),
2023   LLVM_READOBJ_DT_FLAG_ENT(RHF, CORD),
2024   LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_UNRES_UNDEF),
2025   LLVM_READOBJ_DT_FLAG_ENT(RHF, RLD_ORDER_SAFE)
2026 };
2027 
2028 #undef LLVM_READOBJ_DT_FLAG_ENT
2029 
2030 template <typename T, typename TFlag>
2031 void printFlags(T Value, ArrayRef<EnumEntry<TFlag>> Flags, raw_ostream &OS) {
2032   SmallVector<EnumEntry<TFlag>, 10> SetFlags;
2033   for (const EnumEntry<TFlag> &Flag : Flags)
2034     if (Flag.Value != 0 && (Value & Flag.Value) == Flag.Value)
2035       SetFlags.push_back(Flag);
2036 
2037   for (const EnumEntry<TFlag> &Flag : SetFlags)
2038     OS << Flag.Name << " ";
2039 }
2040 
2041 template <class ELFT>
2042 const typename ELFT::Shdr *
2043 ELFDumper<ELFT>::findSectionByName(StringRef Name) const {
2044   for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
2045     if (Expected<StringRef> NameOrErr = Obj.getSectionName(Shdr)) {
2046       if (*NameOrErr == Name)
2047         return &Shdr;
2048     } else {
2049       reportUniqueWarning("unable to read the name of " + describe(Shdr) +
2050                           ": " + toString(NameOrErr.takeError()));
2051     }
2052   }
2053   return nullptr;
2054 }
2055 
2056 template <class ELFT>
2057 std::string ELFDumper<ELFT>::getDynamicEntry(uint64_t Type,
2058                                              uint64_t Value) const {
2059   auto FormatHexValue = [](uint64_t V) {
2060     std::string Str;
2061     raw_string_ostream OS(Str);
2062     const char *ConvChar =
2063         (opts::Output == opts::GNU) ? "0x%" PRIx64 : "0x%" PRIX64;
2064     OS << format(ConvChar, V);
2065     return OS.str();
2066   };
2067 
2068   auto FormatFlags = [](uint64_t V,
2069                         llvm::ArrayRef<llvm::EnumEntry<unsigned int>> Array) {
2070     std::string Str;
2071     raw_string_ostream OS(Str);
2072     printFlags(V, Array, OS);
2073     return OS.str();
2074   };
2075 
2076   // Handle custom printing of architecture specific tags
2077   switch (Obj.getHeader().e_machine) {
2078   case EM_AARCH64:
2079     switch (Type) {
2080     case DT_AARCH64_BTI_PLT:
2081     case DT_AARCH64_PAC_PLT:
2082     case DT_AARCH64_VARIANT_PCS:
2083       return std::to_string(Value);
2084     default:
2085       break;
2086     }
2087     break;
2088   case EM_HEXAGON:
2089     switch (Type) {
2090     case DT_HEXAGON_VER:
2091       return std::to_string(Value);
2092     case DT_HEXAGON_SYMSZ:
2093     case DT_HEXAGON_PLT:
2094       return FormatHexValue(Value);
2095     default:
2096       break;
2097     }
2098     break;
2099   case EM_MIPS:
2100     switch (Type) {
2101     case DT_MIPS_RLD_VERSION:
2102     case DT_MIPS_LOCAL_GOTNO:
2103     case DT_MIPS_SYMTABNO:
2104     case DT_MIPS_UNREFEXTNO:
2105       return std::to_string(Value);
2106     case DT_MIPS_TIME_STAMP:
2107     case DT_MIPS_ICHECKSUM:
2108     case DT_MIPS_IVERSION:
2109     case DT_MIPS_BASE_ADDRESS:
2110     case DT_MIPS_MSYM:
2111     case DT_MIPS_CONFLICT:
2112     case DT_MIPS_LIBLIST:
2113     case DT_MIPS_CONFLICTNO:
2114     case DT_MIPS_LIBLISTNO:
2115     case DT_MIPS_GOTSYM:
2116     case DT_MIPS_HIPAGENO:
2117     case DT_MIPS_RLD_MAP:
2118     case DT_MIPS_DELTA_CLASS:
2119     case DT_MIPS_DELTA_CLASS_NO:
2120     case DT_MIPS_DELTA_INSTANCE:
2121     case DT_MIPS_DELTA_RELOC:
2122     case DT_MIPS_DELTA_RELOC_NO:
2123     case DT_MIPS_DELTA_SYM:
2124     case DT_MIPS_DELTA_SYM_NO:
2125     case DT_MIPS_DELTA_CLASSSYM:
2126     case DT_MIPS_DELTA_CLASSSYM_NO:
2127     case DT_MIPS_CXX_FLAGS:
2128     case DT_MIPS_PIXIE_INIT:
2129     case DT_MIPS_SYMBOL_LIB:
2130     case DT_MIPS_LOCALPAGE_GOTIDX:
2131     case DT_MIPS_LOCAL_GOTIDX:
2132     case DT_MIPS_HIDDEN_GOTIDX:
2133     case DT_MIPS_PROTECTED_GOTIDX:
2134     case DT_MIPS_OPTIONS:
2135     case DT_MIPS_INTERFACE:
2136     case DT_MIPS_DYNSTR_ALIGN:
2137     case DT_MIPS_INTERFACE_SIZE:
2138     case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
2139     case DT_MIPS_PERF_SUFFIX:
2140     case DT_MIPS_COMPACT_SIZE:
2141     case DT_MIPS_GP_VALUE:
2142     case DT_MIPS_AUX_DYNAMIC:
2143     case DT_MIPS_PLTGOT:
2144     case DT_MIPS_RWPLT:
2145     case DT_MIPS_RLD_MAP_REL:
2146       return FormatHexValue(Value);
2147     case DT_MIPS_FLAGS:
2148       return FormatFlags(Value, makeArrayRef(ElfDynamicDTMipsFlags));
2149     default:
2150       break;
2151     }
2152     break;
2153   default:
2154     break;
2155   }
2156 
2157   switch (Type) {
2158   case DT_PLTREL:
2159     if (Value == DT_REL)
2160       return "REL";
2161     if (Value == DT_RELA)
2162       return "RELA";
2163     LLVM_FALLTHROUGH;
2164   case DT_PLTGOT:
2165   case DT_HASH:
2166   case DT_STRTAB:
2167   case DT_SYMTAB:
2168   case DT_RELA:
2169   case DT_INIT:
2170   case DT_FINI:
2171   case DT_REL:
2172   case DT_JMPREL:
2173   case DT_INIT_ARRAY:
2174   case DT_FINI_ARRAY:
2175   case DT_PREINIT_ARRAY:
2176   case DT_DEBUG:
2177   case DT_VERDEF:
2178   case DT_VERNEED:
2179   case DT_VERSYM:
2180   case DT_GNU_HASH:
2181   case DT_NULL:
2182     return FormatHexValue(Value);
2183   case DT_RELACOUNT:
2184   case DT_RELCOUNT:
2185   case DT_VERDEFNUM:
2186   case DT_VERNEEDNUM:
2187     return std::to_string(Value);
2188   case DT_PLTRELSZ:
2189   case DT_RELASZ:
2190   case DT_RELAENT:
2191   case DT_STRSZ:
2192   case DT_SYMENT:
2193   case DT_RELSZ:
2194   case DT_RELENT:
2195   case DT_INIT_ARRAYSZ:
2196   case DT_FINI_ARRAYSZ:
2197   case DT_PREINIT_ARRAYSZ:
2198   case DT_ANDROID_RELSZ:
2199   case DT_ANDROID_RELASZ:
2200     return std::to_string(Value) + " (bytes)";
2201   case DT_NEEDED:
2202   case DT_SONAME:
2203   case DT_AUXILIARY:
2204   case DT_USED:
2205   case DT_FILTER:
2206   case DT_RPATH:
2207   case DT_RUNPATH: {
2208     const std::map<uint64_t, const char *> TagNames = {
2209         {DT_NEEDED, "Shared library"},       {DT_SONAME, "Library soname"},
2210         {DT_AUXILIARY, "Auxiliary library"}, {DT_USED, "Not needed object"},
2211         {DT_FILTER, "Filter library"},       {DT_RPATH, "Library rpath"},
2212         {DT_RUNPATH, "Library runpath"},
2213     };
2214 
2215     return (Twine(TagNames.at(Type)) + ": [" + getDynamicString(Value) + "]")
2216         .str();
2217   }
2218   case DT_FLAGS:
2219     return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags));
2220   case DT_FLAGS_1:
2221     return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags1));
2222   default:
2223     return FormatHexValue(Value);
2224   }
2225 }
2226 
2227 template <class ELFT>
2228 StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const {
2229   if (DynamicStringTable.empty() && !DynamicStringTable.data()) {
2230     reportUniqueWarning("string table was not found");
2231     return "<?>";
2232   }
2233 
2234   auto WarnAndReturn = [this](const Twine &Msg, uint64_t Offset) {
2235     reportUniqueWarning("string table at offset 0x" + Twine::utohexstr(Offset) +
2236                         Msg);
2237     return "<?>";
2238   };
2239 
2240   const uint64_t FileSize = Obj.getBufSize();
2241   const uint64_t Offset =
2242       (const uint8_t *)DynamicStringTable.data() - Obj.base();
2243   if (DynamicStringTable.size() > FileSize - Offset)
2244     return WarnAndReturn(" with size 0x" +
2245                              Twine::utohexstr(DynamicStringTable.size()) +
2246                              " goes past the end of the file (0x" +
2247                              Twine::utohexstr(FileSize) + ")",
2248                          Offset);
2249 
2250   if (Value >= DynamicStringTable.size())
2251     return WarnAndReturn(
2252         ": unable to read the string at 0x" + Twine::utohexstr(Offset + Value) +
2253             ": it goes past the end of the table (0x" +
2254             Twine::utohexstr(Offset + DynamicStringTable.size()) + ")",
2255         Offset);
2256 
2257   if (DynamicStringTable.back() != '\0')
2258     return WarnAndReturn(": unable to read the string at 0x" +
2259                              Twine::utohexstr(Offset + Value) +
2260                              ": the string table is not null-terminated",
2261                          Offset);
2262 
2263   return DynamicStringTable.data() + Value;
2264 }
2265 
2266 template <class ELFT> void ELFDumper<ELFT>::printUnwindInfo() {
2267   DwarfCFIEH::PrinterContext<ELFT> Ctx(W, ObjF);
2268   Ctx.printUnwindInformation();
2269 }
2270 
2271 // The namespace is needed to fix the compilation with GCC older than 7.0+.
2272 namespace {
2273 template <> void ELFDumper<ELF32LE>::printUnwindInfo() {
2274   if (Obj.getHeader().e_machine == EM_ARM) {
2275     ARM::EHABI::PrinterContext<ELF32LE> Ctx(W, Obj, ObjF.getFileName(),
2276                                             DotSymtabSec);
2277     Ctx.PrintUnwindInformation();
2278   }
2279   DwarfCFIEH::PrinterContext<ELF32LE> Ctx(W, ObjF);
2280   Ctx.printUnwindInformation();
2281 }
2282 } // namespace
2283 
2284 template <class ELFT> void ELFDumper<ELFT>::printNeededLibraries() {
2285   ListScope D(W, "NeededLibraries");
2286 
2287   std::vector<StringRef> Libs;
2288   for (const auto &Entry : dynamic_table())
2289     if (Entry.d_tag == ELF::DT_NEEDED)
2290       Libs.push_back(getDynamicString(Entry.d_un.d_val));
2291 
2292   llvm::sort(Libs);
2293 
2294   for (StringRef L : Libs)
2295     W.startLine() << L << "\n";
2296 }
2297 
2298 template <class ELFT>
2299 static Error checkHashTable(const ELFDumper<ELFT> &Dumper,
2300                             const typename ELFT::Hash *H,
2301                             bool *IsHeaderValid = nullptr) {
2302   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
2303   const uint64_t SecOffset = (const uint8_t *)H - Obj.base();
2304   if (Dumper.getHashTableEntSize() == 8) {
2305     auto It = llvm::find_if(ElfMachineType, [&](const EnumEntry<unsigned> &E) {
2306       return E.Value == Obj.getHeader().e_machine;
2307     });
2308     if (IsHeaderValid)
2309       *IsHeaderValid = false;
2310     return createError("the hash table at 0x" + Twine::utohexstr(SecOffset) +
2311                        " is not supported: it contains non-standard 8 "
2312                        "byte entries on " +
2313                        It->AltName + " platform");
2314   }
2315 
2316   auto MakeError = [&](const Twine &Msg = "") {
2317     return createError("the hash table at offset 0x" +
2318                        Twine::utohexstr(SecOffset) +
2319                        " goes past the end of the file (0x" +
2320                        Twine::utohexstr(Obj.getBufSize()) + ")" + Msg);
2321   };
2322 
2323   // Each SHT_HASH section starts from two 32-bit fields: nbucket and nchain.
2324   const unsigned HeaderSize = 2 * sizeof(typename ELFT::Word);
2325 
2326   if (IsHeaderValid)
2327     *IsHeaderValid = Obj.getBufSize() - SecOffset >= HeaderSize;
2328 
2329   if (Obj.getBufSize() - SecOffset < HeaderSize)
2330     return MakeError();
2331 
2332   if (Obj.getBufSize() - SecOffset - HeaderSize <
2333       ((uint64_t)H->nbucket + H->nchain) * sizeof(typename ELFT::Word))
2334     return MakeError(", nbucket = " + Twine(H->nbucket) +
2335                      ", nchain = " + Twine(H->nchain));
2336   return Error::success();
2337 }
2338 
2339 template <class ELFT>
2340 static Error checkGNUHashTable(const ELFFile<ELFT> &Obj,
2341                                const typename ELFT::GnuHash *GnuHashTable,
2342                                bool *IsHeaderValid = nullptr) {
2343   const uint8_t *TableData = reinterpret_cast<const uint8_t *>(GnuHashTable);
2344   assert(TableData >= Obj.base() && TableData < Obj.base() + Obj.getBufSize() &&
2345          "GnuHashTable must always point to a location inside the file");
2346 
2347   uint64_t TableOffset = TableData - Obj.base();
2348   if (IsHeaderValid)
2349     *IsHeaderValid = TableOffset + /*Header size:*/ 16 < Obj.getBufSize();
2350   if (TableOffset + 16 + (uint64_t)GnuHashTable->nbuckets * 4 +
2351           (uint64_t)GnuHashTable->maskwords * sizeof(typename ELFT::Off) >=
2352       Obj.getBufSize())
2353     return createError("unable to dump the SHT_GNU_HASH "
2354                        "section at 0x" +
2355                        Twine::utohexstr(TableOffset) +
2356                        ": it goes past the end of the file");
2357   return Error::success();
2358 }
2359 
2360 template <typename ELFT> void ELFDumper<ELFT>::printHashTable() {
2361   DictScope D(W, "HashTable");
2362   if (!HashTable)
2363     return;
2364 
2365   bool IsHeaderValid;
2366   Error Err = checkHashTable(*this, HashTable, &IsHeaderValid);
2367   if (IsHeaderValid) {
2368     W.printNumber("Num Buckets", HashTable->nbucket);
2369     W.printNumber("Num Chains", HashTable->nchain);
2370   }
2371 
2372   if (Err) {
2373     reportUniqueWarning(std::move(Err));
2374     return;
2375   }
2376 
2377   W.printList("Buckets", HashTable->buckets());
2378   W.printList("Chains", HashTable->chains());
2379 }
2380 
2381 template <class ELFT>
2382 static Expected<ArrayRef<typename ELFT::Word>>
2383 getGnuHashTableChains(Optional<DynRegionInfo> DynSymRegion,
2384                       const typename ELFT::GnuHash *GnuHashTable) {
2385   if (!DynSymRegion)
2386     return createError("no dynamic symbol table found");
2387 
2388   ArrayRef<typename ELFT::Sym> DynSymTable =
2389       DynSymRegion->template getAsArrayRef<typename ELFT::Sym>();
2390   size_t NumSyms = DynSymTable.size();
2391   if (!NumSyms)
2392     return createError("the dynamic symbol table is empty");
2393 
2394   if (GnuHashTable->symndx < NumSyms)
2395     return GnuHashTable->values(NumSyms);
2396 
2397   // A normal empty GNU hash table section produced by linker might have
2398   // symndx set to the number of dynamic symbols + 1 (for the zero symbol)
2399   // and have dummy null values in the Bloom filter and in the buckets
2400   // vector (or no values at all). It happens because the value of symndx is not
2401   // important for dynamic loaders when the GNU hash table is empty. They just
2402   // skip the whole object during symbol lookup. In such cases, the symndx value
2403   // is irrelevant and we should not report a warning.
2404   ArrayRef<typename ELFT::Word> Buckets = GnuHashTable->buckets();
2405   if (!llvm::all_of(Buckets, [](typename ELFT::Word V) { return V == 0; }))
2406     return createError(
2407         "the first hashed symbol index (" + Twine(GnuHashTable->symndx) +
2408         ") is greater than or equal to the number of dynamic symbols (" +
2409         Twine(NumSyms) + ")");
2410   // There is no way to represent an array of (dynamic symbols count - symndx)
2411   // length.
2412   return ArrayRef<typename ELFT::Word>();
2413 }
2414 
2415 template <typename ELFT>
2416 void ELFDumper<ELFT>::printGnuHashTable() {
2417   DictScope D(W, "GnuHashTable");
2418   if (!GnuHashTable)
2419     return;
2420 
2421   bool IsHeaderValid;
2422   Error Err = checkGNUHashTable<ELFT>(Obj, GnuHashTable, &IsHeaderValid);
2423   if (IsHeaderValid) {
2424     W.printNumber("Num Buckets", GnuHashTable->nbuckets);
2425     W.printNumber("First Hashed Symbol Index", GnuHashTable->symndx);
2426     W.printNumber("Num Mask Words", GnuHashTable->maskwords);
2427     W.printNumber("Shift Count", GnuHashTable->shift2);
2428   }
2429 
2430   if (Err) {
2431     reportUniqueWarning(std::move(Err));
2432     return;
2433   }
2434 
2435   ArrayRef<typename ELFT::Off> BloomFilter = GnuHashTable->filter();
2436   W.printHexList("Bloom Filter", BloomFilter);
2437 
2438   ArrayRef<Elf_Word> Buckets = GnuHashTable->buckets();
2439   W.printList("Buckets", Buckets);
2440 
2441   Expected<ArrayRef<Elf_Word>> Chains =
2442       getGnuHashTableChains<ELFT>(DynSymRegion, GnuHashTable);
2443   if (!Chains) {
2444     reportUniqueWarning("unable to dump 'Values' for the SHT_GNU_HASH "
2445                         "section: " +
2446                         toString(Chains.takeError()));
2447     return;
2448   }
2449 
2450   W.printHexList("Values", *Chains);
2451 }
2452 
2453 template <typename ELFT> void ELFDumper<ELFT>::printLoadName() {
2454   StringRef SOName = "<Not found>";
2455   if (SONameOffset)
2456     SOName = getDynamicString(*SONameOffset);
2457   W.printString("LoadName", SOName);
2458 }
2459 
2460 template <class ELFT> void ELFDumper<ELFT>::printArchSpecificInfo() {
2461   switch (Obj.getHeader().e_machine) {
2462   case EM_ARM:
2463   case EM_RISCV:
2464     printAttributes();
2465     break;
2466   case EM_MIPS: {
2467     printMipsABIFlags();
2468     printMipsOptions();
2469     printMipsReginfo();
2470     MipsGOTParser<ELFT> Parser(*this);
2471     if (Error E = Parser.findGOT(dynamic_table(), dynamic_symbols()))
2472       reportUniqueWarning(std::move(E));
2473     else if (!Parser.isGotEmpty())
2474       printMipsGOT(Parser);
2475 
2476     if (Error E = Parser.findPLT(dynamic_table()))
2477       reportUniqueWarning(std::move(E));
2478     else if (!Parser.isPltEmpty())
2479       printMipsPLT(Parser);
2480     break;
2481   }
2482   default:
2483     break;
2484   }
2485 }
2486 
2487 template <class ELFT> void ELFDumper<ELFT>::printAttributes() {
2488   if (!Obj.isLE()) {
2489     W.startLine() << "Attributes not implemented.\n";
2490     return;
2491   }
2492 
2493   const unsigned Machine = Obj.getHeader().e_machine;
2494   assert((Machine == EM_ARM || Machine == EM_RISCV) &&
2495          "Attributes not implemented.");
2496 
2497   DictScope BA(W, "BuildAttributes");
2498   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
2499     if (Sec.sh_type != ELF::SHT_ARM_ATTRIBUTES &&
2500         Sec.sh_type != ELF::SHT_RISCV_ATTRIBUTES)
2501       continue;
2502 
2503     ArrayRef<uint8_t> Contents;
2504     if (Expected<ArrayRef<uint8_t>> ContentOrErr =
2505             Obj.getSectionContents(Sec)) {
2506       Contents = *ContentOrErr;
2507       if (Contents.empty()) {
2508         reportUniqueWarning("the " + describe(Sec) + " is empty");
2509         continue;
2510       }
2511     } else {
2512       reportUniqueWarning("unable to read the content of the " + describe(Sec) +
2513                           ": " + toString(ContentOrErr.takeError()));
2514       continue;
2515     }
2516 
2517     W.printHex("FormatVersion", Contents[0]);
2518 
2519     auto ParseAttrubutes = [&]() {
2520       if (Machine == EM_ARM)
2521         return ARMAttributeParser(&W).parse(Contents, support::little);
2522       return RISCVAttributeParser(&W).parse(Contents, support::little);
2523     };
2524 
2525     if (Error E = ParseAttrubutes())
2526       reportUniqueWarning("unable to dump attributes from the " +
2527                           describe(Sec) + ": " + toString(std::move(E)));
2528   }
2529 }
2530 
2531 namespace {
2532 
2533 template <class ELFT> class MipsGOTParser {
2534 public:
2535   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
2536   using Entry = typename ELFT::Addr;
2537   using Entries = ArrayRef<Entry>;
2538 
2539   const bool IsStatic;
2540   const ELFFile<ELFT> &Obj;
2541   const ELFDumper<ELFT> &Dumper;
2542 
2543   MipsGOTParser(const ELFDumper<ELFT> &D);
2544   Error findGOT(Elf_Dyn_Range DynTable, Elf_Sym_Range DynSyms);
2545   Error findPLT(Elf_Dyn_Range DynTable);
2546 
2547   bool isGotEmpty() const { return GotEntries.empty(); }
2548   bool isPltEmpty() const { return PltEntries.empty(); }
2549 
2550   uint64_t getGp() const;
2551 
2552   const Entry *getGotLazyResolver() const;
2553   const Entry *getGotModulePointer() const;
2554   const Entry *getPltLazyResolver() const;
2555   const Entry *getPltModulePointer() const;
2556 
2557   Entries getLocalEntries() const;
2558   Entries getGlobalEntries() const;
2559   Entries getOtherEntries() const;
2560   Entries getPltEntries() const;
2561 
2562   uint64_t getGotAddress(const Entry * E) const;
2563   int64_t getGotOffset(const Entry * E) const;
2564   const Elf_Sym *getGotSym(const Entry *E) const;
2565 
2566   uint64_t getPltAddress(const Entry * E) const;
2567   const Elf_Sym *getPltSym(const Entry *E) const;
2568 
2569   StringRef getPltStrTable() const { return PltStrTable; }
2570   const Elf_Shdr *getPltSymTable() const { return PltSymTable; }
2571 
2572 private:
2573   const Elf_Shdr *GotSec;
2574   size_t LocalNum;
2575   size_t GlobalNum;
2576 
2577   const Elf_Shdr *PltSec;
2578   const Elf_Shdr *PltRelSec;
2579   const Elf_Shdr *PltSymTable;
2580   StringRef FileName;
2581 
2582   Elf_Sym_Range GotDynSyms;
2583   StringRef PltStrTable;
2584 
2585   Entries GotEntries;
2586   Entries PltEntries;
2587 };
2588 
2589 } // end anonymous namespace
2590 
2591 template <class ELFT>
2592 MipsGOTParser<ELFT>::MipsGOTParser(const ELFDumper<ELFT> &D)
2593     : IsStatic(D.dynamic_table().empty()), Obj(D.getElfObject().getELFFile()),
2594       Dumper(D), GotSec(nullptr), LocalNum(0), GlobalNum(0), PltSec(nullptr),
2595       PltRelSec(nullptr), PltSymTable(nullptr),
2596       FileName(D.getElfObject().getFileName()) {}
2597 
2598 template <class ELFT>
2599 Error MipsGOTParser<ELFT>::findGOT(Elf_Dyn_Range DynTable,
2600                                    Elf_Sym_Range DynSyms) {
2601   // See "Global Offset Table" in Chapter 5 in the following document
2602   // for detailed GOT description.
2603   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
2604 
2605   // Find static GOT secton.
2606   if (IsStatic) {
2607     GotSec = Dumper.findSectionByName(".got");
2608     if (!GotSec)
2609       return Error::success();
2610 
2611     ArrayRef<uint8_t> Content =
2612         unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
2613     GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
2614                          Content.size() / sizeof(Entry));
2615     LocalNum = GotEntries.size();
2616     return Error::success();
2617   }
2618 
2619   // Lookup dynamic table tags which define the GOT layout.
2620   Optional<uint64_t> DtPltGot;
2621   Optional<uint64_t> DtLocalGotNum;
2622   Optional<uint64_t> DtGotSym;
2623   for (const auto &Entry : DynTable) {
2624     switch (Entry.getTag()) {
2625     case ELF::DT_PLTGOT:
2626       DtPltGot = Entry.getVal();
2627       break;
2628     case ELF::DT_MIPS_LOCAL_GOTNO:
2629       DtLocalGotNum = Entry.getVal();
2630       break;
2631     case ELF::DT_MIPS_GOTSYM:
2632       DtGotSym = Entry.getVal();
2633       break;
2634     }
2635   }
2636 
2637   if (!DtPltGot && !DtLocalGotNum && !DtGotSym)
2638     return Error::success();
2639 
2640   if (!DtPltGot)
2641     return createError("cannot find PLTGOT dynamic tag");
2642   if (!DtLocalGotNum)
2643     return createError("cannot find MIPS_LOCAL_GOTNO dynamic tag");
2644   if (!DtGotSym)
2645     return createError("cannot find MIPS_GOTSYM dynamic tag");
2646 
2647   size_t DynSymTotal = DynSyms.size();
2648   if (*DtGotSym > DynSymTotal)
2649     return createError("DT_MIPS_GOTSYM value (" + Twine(*DtGotSym) +
2650                        ") exceeds the number of dynamic symbols (" +
2651                        Twine(DynSymTotal) + ")");
2652 
2653   GotSec = findNotEmptySectionByAddress(Obj, FileName, *DtPltGot);
2654   if (!GotSec)
2655     return createError("there is no non-empty GOT section at 0x" +
2656                        Twine::utohexstr(*DtPltGot));
2657 
2658   LocalNum = *DtLocalGotNum;
2659   GlobalNum = DynSymTotal - *DtGotSym;
2660 
2661   ArrayRef<uint8_t> Content =
2662       unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
2663   GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
2664                        Content.size() / sizeof(Entry));
2665   GotDynSyms = DynSyms.drop_front(*DtGotSym);
2666 
2667   return Error::success();
2668 }
2669 
2670 template <class ELFT>
2671 Error MipsGOTParser<ELFT>::findPLT(Elf_Dyn_Range DynTable) {
2672   // Lookup dynamic table tags which define the PLT layout.
2673   Optional<uint64_t> DtMipsPltGot;
2674   Optional<uint64_t> DtJmpRel;
2675   for (const auto &Entry : DynTable) {
2676     switch (Entry.getTag()) {
2677     case ELF::DT_MIPS_PLTGOT:
2678       DtMipsPltGot = Entry.getVal();
2679       break;
2680     case ELF::DT_JMPREL:
2681       DtJmpRel = Entry.getVal();
2682       break;
2683     }
2684   }
2685 
2686   if (!DtMipsPltGot && !DtJmpRel)
2687     return Error::success();
2688 
2689   // Find PLT section.
2690   if (!DtMipsPltGot)
2691     return createError("cannot find MIPS_PLTGOT dynamic tag");
2692   if (!DtJmpRel)
2693     return createError("cannot find JMPREL dynamic tag");
2694 
2695   PltSec = findNotEmptySectionByAddress(Obj, FileName, *DtMipsPltGot);
2696   if (!PltSec)
2697     return createError("there is no non-empty PLTGOT section at 0x" +
2698                        Twine::utohexstr(*DtMipsPltGot));
2699 
2700   PltRelSec = findNotEmptySectionByAddress(Obj, FileName, *DtJmpRel);
2701   if (!PltRelSec)
2702     return createError("there is no non-empty RELPLT section at 0x" +
2703                        Twine::utohexstr(*DtJmpRel));
2704 
2705   if (Expected<ArrayRef<uint8_t>> PltContentOrErr =
2706           Obj.getSectionContents(*PltSec))
2707     PltEntries =
2708         Entries(reinterpret_cast<const Entry *>(PltContentOrErr->data()),
2709                 PltContentOrErr->size() / sizeof(Entry));
2710   else
2711     return createError("unable to read PLTGOT section content: " +
2712                        toString(PltContentOrErr.takeError()));
2713 
2714   if (Expected<const Elf_Shdr *> PltSymTableOrErr =
2715           Obj.getSection(PltRelSec->sh_link))
2716     PltSymTable = *PltSymTableOrErr;
2717   else
2718     return createError("unable to get a symbol table linked to the " +
2719                        describe(Obj, *PltRelSec) + ": " +
2720                        toString(PltSymTableOrErr.takeError()));
2721 
2722   if (Expected<StringRef> StrTabOrErr =
2723           Obj.getStringTableForSymtab(*PltSymTable))
2724     PltStrTable = *StrTabOrErr;
2725   else
2726     return createError("unable to get a string table for the " +
2727                        describe(Obj, *PltSymTable) + ": " +
2728                        toString(StrTabOrErr.takeError()));
2729 
2730   return Error::success();
2731 }
2732 
2733 template <class ELFT> uint64_t MipsGOTParser<ELFT>::getGp() const {
2734   return GotSec->sh_addr + 0x7ff0;
2735 }
2736 
2737 template <class ELFT>
2738 const typename MipsGOTParser<ELFT>::Entry *
2739 MipsGOTParser<ELFT>::getGotLazyResolver() const {
2740   return LocalNum > 0 ? &GotEntries[0] : nullptr;
2741 }
2742 
2743 template <class ELFT>
2744 const typename MipsGOTParser<ELFT>::Entry *
2745 MipsGOTParser<ELFT>::getGotModulePointer() const {
2746   if (LocalNum < 2)
2747     return nullptr;
2748   const Entry &E = GotEntries[1];
2749   if ((E >> (sizeof(Entry) * 8 - 1)) == 0)
2750     return nullptr;
2751   return &E;
2752 }
2753 
2754 template <class ELFT>
2755 typename MipsGOTParser<ELFT>::Entries
2756 MipsGOTParser<ELFT>::getLocalEntries() const {
2757   size_t Skip = getGotModulePointer() ? 2 : 1;
2758   if (LocalNum - Skip <= 0)
2759     return Entries();
2760   return GotEntries.slice(Skip, LocalNum - Skip);
2761 }
2762 
2763 template <class ELFT>
2764 typename MipsGOTParser<ELFT>::Entries
2765 MipsGOTParser<ELFT>::getGlobalEntries() const {
2766   if (GlobalNum == 0)
2767     return Entries();
2768   return GotEntries.slice(LocalNum, GlobalNum);
2769 }
2770 
2771 template <class ELFT>
2772 typename MipsGOTParser<ELFT>::Entries
2773 MipsGOTParser<ELFT>::getOtherEntries() const {
2774   size_t OtherNum = GotEntries.size() - LocalNum - GlobalNum;
2775   if (OtherNum == 0)
2776     return Entries();
2777   return GotEntries.slice(LocalNum + GlobalNum, OtherNum);
2778 }
2779 
2780 template <class ELFT>
2781 uint64_t MipsGOTParser<ELFT>::getGotAddress(const Entry *E) const {
2782   int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
2783   return GotSec->sh_addr + Offset;
2784 }
2785 
2786 template <class ELFT>
2787 int64_t MipsGOTParser<ELFT>::getGotOffset(const Entry *E) const {
2788   int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
2789   return Offset - 0x7ff0;
2790 }
2791 
2792 template <class ELFT>
2793 const typename MipsGOTParser<ELFT>::Elf_Sym *
2794 MipsGOTParser<ELFT>::getGotSym(const Entry *E) const {
2795   int64_t Offset = std::distance(GotEntries.data(), E);
2796   return &GotDynSyms[Offset - LocalNum];
2797 }
2798 
2799 template <class ELFT>
2800 const typename MipsGOTParser<ELFT>::Entry *
2801 MipsGOTParser<ELFT>::getPltLazyResolver() const {
2802   return PltEntries.empty() ? nullptr : &PltEntries[0];
2803 }
2804 
2805 template <class ELFT>
2806 const typename MipsGOTParser<ELFT>::Entry *
2807 MipsGOTParser<ELFT>::getPltModulePointer() const {
2808   return PltEntries.size() < 2 ? nullptr : &PltEntries[1];
2809 }
2810 
2811 template <class ELFT>
2812 typename MipsGOTParser<ELFT>::Entries
2813 MipsGOTParser<ELFT>::getPltEntries() const {
2814   if (PltEntries.size() <= 2)
2815     return Entries();
2816   return PltEntries.slice(2, PltEntries.size() - 2);
2817 }
2818 
2819 template <class ELFT>
2820 uint64_t MipsGOTParser<ELFT>::getPltAddress(const Entry *E) const {
2821   int64_t Offset = std::distance(PltEntries.data(), E) * sizeof(Entry);
2822   return PltSec->sh_addr + Offset;
2823 }
2824 
2825 template <class ELFT>
2826 const typename MipsGOTParser<ELFT>::Elf_Sym *
2827 MipsGOTParser<ELFT>::getPltSym(const Entry *E) const {
2828   int64_t Offset = std::distance(getPltEntries().data(), E);
2829   if (PltRelSec->sh_type == ELF::SHT_REL) {
2830     Elf_Rel_Range Rels = unwrapOrError(FileName, Obj.rels(*PltRelSec));
2831     return unwrapOrError(FileName,
2832                          Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
2833   } else {
2834     Elf_Rela_Range Rels = unwrapOrError(FileName, Obj.relas(*PltRelSec));
2835     return unwrapOrError(FileName,
2836                          Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
2837   }
2838 }
2839 
2840 static const EnumEntry<unsigned> ElfMipsISAExtType[] = {
2841   {"None",                    Mips::AFL_EXT_NONE},
2842   {"Broadcom SB-1",           Mips::AFL_EXT_SB1},
2843   {"Cavium Networks Octeon",  Mips::AFL_EXT_OCTEON},
2844   {"Cavium Networks Octeon2", Mips::AFL_EXT_OCTEON2},
2845   {"Cavium Networks OcteonP", Mips::AFL_EXT_OCTEONP},
2846   {"Cavium Networks Octeon3", Mips::AFL_EXT_OCTEON3},
2847   {"LSI R4010",               Mips::AFL_EXT_4010},
2848   {"Loongson 2E",             Mips::AFL_EXT_LOONGSON_2E},
2849   {"Loongson 2F",             Mips::AFL_EXT_LOONGSON_2F},
2850   {"Loongson 3A",             Mips::AFL_EXT_LOONGSON_3A},
2851   {"MIPS R4650",              Mips::AFL_EXT_4650},
2852   {"MIPS R5900",              Mips::AFL_EXT_5900},
2853   {"MIPS R10000",             Mips::AFL_EXT_10000},
2854   {"NEC VR4100",              Mips::AFL_EXT_4100},
2855   {"NEC VR4111/VR4181",       Mips::AFL_EXT_4111},
2856   {"NEC VR4120",              Mips::AFL_EXT_4120},
2857   {"NEC VR5400",              Mips::AFL_EXT_5400},
2858   {"NEC VR5500",              Mips::AFL_EXT_5500},
2859   {"RMI Xlr",                 Mips::AFL_EXT_XLR},
2860   {"Toshiba R3900",           Mips::AFL_EXT_3900}
2861 };
2862 
2863 static const EnumEntry<unsigned> ElfMipsASEFlags[] = {
2864   {"DSP",                Mips::AFL_ASE_DSP},
2865   {"DSPR2",              Mips::AFL_ASE_DSPR2},
2866   {"Enhanced VA Scheme", Mips::AFL_ASE_EVA},
2867   {"MCU",                Mips::AFL_ASE_MCU},
2868   {"MDMX",               Mips::AFL_ASE_MDMX},
2869   {"MIPS-3D",            Mips::AFL_ASE_MIPS3D},
2870   {"MT",                 Mips::AFL_ASE_MT},
2871   {"SmartMIPS",          Mips::AFL_ASE_SMARTMIPS},
2872   {"VZ",                 Mips::AFL_ASE_VIRT},
2873   {"MSA",                Mips::AFL_ASE_MSA},
2874   {"MIPS16",             Mips::AFL_ASE_MIPS16},
2875   {"microMIPS",          Mips::AFL_ASE_MICROMIPS},
2876   {"XPA",                Mips::AFL_ASE_XPA},
2877   {"CRC",                Mips::AFL_ASE_CRC},
2878   {"GINV",               Mips::AFL_ASE_GINV},
2879 };
2880 
2881 static const EnumEntry<unsigned> ElfMipsFpABIType[] = {
2882   {"Hard or soft float",                  Mips::Val_GNU_MIPS_ABI_FP_ANY},
2883   {"Hard float (double precision)",       Mips::Val_GNU_MIPS_ABI_FP_DOUBLE},
2884   {"Hard float (single precision)",       Mips::Val_GNU_MIPS_ABI_FP_SINGLE},
2885   {"Soft float",                          Mips::Val_GNU_MIPS_ABI_FP_SOFT},
2886   {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)",
2887    Mips::Val_GNU_MIPS_ABI_FP_OLD_64},
2888   {"Hard float (32-bit CPU, Any FPU)",    Mips::Val_GNU_MIPS_ABI_FP_XX},
2889   {"Hard float (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64},
2890   {"Hard float compat (32-bit CPU, 64-bit FPU)",
2891    Mips::Val_GNU_MIPS_ABI_FP_64A}
2892 };
2893 
2894 static const EnumEntry<unsigned> ElfMipsFlags1[] {
2895   {"ODDSPREG", Mips::AFL_FLAGS1_ODDSPREG},
2896 };
2897 
2898 static int getMipsRegisterSize(uint8_t Flag) {
2899   switch (Flag) {
2900   case Mips::AFL_REG_NONE:
2901     return 0;
2902   case Mips::AFL_REG_32:
2903     return 32;
2904   case Mips::AFL_REG_64:
2905     return 64;
2906   case Mips::AFL_REG_128:
2907     return 128;
2908   default:
2909     return -1;
2910   }
2911 }
2912 
2913 template <class ELFT>
2914 static void printMipsReginfoData(ScopedPrinter &W,
2915                                  const Elf_Mips_RegInfo<ELFT> &Reginfo) {
2916   W.printHex("GP", Reginfo.ri_gp_value);
2917   W.printHex("General Mask", Reginfo.ri_gprmask);
2918   W.printHex("Co-Proc Mask0", Reginfo.ri_cprmask[0]);
2919   W.printHex("Co-Proc Mask1", Reginfo.ri_cprmask[1]);
2920   W.printHex("Co-Proc Mask2", Reginfo.ri_cprmask[2]);
2921   W.printHex("Co-Proc Mask3", Reginfo.ri_cprmask[3]);
2922 }
2923 
2924 template <class ELFT> void ELFDumper<ELFT>::printMipsReginfo() {
2925   const Elf_Shdr *RegInfoSec = findSectionByName(".reginfo");
2926   if (!RegInfoSec) {
2927     W.startLine() << "There is no .reginfo section in the file.\n";
2928     return;
2929   }
2930 
2931   Expected<ArrayRef<uint8_t>> ContentsOrErr =
2932       Obj.getSectionContents(*RegInfoSec);
2933   if (!ContentsOrErr) {
2934     this->reportUniqueWarning(
2935         "unable to read the content of the .reginfo section (" +
2936         describe(*RegInfoSec) + "): " + toString(ContentsOrErr.takeError()));
2937     return;
2938   }
2939 
2940   if (ContentsOrErr->size() < sizeof(Elf_Mips_RegInfo<ELFT>)) {
2941     this->reportUniqueWarning("the .reginfo section has an invalid size (0x" +
2942                               Twine::utohexstr(ContentsOrErr->size()) + ")");
2943     return;
2944   }
2945 
2946   DictScope GS(W, "MIPS RegInfo");
2947   printMipsReginfoData(W, *reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(
2948                               ContentsOrErr->data()));
2949 }
2950 
2951 template <class ELFT>
2952 static Expected<const Elf_Mips_Options<ELFT> *>
2953 readMipsOptions(const uint8_t *SecBegin, ArrayRef<uint8_t> &SecData,
2954                 bool &IsSupported) {
2955   if (SecData.size() < sizeof(Elf_Mips_Options<ELFT>))
2956     return createError("the .MIPS.options section has an invalid size (0x" +
2957                        Twine::utohexstr(SecData.size()) + ")");
2958 
2959   const Elf_Mips_Options<ELFT> *O =
2960       reinterpret_cast<const Elf_Mips_Options<ELFT> *>(SecData.data());
2961   const uint8_t Size = O->size;
2962   if (Size > SecData.size()) {
2963     const uint64_t Offset = SecData.data() - SecBegin;
2964     const uint64_t SecSize = Offset + SecData.size();
2965     return createError("a descriptor of size 0x" + Twine::utohexstr(Size) +
2966                        " at offset 0x" + Twine::utohexstr(Offset) +
2967                        " goes past the end of the .MIPS.options "
2968                        "section of size 0x" +
2969                        Twine::utohexstr(SecSize));
2970   }
2971 
2972   IsSupported = O->kind == ODK_REGINFO;
2973   const size_t ExpectedSize =
2974       sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>);
2975 
2976   if (IsSupported)
2977     if (Size < ExpectedSize)
2978       return createError(
2979           "a .MIPS.options entry of kind " +
2980           Twine(getElfMipsOptionsOdkType(O->kind)) +
2981           " has an invalid size (0x" + Twine::utohexstr(Size) +
2982           "), the expected size is 0x" + Twine::utohexstr(ExpectedSize));
2983 
2984   SecData = SecData.drop_front(Size);
2985   return O;
2986 }
2987 
2988 template <class ELFT> void ELFDumper<ELFT>::printMipsOptions() {
2989   const Elf_Shdr *MipsOpts = findSectionByName(".MIPS.options");
2990   if (!MipsOpts) {
2991     W.startLine() << "There is no .MIPS.options section in the file.\n";
2992     return;
2993   }
2994 
2995   DictScope GS(W, "MIPS Options");
2996 
2997   ArrayRef<uint8_t> Data =
2998       unwrapOrError(ObjF.getFileName(), Obj.getSectionContents(*MipsOpts));
2999   const uint8_t *const SecBegin = Data.begin();
3000   while (!Data.empty()) {
3001     bool IsSupported;
3002     Expected<const Elf_Mips_Options<ELFT> *> OptsOrErr =
3003         readMipsOptions<ELFT>(SecBegin, Data, IsSupported);
3004     if (!OptsOrErr) {
3005       reportUniqueWarning(OptsOrErr.takeError());
3006       break;
3007     }
3008 
3009     unsigned Kind = (*OptsOrErr)->kind;
3010     const char *Type = getElfMipsOptionsOdkType(Kind);
3011     if (!IsSupported) {
3012       W.startLine() << "Unsupported MIPS options tag: " << Type << " (" << Kind
3013                     << ")\n";
3014       continue;
3015     }
3016 
3017     DictScope GS(W, Type);
3018     if (Kind == ODK_REGINFO)
3019       printMipsReginfoData(W, (*OptsOrErr)->getRegInfo());
3020     else
3021       llvm_unreachable("unexpected .MIPS.options section descriptor kind");
3022   }
3023 }
3024 
3025 template <class ELFT> void ELFDumper<ELFT>::printStackMap() const {
3026   const Elf_Shdr *StackMapSection = findSectionByName(".llvm_stackmaps");
3027   if (!StackMapSection)
3028     return;
3029 
3030   auto Warn = [&](Error &&E) {
3031     this->reportUniqueWarning("unable to read the stack map from " +
3032                               describe(*StackMapSection) + ": " +
3033                               toString(std::move(E)));
3034   };
3035 
3036   Expected<ArrayRef<uint8_t>> ContentOrErr =
3037       Obj.getSectionContents(*StackMapSection);
3038   if (!ContentOrErr) {
3039     Warn(ContentOrErr.takeError());
3040     return;
3041   }
3042 
3043   if (Error E = StackMapParser<ELFT::TargetEndianness>::validateHeader(
3044           *ContentOrErr)) {
3045     Warn(std::move(E));
3046     return;
3047   }
3048 
3049   prettyPrintStackMap(W, StackMapParser<ELFT::TargetEndianness>(*ContentOrErr));
3050 }
3051 
3052 template <class ELFT>
3053 void ELFDumper<ELFT>::printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
3054                                  const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
3055   Expected<RelSymbol<ELFT>> Target = getRelocationTarget(R, SymTab);
3056   if (!Target)
3057     reportUniqueWarning("unable to print relocation " + Twine(RelIndex) +
3058                         " in " + describe(Sec) + ": " +
3059                         toString(Target.takeError()));
3060   else
3061     printRelRelaReloc(R, *Target);
3062 }
3063 
3064 static inline void printFields(formatted_raw_ostream &OS, StringRef Str1,
3065                                StringRef Str2) {
3066   OS.PadToColumn(2u);
3067   OS << Str1;
3068   OS.PadToColumn(37u);
3069   OS << Str2 << "\n";
3070   OS.flush();
3071 }
3072 
3073 template <class ELFT>
3074 static std::string getSectionHeadersNumString(const ELFFile<ELFT> &Obj,
3075                                               StringRef FileName) {
3076   const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3077   if (ElfHeader.e_shnum != 0)
3078     return to_string(ElfHeader.e_shnum);
3079 
3080   Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3081   if (!ArrOrErr) {
3082     // In this case we can ignore an error, because we have already reported a
3083     // warning about the broken section header table earlier.
3084     consumeError(ArrOrErr.takeError());
3085     return "<?>";
3086   }
3087 
3088   if (ArrOrErr->empty())
3089     return "0";
3090   return "0 (" + to_string((*ArrOrErr)[0].sh_size) + ")";
3091 }
3092 
3093 template <class ELFT>
3094 static std::string getSectionHeaderTableIndexString(const ELFFile<ELFT> &Obj,
3095                                                     StringRef FileName) {
3096   const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3097   if (ElfHeader.e_shstrndx != SHN_XINDEX)
3098     return to_string(ElfHeader.e_shstrndx);
3099 
3100   Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3101   if (!ArrOrErr) {
3102     // In this case we can ignore an error, because we have already reported a
3103     // warning about the broken section header table earlier.
3104     consumeError(ArrOrErr.takeError());
3105     return "<?>";
3106   }
3107 
3108   if (ArrOrErr->empty())
3109     return "65535 (corrupt: out of range)";
3110   return to_string(ElfHeader.e_shstrndx) + " (" +
3111          to_string((*ArrOrErr)[0].sh_link) + ")";
3112 }
3113 
3114 static const EnumEntry<unsigned> *getObjectFileEnumEntry(unsigned Type) {
3115   auto It = llvm::find_if(ElfObjectFileType, [&](const EnumEntry<unsigned> &E) {
3116     return E.Value == Type;
3117   });
3118   if (It != makeArrayRef(ElfObjectFileType).end())
3119     return It;
3120   return nullptr;
3121 }
3122 
3123 template <class ELFT> void GNUELFDumper<ELFT>::printFileHeaders() {
3124   const Elf_Ehdr &e = this->Obj.getHeader();
3125   OS << "ELF Header:\n";
3126   OS << "  Magic:  ";
3127   std::string Str;
3128   for (int i = 0; i < ELF::EI_NIDENT; i++)
3129     OS << format(" %02x", static_cast<int>(e.e_ident[i]));
3130   OS << "\n";
3131   Str = printEnum(e.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass));
3132   printFields(OS, "Class:", Str);
3133   Str = printEnum(e.e_ident[ELF::EI_DATA], makeArrayRef(ElfDataEncoding));
3134   printFields(OS, "Data:", Str);
3135   OS.PadToColumn(2u);
3136   OS << "Version:";
3137   OS.PadToColumn(37u);
3138   OS << to_hexString(e.e_ident[ELF::EI_VERSION]);
3139   if (e.e_version == ELF::EV_CURRENT)
3140     OS << " (current)";
3141   OS << "\n";
3142   Str = printEnum(e.e_ident[ELF::EI_OSABI], makeArrayRef(ElfOSABI));
3143   printFields(OS, "OS/ABI:", Str);
3144   printFields(OS,
3145               "ABI Version:", std::to_string(e.e_ident[ELF::EI_ABIVERSION]));
3146 
3147   if (const EnumEntry<unsigned> *E = getObjectFileEnumEntry(e.e_type)) {
3148     Str = E->AltName.str();
3149   } else {
3150     if (e.e_type >= ET_LOPROC)
3151       Str = "Processor Specific: (" + to_hexString(e.e_type, false) + ")";
3152     else if (e.e_type >= ET_LOOS)
3153       Str = "OS Specific: (" + to_hexString(e.e_type, false) + ")";
3154     else
3155       Str = "<unknown>: " + to_hexString(e.e_type, false);
3156   }
3157   printFields(OS, "Type:", Str);
3158 
3159   Str = printEnum(e.e_machine, makeArrayRef(ElfMachineType));
3160   printFields(OS, "Machine:", Str);
3161   Str = "0x" + to_hexString(e.e_version);
3162   printFields(OS, "Version:", Str);
3163   Str = "0x" + to_hexString(e.e_entry);
3164   printFields(OS, "Entry point address:", Str);
3165   Str = to_string(e.e_phoff) + " (bytes into file)";
3166   printFields(OS, "Start of program headers:", Str);
3167   Str = to_string(e.e_shoff) + " (bytes into file)";
3168   printFields(OS, "Start of section headers:", Str);
3169   std::string ElfFlags;
3170   if (e.e_machine == EM_MIPS)
3171     ElfFlags =
3172         printFlags(e.e_flags, makeArrayRef(ElfHeaderMipsFlags),
3173                    unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
3174                    unsigned(ELF::EF_MIPS_MACH));
3175   else if (e.e_machine == EM_RISCV)
3176     ElfFlags = printFlags(e.e_flags, makeArrayRef(ElfHeaderRISCVFlags));
3177   Str = "0x" + to_hexString(e.e_flags);
3178   if (!ElfFlags.empty())
3179     Str = Str + ", " + ElfFlags;
3180   printFields(OS, "Flags:", Str);
3181   Str = to_string(e.e_ehsize) + " (bytes)";
3182   printFields(OS, "Size of this header:", Str);
3183   Str = to_string(e.e_phentsize) + " (bytes)";
3184   printFields(OS, "Size of program headers:", Str);
3185   Str = to_string(e.e_phnum);
3186   printFields(OS, "Number of program headers:", Str);
3187   Str = to_string(e.e_shentsize) + " (bytes)";
3188   printFields(OS, "Size of section headers:", Str);
3189   Str = getSectionHeadersNumString(this->Obj, this->FileName);
3190   printFields(OS, "Number of section headers:", Str);
3191   Str = getSectionHeaderTableIndexString(this->Obj, this->FileName);
3192   printFields(OS, "Section header string table index:", Str);
3193 }
3194 
3195 template <class ELFT> std::vector<GroupSection> ELFDumper<ELFT>::getGroups() {
3196   auto GetSignature = [&](const Elf_Sym &Sym, unsigned SymNdx,
3197                           const Elf_Shdr &Symtab) -> StringRef {
3198     Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(Symtab);
3199     if (!StrTableOrErr) {
3200       reportUniqueWarning("unable to get the string table for " +
3201                           describe(Symtab) + ": " +
3202                           toString(StrTableOrErr.takeError()));
3203       return "<?>";
3204     }
3205 
3206     StringRef Strings = *StrTableOrErr;
3207     if (Sym.st_name >= Strings.size()) {
3208       reportUniqueWarning("unable to get the name of the symbol with index " +
3209                           Twine(SymNdx) + ": st_name (0x" +
3210                           Twine::utohexstr(Sym.st_name) +
3211                           ") is past the end of the string table of size 0x" +
3212                           Twine::utohexstr(Strings.size()));
3213       return "<?>";
3214     }
3215 
3216     return StrTableOrErr->data() + Sym.st_name;
3217   };
3218 
3219   std::vector<GroupSection> Ret;
3220   uint64_t I = 0;
3221   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
3222     ++I;
3223     if (Sec.sh_type != ELF::SHT_GROUP)
3224       continue;
3225 
3226     StringRef Signature = "<?>";
3227     if (Expected<const Elf_Shdr *> SymtabOrErr = Obj.getSection(Sec.sh_link)) {
3228       if (Expected<const Elf_Sym *> SymOrErr =
3229               Obj.template getEntry<Elf_Sym>(**SymtabOrErr, Sec.sh_info))
3230         Signature = GetSignature(**SymOrErr, Sec.sh_info, **SymtabOrErr);
3231       else
3232         reportUniqueWarning("unable to get the signature symbol for " +
3233                             describe(Sec) + ": " +
3234                             toString(SymOrErr.takeError()));
3235     } else {
3236       reportUniqueWarning("unable to get the symbol table for " +
3237                           describe(Sec) + ": " +
3238                           toString(SymtabOrErr.takeError()));
3239     }
3240 
3241     ArrayRef<Elf_Word> Data;
3242     if (Expected<ArrayRef<Elf_Word>> ContentsOrErr =
3243             Obj.template getSectionContentsAsArray<Elf_Word>(Sec)) {
3244       if (ContentsOrErr->empty())
3245         reportUniqueWarning("unable to read the section group flag from the " +
3246                             describe(Sec) + ": the section is empty");
3247       else
3248         Data = *ContentsOrErr;
3249     } else {
3250       reportUniqueWarning("unable to get the content of the " + describe(Sec) +
3251                           ": " + toString(ContentsOrErr.takeError()));
3252     }
3253 
3254     Ret.push_back({getPrintableSectionName(Sec),
3255                    maybeDemangle(Signature),
3256                    Sec.sh_name,
3257                    I - 1,
3258                    Sec.sh_link,
3259                    Sec.sh_info,
3260                    Data.empty() ? Elf_Word(0) : Data[0],
3261                    {}});
3262 
3263     if (Data.empty())
3264       continue;
3265 
3266     std::vector<GroupMember> &GM = Ret.back().Members;
3267     for (uint32_t Ndx : Data.slice(1)) {
3268       if (Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(Ndx)) {
3269         GM.push_back({getPrintableSectionName(**SecOrErr), Ndx});
3270       } else {
3271         reportUniqueWarning("unable to get the section with index " +
3272                             Twine(Ndx) + " when dumping the " + describe(Sec) +
3273                             ": " + toString(SecOrErr.takeError()));
3274         GM.push_back({"<?>", Ndx});
3275       }
3276     }
3277   }
3278   return Ret;
3279 }
3280 
3281 static DenseMap<uint64_t, const GroupSection *>
3282 mapSectionsToGroups(ArrayRef<GroupSection> Groups) {
3283   DenseMap<uint64_t, const GroupSection *> Ret;
3284   for (const GroupSection &G : Groups)
3285     for (const GroupMember &GM : G.Members)
3286       Ret.insert({GM.Index, &G});
3287   return Ret;
3288 }
3289 
3290 template <class ELFT> void GNUELFDumper<ELFT>::printGroupSections() {
3291   std::vector<GroupSection> V = this->getGroups();
3292   DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
3293   for (const GroupSection &G : V) {
3294     OS << "\n"
3295        << getGroupType(G.Type) << " group section ["
3296        << format_decimal(G.Index, 5) << "] `" << G.Name << "' [" << G.Signature
3297        << "] contains " << G.Members.size() << " sections:\n"
3298        << "   [Index]    Name\n";
3299     for (const GroupMember &GM : G.Members) {
3300       const GroupSection *MainGroup = Map[GM.Index];
3301       if (MainGroup != &G)
3302         this->reportUniqueWarning(
3303             "section with index " + Twine(GM.Index) +
3304             ", included in the group section with index " +
3305             Twine(MainGroup->Index) +
3306             ", was also found in the group section with index " +
3307             Twine(G.Index));
3308       OS << "   [" << format_decimal(GM.Index, 5) << "]   " << GM.Name << "\n";
3309     }
3310   }
3311 
3312   if (V.empty())
3313     OS << "There are no section groups in this file.\n";
3314 }
3315 
3316 template <class ELFT>
3317 void GNUELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
3318   OS << to_string(format_hex_no_prefix(R, ELFT::Is64Bits ? 16 : 8)) << "\n";
3319 }
3320 
3321 template <class ELFT>
3322 void GNUELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
3323                                            const RelSymbol<ELFT> &RelSym) {
3324   // First two fields are bit width dependent. The rest of them are fixed width.
3325   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3326   Field Fields[5] = {0, 10 + Bias, 19 + 2 * Bias, 42 + 2 * Bias, 53 + 2 * Bias};
3327   unsigned Width = ELFT::Is64Bits ? 16 : 8;
3328 
3329   Fields[0].Str = to_string(format_hex_no_prefix(R.Offset, Width));
3330   Fields[1].Str = to_string(format_hex_no_prefix(R.Info, Width));
3331 
3332   SmallString<32> RelocName;
3333   this->Obj.getRelocationTypeName(R.Type, RelocName);
3334   Fields[2].Str = RelocName.c_str();
3335 
3336   if (RelSym.Sym)
3337     Fields[3].Str =
3338         to_string(format_hex_no_prefix(RelSym.Sym->getValue(), Width));
3339 
3340   Fields[4].Str = std::string(RelSym.Name);
3341   for (const Field &F : Fields)
3342     printField(F);
3343 
3344   std::string Addend;
3345   if (Optional<int64_t> A = R.Addend) {
3346     int64_t RelAddend = *A;
3347     if (!RelSym.Name.empty()) {
3348       if (RelAddend < 0) {
3349         Addend = " - ";
3350         RelAddend = std::abs(RelAddend);
3351       } else {
3352         Addend = " + ";
3353       }
3354     }
3355     Addend += to_hexString(RelAddend, false);
3356   }
3357   OS << Addend << "\n";
3358 }
3359 
3360 template <class ELFT>
3361 static void printRelocHeaderFields(formatted_raw_ostream &OS, unsigned SType) {
3362   bool IsRela = SType == ELF::SHT_RELA || SType == ELF::SHT_ANDROID_RELA;
3363   bool IsRelr = SType == ELF::SHT_RELR || SType == ELF::SHT_ANDROID_RELR;
3364   if (ELFT::Is64Bits)
3365     OS << "    ";
3366   else
3367     OS << " ";
3368   if (IsRelr && opts::RawRelr)
3369     OS << "Data  ";
3370   else
3371     OS << "Offset";
3372   if (ELFT::Is64Bits)
3373     OS << "             Info             Type"
3374        << "               Symbol's Value  Symbol's Name";
3375   else
3376     OS << "     Info    Type                Sym. Value  Symbol's Name";
3377   if (IsRela)
3378     OS << " + Addend";
3379   OS << "\n";
3380 }
3381 
3382 template <class ELFT>
3383 void GNUELFDumper<ELFT>::printDynamicRelocHeader(unsigned Type, StringRef Name,
3384                                                  const DynRegionInfo &Reg) {
3385   uint64_t Offset = Reg.Addr - this->Obj.base();
3386   OS << "\n'" << Name.str().c_str() << "' relocation section at offset 0x"
3387      << to_hexString(Offset, false) << " contains " << Reg.Size << " bytes:\n";
3388   printRelocHeaderFields<ELFT>(OS, Type);
3389 }
3390 
3391 template <class ELFT>
3392 static bool isRelocationSec(const typename ELFT::Shdr &Sec) {
3393   return Sec.sh_type == ELF::SHT_REL || Sec.sh_type == ELF::SHT_RELA ||
3394          Sec.sh_type == ELF::SHT_RELR || Sec.sh_type == ELF::SHT_ANDROID_REL ||
3395          Sec.sh_type == ELF::SHT_ANDROID_RELA ||
3396          Sec.sh_type == ELF::SHT_ANDROID_RELR;
3397 }
3398 
3399 template <class ELFT> void GNUELFDumper<ELFT>::printRelocations() {
3400   auto GetEntriesNum = [&](const Elf_Shdr &Sec) -> Expected<size_t> {
3401     // Android's packed relocation section needs to be unpacked first
3402     // to get the actual number of entries.
3403     if (Sec.sh_type == ELF::SHT_ANDROID_REL ||
3404         Sec.sh_type == ELF::SHT_ANDROID_RELA) {
3405       Expected<std::vector<typename ELFT::Rela>> RelasOrErr =
3406           this->Obj.android_relas(Sec);
3407       if (!RelasOrErr)
3408         return RelasOrErr.takeError();
3409       return RelasOrErr->size();
3410     }
3411 
3412     if (!opts::RawRelr && (Sec.sh_type == ELF::SHT_RELR ||
3413                            Sec.sh_type == ELF::SHT_ANDROID_RELR)) {
3414       Expected<Elf_Relr_Range> RelrsOrErr = this->Obj.relrs(Sec);
3415       if (!RelrsOrErr)
3416         return RelrsOrErr.takeError();
3417       return this->Obj.decode_relrs(*RelrsOrErr).size();
3418     }
3419 
3420     return Sec.getEntityCount();
3421   };
3422 
3423   bool HasRelocSections = false;
3424   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
3425     if (!isRelocationSec<ELFT>(Sec))
3426       continue;
3427     HasRelocSections = true;
3428 
3429     std::string EntriesNum = "<?>";
3430     if (Expected<size_t> NumOrErr = GetEntriesNum(Sec))
3431       EntriesNum = std::to_string(*NumOrErr);
3432     else
3433       this->reportUniqueWarning("unable to get the number of relocations in " +
3434                                 this->describe(Sec) + ": " +
3435                                 toString(NumOrErr.takeError()));
3436 
3437     uintX_t Offset = Sec.sh_offset;
3438     StringRef Name = this->getPrintableSectionName(Sec);
3439     OS << "\nRelocation section '" << Name << "' at offset 0x"
3440        << to_hexString(Offset, false) << " contains " << EntriesNum
3441        << " entries:\n";
3442     printRelocHeaderFields<ELFT>(OS, Sec.sh_type);
3443     this->printRelocationsHelper(Sec);
3444   }
3445   if (!HasRelocSections)
3446     OS << "\nThere are no relocations in this file.\n";
3447 }
3448 
3449 // Print the offset of a particular section from anyone of the ranges:
3450 // [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER].
3451 // If 'Type' does not fall within any of those ranges, then a string is
3452 // returned as '<unknown>' followed by the type value.
3453 static std::string getSectionTypeOffsetString(unsigned Type) {
3454   if (Type >= SHT_LOOS && Type <= SHT_HIOS)
3455     return "LOOS+0x" + to_hexString(Type - SHT_LOOS);
3456   else if (Type >= SHT_LOPROC && Type <= SHT_HIPROC)
3457     return "LOPROC+0x" + to_hexString(Type - SHT_LOPROC);
3458   else if (Type >= SHT_LOUSER && Type <= SHT_HIUSER)
3459     return "LOUSER+0x" + to_hexString(Type - SHT_LOUSER);
3460   return "0x" + to_hexString(Type) + ": <unknown>";
3461 }
3462 
3463 static std::string getSectionTypeString(unsigned Machine, unsigned Type) {
3464   StringRef Name = getELFSectionTypeName(Machine, Type);
3465 
3466   // Handle SHT_GNU_* type names.
3467   if (Name.startswith("SHT_GNU_")) {
3468     if (Name == "SHT_GNU_HASH")
3469       return "GNU_HASH";
3470     // E.g. SHT_GNU_verneed -> VERNEED.
3471     return Name.drop_front(8).upper();
3472   }
3473 
3474   if (Name == "SHT_SYMTAB_SHNDX")
3475     return "SYMTAB SECTION INDICES";
3476 
3477   if (Name.startswith("SHT_"))
3478     return Name.drop_front(4).str();
3479   return getSectionTypeOffsetString(Type);
3480 }
3481 
3482 static void printSectionDescription(formatted_raw_ostream &OS,
3483                                     unsigned EMachine) {
3484   OS << "Key to Flags:\n";
3485   OS << "  W (write), A (alloc), X (execute), M (merge), S (strings), I "
3486         "(info),\n";
3487   OS << "  L (link order), O (extra OS processing required), G (group), T "
3488         "(TLS),\n";
3489   OS << "  C (compressed), x (unknown), o (OS specific), E (exclude),\n";
3490   OS << "  R (retain)";
3491 
3492   if (EMachine == EM_X86_64)
3493     OS << ", l (large)";
3494   else if (EMachine == EM_ARM)
3495     OS << ", y (purecode)";
3496 
3497   OS << ", p (processor specific)\n";
3498 }
3499 
3500 template <class ELFT> void GNUELFDumper<ELFT>::printSectionHeaders() {
3501   unsigned Bias = ELFT::Is64Bits ? 0 : 8;
3502   ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
3503   OS << "There are " << to_string(Sections.size())
3504      << " section headers, starting at offset "
3505      << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n";
3506   OS << "Section Headers:\n";
3507   Field Fields[11] = {
3508       {"[Nr]", 2},        {"Name", 7},        {"Type", 25},
3509       {"Address", 41},    {"Off", 58 - Bias}, {"Size", 65 - Bias},
3510       {"ES", 72 - Bias},  {"Flg", 75 - Bias}, {"Lk", 79 - Bias},
3511       {"Inf", 82 - Bias}, {"Al", 86 - Bias}};
3512   for (const Field &F : Fields)
3513     printField(F);
3514   OS << "\n";
3515 
3516   StringRef SecStrTable;
3517   if (Expected<StringRef> SecStrTableOrErr =
3518           this->Obj.getSectionStringTable(Sections, this->WarningHandler))
3519     SecStrTable = *SecStrTableOrErr;
3520   else
3521     this->reportUniqueWarning(SecStrTableOrErr.takeError());
3522 
3523   size_t SectionIndex = 0;
3524   for (const Elf_Shdr &Sec : Sections) {
3525     Fields[0].Str = to_string(SectionIndex);
3526     if (SecStrTable.empty())
3527       Fields[1].Str = "<no-strings>";
3528     else
3529       Fields[1].Str = std::string(unwrapOrError<StringRef>(
3530           this->FileName, this->Obj.getSectionName(Sec, SecStrTable)));
3531     Fields[2].Str =
3532         getSectionTypeString(this->Obj.getHeader().e_machine, Sec.sh_type);
3533     Fields[3].Str =
3534         to_string(format_hex_no_prefix(Sec.sh_addr, ELFT::Is64Bits ? 16 : 8));
3535     Fields[4].Str = to_string(format_hex_no_prefix(Sec.sh_offset, 6));
3536     Fields[5].Str = to_string(format_hex_no_prefix(Sec.sh_size, 6));
3537     Fields[6].Str = to_string(format_hex_no_prefix(Sec.sh_entsize, 2));
3538     Fields[7].Str = getGNUFlags(this->Obj.getHeader().e_machine, Sec.sh_flags);
3539     Fields[8].Str = to_string(Sec.sh_link);
3540     Fields[9].Str = to_string(Sec.sh_info);
3541     Fields[10].Str = to_string(Sec.sh_addralign);
3542 
3543     OS.PadToColumn(Fields[0].Column);
3544     OS << "[" << right_justify(Fields[0].Str, 2) << "]";
3545     for (int i = 1; i < 7; i++)
3546       printField(Fields[i]);
3547     OS.PadToColumn(Fields[7].Column);
3548     OS << right_justify(Fields[7].Str, 3);
3549     OS.PadToColumn(Fields[8].Column);
3550     OS << right_justify(Fields[8].Str, 2);
3551     OS.PadToColumn(Fields[9].Column);
3552     OS << right_justify(Fields[9].Str, 3);
3553     OS.PadToColumn(Fields[10].Column);
3554     OS << right_justify(Fields[10].Str, 2);
3555     OS << "\n";
3556     ++SectionIndex;
3557   }
3558   printSectionDescription(OS, this->Obj.getHeader().e_machine);
3559 }
3560 
3561 template <class ELFT>
3562 void GNUELFDumper<ELFT>::printSymtabMessage(const Elf_Shdr *Symtab,
3563                                             size_t Entries,
3564                                             bool NonVisibilityBitsUsed) const {
3565   StringRef Name;
3566   if (Symtab)
3567     Name = this->getPrintableSectionName(*Symtab);
3568   if (!Name.empty())
3569     OS << "\nSymbol table '" << Name << "'";
3570   else
3571     OS << "\nSymbol table for image";
3572   OS << " contains " << Entries << " entries:\n";
3573 
3574   if (ELFT::Is64Bits)
3575     OS << "   Num:    Value          Size Type    Bind   Vis";
3576   else
3577     OS << "   Num:    Value  Size Type    Bind   Vis";
3578 
3579   if (NonVisibilityBitsUsed)
3580     OS << "             ";
3581   OS << "       Ndx Name\n";
3582 }
3583 
3584 template <class ELFT>
3585 std::string
3586 GNUELFDumper<ELFT>::getSymbolSectionNdx(const Elf_Sym &Symbol,
3587                                         unsigned SymIndex,
3588                                         DataRegion<Elf_Word> ShndxTable) const {
3589   unsigned SectionIndex = Symbol.st_shndx;
3590   switch (SectionIndex) {
3591   case ELF::SHN_UNDEF:
3592     return "UND";
3593   case ELF::SHN_ABS:
3594     return "ABS";
3595   case ELF::SHN_COMMON:
3596     return "COM";
3597   case ELF::SHN_XINDEX: {
3598     Expected<uint32_t> IndexOrErr =
3599         object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, ShndxTable);
3600     if (!IndexOrErr) {
3601       assert(Symbol.st_shndx == SHN_XINDEX &&
3602              "getExtendedSymbolTableIndex should only fail due to an invalid "
3603              "SHT_SYMTAB_SHNDX table/reference");
3604       this->reportUniqueWarning(IndexOrErr.takeError());
3605       return "RSV[0xffff]";
3606     }
3607     return to_string(format_decimal(*IndexOrErr, 3));
3608   }
3609   default:
3610     // Find if:
3611     // Processor specific
3612     if (SectionIndex >= ELF::SHN_LOPROC && SectionIndex <= ELF::SHN_HIPROC)
3613       return std::string("PRC[0x") +
3614              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3615     // OS specific
3616     if (SectionIndex >= ELF::SHN_LOOS && SectionIndex <= ELF::SHN_HIOS)
3617       return std::string("OS[0x") +
3618              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3619     // Architecture reserved:
3620     if (SectionIndex >= ELF::SHN_LORESERVE &&
3621         SectionIndex <= ELF::SHN_HIRESERVE)
3622       return std::string("RSV[0x") +
3623              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3624     // A normal section with an index
3625     return to_string(format_decimal(SectionIndex, 3));
3626   }
3627 }
3628 
3629 template <class ELFT>
3630 void GNUELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
3631                                      DataRegion<Elf_Word> ShndxTable,
3632                                      Optional<StringRef> StrTable,
3633                                      bool IsDynamic,
3634                                      bool NonVisibilityBitsUsed) const {
3635   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3636   Field Fields[8] = {0,         8,         17 + Bias, 23 + Bias,
3637                      31 + Bias, 38 + Bias, 48 + Bias, 51 + Bias};
3638   Fields[0].Str = to_string(format_decimal(SymIndex, 6)) + ":";
3639   Fields[1].Str =
3640       to_string(format_hex_no_prefix(Symbol.st_value, ELFT::Is64Bits ? 16 : 8));
3641   Fields[2].Str = to_string(format_decimal(Symbol.st_size, 5));
3642 
3643   unsigned char SymbolType = Symbol.getType();
3644   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
3645       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
3646     Fields[3].Str = printEnum(SymbolType, makeArrayRef(AMDGPUSymbolTypes));
3647   else
3648     Fields[3].Str = printEnum(SymbolType, makeArrayRef(ElfSymbolTypes));
3649 
3650   Fields[4].Str =
3651       printEnum(Symbol.getBinding(), makeArrayRef(ElfSymbolBindings));
3652   Fields[5].Str =
3653       printEnum(Symbol.getVisibility(), makeArrayRef(ElfSymbolVisibilities));
3654 
3655   if (Symbol.st_other & ~0x3) {
3656     if (this->Obj.getHeader().e_machine == ELF::EM_AARCH64) {
3657       uint8_t Other = Symbol.st_other & ~0x3;
3658       if (Other & STO_AARCH64_VARIANT_PCS) {
3659         Other &= ~STO_AARCH64_VARIANT_PCS;
3660         Fields[5].Str += " [VARIANT_PCS";
3661         if (Other != 0)
3662           Fields[5].Str.append(" | " + to_hexString(Other, false));
3663         Fields[5].Str.append("]");
3664       }
3665     } else {
3666       Fields[5].Str +=
3667           " [<other: " + to_string(format_hex(Symbol.st_other, 2)) + ">]";
3668     }
3669   }
3670 
3671   Fields[6].Column += NonVisibilityBitsUsed ? 13 : 0;
3672   Fields[6].Str = getSymbolSectionNdx(Symbol, SymIndex, ShndxTable);
3673 
3674   Fields[7].Str = this->getFullSymbolName(Symbol, SymIndex, ShndxTable,
3675                                           StrTable, IsDynamic);
3676   for (const Field &Entry : Fields)
3677     printField(Entry);
3678   OS << "\n";
3679 }
3680 
3681 template <class ELFT>
3682 void GNUELFDumper<ELFT>::printHashedSymbol(const Elf_Sym *Symbol,
3683                                            unsigned SymIndex,
3684                                            DataRegion<Elf_Word> ShndxTable,
3685                                            StringRef StrTable,
3686                                            uint32_t Bucket) {
3687   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3688   Field Fields[9] = {0,         6,         11,        20 + Bias, 25 + Bias,
3689                      34 + Bias, 41 + Bias, 49 + Bias, 53 + Bias};
3690   Fields[0].Str = to_string(format_decimal(SymIndex, 5));
3691   Fields[1].Str = to_string(format_decimal(Bucket, 3)) + ":";
3692 
3693   Fields[2].Str = to_string(
3694       format_hex_no_prefix(Symbol->st_value, ELFT::Is64Bits ? 16 : 8));
3695   Fields[3].Str = to_string(format_decimal(Symbol->st_size, 5));
3696 
3697   unsigned char SymbolType = Symbol->getType();
3698   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
3699       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
3700     Fields[4].Str = printEnum(SymbolType, makeArrayRef(AMDGPUSymbolTypes));
3701   else
3702     Fields[4].Str = printEnum(SymbolType, makeArrayRef(ElfSymbolTypes));
3703 
3704   Fields[5].Str =
3705       printEnum(Symbol->getBinding(), makeArrayRef(ElfSymbolBindings));
3706   Fields[6].Str =
3707       printEnum(Symbol->getVisibility(), makeArrayRef(ElfSymbolVisibilities));
3708   Fields[7].Str = getSymbolSectionNdx(*Symbol, SymIndex, ShndxTable);
3709   Fields[8].Str =
3710       this->getFullSymbolName(*Symbol, SymIndex, ShndxTable, StrTable, true);
3711 
3712   for (const Field &Entry : Fields)
3713     printField(Entry);
3714   OS << "\n";
3715 }
3716 
3717 template <class ELFT>
3718 void GNUELFDumper<ELFT>::printSymbols(bool PrintSymbols,
3719                                       bool PrintDynamicSymbols) {
3720   if (!PrintSymbols && !PrintDynamicSymbols)
3721     return;
3722   // GNU readelf prints both the .dynsym and .symtab with --symbols.
3723   this->printSymbolsHelper(true);
3724   if (PrintSymbols)
3725     this->printSymbolsHelper(false);
3726 }
3727 
3728 template <class ELFT>
3729 void GNUELFDumper<ELFT>::printHashTableSymbols(const Elf_Hash &SysVHash) {
3730   if (this->DynamicStringTable.empty())
3731     return;
3732 
3733   if (ELFT::Is64Bits)
3734     OS << "  Num Buc:    Value          Size   Type   Bind Vis      Ndx Name";
3735   else
3736     OS << "  Num Buc:    Value  Size   Type   Bind Vis      Ndx Name";
3737   OS << "\n";
3738 
3739   Elf_Sym_Range DynSyms = this->dynamic_symbols();
3740   const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
3741   if (!FirstSym) {
3742     this->reportUniqueWarning(
3743         Twine("unable to print symbols for the .hash table: the "
3744               "dynamic symbol table ") +
3745         (this->DynSymRegion ? "is empty" : "was not found"));
3746     return;
3747   }
3748 
3749   DataRegion<Elf_Word> ShndxTable(
3750       (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
3751   auto Buckets = SysVHash.buckets();
3752   auto Chains = SysVHash.chains();
3753   for (uint32_t Buc = 0; Buc < SysVHash.nbucket; Buc++) {
3754     if (Buckets[Buc] == ELF::STN_UNDEF)
3755       continue;
3756     std::vector<bool> Visited(SysVHash.nchain);
3757     for (uint32_t Ch = Buckets[Buc]; Ch < SysVHash.nchain; Ch = Chains[Ch]) {
3758       if (Ch == ELF::STN_UNDEF)
3759         break;
3760 
3761       if (Visited[Ch]) {
3762         this->reportUniqueWarning(".hash section is invalid: bucket " +
3763                                   Twine(Ch) +
3764                                   ": a cycle was detected in the linked chain");
3765         break;
3766       }
3767 
3768       printHashedSymbol(FirstSym + Ch, Ch, ShndxTable, this->DynamicStringTable,
3769                         Buc);
3770       Visited[Ch] = true;
3771     }
3772   }
3773 }
3774 
3775 template <class ELFT>
3776 void GNUELFDumper<ELFT>::printGnuHashTableSymbols(const Elf_GnuHash &GnuHash) {
3777   if (this->DynamicStringTable.empty())
3778     return;
3779 
3780   Elf_Sym_Range DynSyms = this->dynamic_symbols();
3781   const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
3782   if (!FirstSym) {
3783     this->reportUniqueWarning(
3784         Twine("unable to print symbols for the .gnu.hash table: the "
3785               "dynamic symbol table ") +
3786         (this->DynSymRegion ? "is empty" : "was not found"));
3787     return;
3788   }
3789 
3790   auto GetSymbol = [&](uint64_t SymIndex,
3791                        uint64_t SymsTotal) -> const Elf_Sym * {
3792     if (SymIndex >= SymsTotal) {
3793       this->reportUniqueWarning(
3794           "unable to print hashed symbol with index " + Twine(SymIndex) +
3795           ", which is greater than or equal to the number of dynamic symbols "
3796           "(" +
3797           Twine::utohexstr(SymsTotal) + ")");
3798       return nullptr;
3799     }
3800     return FirstSym + SymIndex;
3801   };
3802 
3803   Expected<ArrayRef<Elf_Word>> ValuesOrErr =
3804       getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHash);
3805   ArrayRef<Elf_Word> Values;
3806   if (!ValuesOrErr)
3807     this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH "
3808                               "section: " +
3809                               toString(ValuesOrErr.takeError()));
3810   else
3811     Values = *ValuesOrErr;
3812 
3813   DataRegion<Elf_Word> ShndxTable(
3814       (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
3815   ArrayRef<Elf_Word> Buckets = GnuHash.buckets();
3816   for (uint32_t Buc = 0; Buc < GnuHash.nbuckets; Buc++) {
3817     if (Buckets[Buc] == ELF::STN_UNDEF)
3818       continue;
3819     uint32_t Index = Buckets[Buc];
3820     // Print whole chain.
3821     while (true) {
3822       uint32_t SymIndex = Index++;
3823       if (const Elf_Sym *Sym = GetSymbol(SymIndex, DynSyms.size()))
3824         printHashedSymbol(Sym, SymIndex, ShndxTable, this->DynamicStringTable,
3825                           Buc);
3826       else
3827         break;
3828 
3829       if (SymIndex < GnuHash.symndx) {
3830         this->reportUniqueWarning(
3831             "unable to read the hash value for symbol with index " +
3832             Twine(SymIndex) +
3833             ", which is less than the index of the first hashed symbol (" +
3834             Twine(GnuHash.symndx) + ")");
3835         break;
3836       }
3837 
3838        // Chain ends at symbol with stopper bit.
3839       if ((Values[SymIndex - GnuHash.symndx] & 1) == 1)
3840         break;
3841     }
3842   }
3843 }
3844 
3845 template <class ELFT> void GNUELFDumper<ELFT>::printHashSymbols() {
3846   if (this->HashTable) {
3847     OS << "\n Symbol table of .hash for image:\n";
3848     if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
3849       this->reportUniqueWarning(std::move(E));
3850     else
3851       printHashTableSymbols(*this->HashTable);
3852   }
3853 
3854   // Try printing the .gnu.hash table.
3855   if (this->GnuHashTable) {
3856     OS << "\n Symbol table of .gnu.hash for image:\n";
3857     if (ELFT::Is64Bits)
3858       OS << "  Num Buc:    Value          Size   Type   Bind Vis      Ndx Name";
3859     else
3860       OS << "  Num Buc:    Value  Size   Type   Bind Vis      Ndx Name";
3861     OS << "\n";
3862 
3863     if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
3864       this->reportUniqueWarning(std::move(E));
3865     else
3866       printGnuHashTableSymbols(*this->GnuHashTable);
3867   }
3868 }
3869 
3870 template <class ELFT> void GNUELFDumper<ELFT>::printSectionDetails() {
3871   ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
3872   OS << "There are " << to_string(Sections.size())
3873      << " section headers, starting at offset "
3874      << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n";
3875 
3876   OS << "Section Headers:\n";
3877 
3878   auto PrintFields = [&](ArrayRef<Field> V) {
3879     for (const Field &F : V)
3880       printField(F);
3881     OS << "\n";
3882   };
3883 
3884   PrintFields({{"[Nr]", 2}, {"Name", 7}});
3885 
3886   constexpr bool Is64 = ELFT::Is64Bits;
3887   PrintFields({{"Type", 7},
3888                {Is64 ? "Address" : "Addr", 23},
3889                {"Off", Is64 ? 40 : 32},
3890                {"Size", Is64 ? 47 : 39},
3891                {"ES", Is64 ? 54 : 46},
3892                {"Lk", Is64 ? 59 : 51},
3893                {"Inf", Is64 ? 62 : 54},
3894                {"Al", Is64 ? 66 : 57}});
3895   PrintFields({{"Flags", 7}});
3896 
3897   StringRef SecStrTable;
3898   if (Expected<StringRef> SecStrTableOrErr =
3899           this->Obj.getSectionStringTable(Sections, this->WarningHandler))
3900     SecStrTable = *SecStrTableOrErr;
3901   else
3902     this->reportUniqueWarning(SecStrTableOrErr.takeError());
3903 
3904   size_t SectionIndex = 0;
3905   const unsigned AddrSize = Is64 ? 16 : 8;
3906   for (const Elf_Shdr &S : Sections) {
3907     StringRef Name = "<?>";
3908     if (Expected<StringRef> NameOrErr =
3909             this->Obj.getSectionName(S, SecStrTable))
3910       Name = *NameOrErr;
3911     else
3912       this->reportUniqueWarning(NameOrErr.takeError());
3913 
3914     OS.PadToColumn(2);
3915     OS << "[" << right_justify(to_string(SectionIndex), 2) << "]";
3916     PrintFields({{Name, 7}});
3917     PrintFields(
3918         {{getSectionTypeString(this->Obj.getHeader().e_machine, S.sh_type), 7},
3919          {to_string(format_hex_no_prefix(S.sh_addr, AddrSize)), 23},
3920          {to_string(format_hex_no_prefix(S.sh_offset, 6)), Is64 ? 39 : 32},
3921          {to_string(format_hex_no_prefix(S.sh_size, 6)), Is64 ? 47 : 39},
3922          {to_string(format_hex_no_prefix(S.sh_entsize, 2)), Is64 ? 54 : 46},
3923          {to_string(S.sh_link), Is64 ? 59 : 51},
3924          {to_string(S.sh_info), Is64 ? 63 : 55},
3925          {to_string(S.sh_addralign), Is64 ? 66 : 58}});
3926 
3927     OS.PadToColumn(7);
3928     OS << "[" << to_string(format_hex_no_prefix(S.sh_flags, AddrSize)) << "]: ";
3929 
3930     DenseMap<unsigned, StringRef> FlagToName = {
3931         {SHF_WRITE, "WRITE"},           {SHF_ALLOC, "ALLOC"},
3932         {SHF_EXECINSTR, "EXEC"},        {SHF_MERGE, "MERGE"},
3933         {SHF_STRINGS, "STRINGS"},       {SHF_INFO_LINK, "INFO LINK"},
3934         {SHF_LINK_ORDER, "LINK ORDER"}, {SHF_OS_NONCONFORMING, "OS NONCONF"},
3935         {SHF_GROUP, "GROUP"},           {SHF_TLS, "TLS"},
3936         {SHF_COMPRESSED, "COMPRESSED"}, {SHF_EXCLUDE, "EXCLUDE"}};
3937 
3938     uint64_t Flags = S.sh_flags;
3939     uint64_t UnknownFlags = 0;
3940     ListSeparator LS;
3941     while (Flags) {
3942       // Take the least significant bit as a flag.
3943       uint64_t Flag = Flags & -Flags;
3944       Flags -= Flag;
3945 
3946       auto It = FlagToName.find(Flag);
3947       if (It != FlagToName.end())
3948         OS << LS << It->second;
3949       else
3950         UnknownFlags |= Flag;
3951     }
3952 
3953     auto PrintUnknownFlags = [&](uint64_t Mask, StringRef Name) {
3954       uint64_t FlagsToPrint = UnknownFlags & Mask;
3955       if (!FlagsToPrint)
3956         return;
3957 
3958       OS << LS << Name << " ("
3959          << to_string(format_hex_no_prefix(FlagsToPrint, AddrSize)) << ")";
3960       UnknownFlags &= ~Mask;
3961     };
3962 
3963     PrintUnknownFlags(SHF_MASKOS, "OS");
3964     PrintUnknownFlags(SHF_MASKPROC, "PROC");
3965     PrintUnknownFlags(uint64_t(-1), "UNKNOWN");
3966 
3967     OS << "\n";
3968     ++SectionIndex;
3969   }
3970 }
3971 
3972 static inline std::string printPhdrFlags(unsigned Flag) {
3973   std::string Str;
3974   Str = (Flag & PF_R) ? "R" : " ";
3975   Str += (Flag & PF_W) ? "W" : " ";
3976   Str += (Flag & PF_X) ? "E" : " ";
3977   return Str;
3978 }
3979 
3980 template <class ELFT>
3981 static bool checkTLSSections(const typename ELFT::Phdr &Phdr,
3982                              const typename ELFT::Shdr &Sec) {
3983   if (Sec.sh_flags & ELF::SHF_TLS) {
3984     // .tbss must only be shown in the PT_TLS segment.
3985     if (Sec.sh_type == ELF::SHT_NOBITS)
3986       return Phdr.p_type == ELF::PT_TLS;
3987 
3988     // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO
3989     // segments.
3990     return (Phdr.p_type == ELF::PT_TLS) || (Phdr.p_type == ELF::PT_LOAD) ||
3991            (Phdr.p_type == ELF::PT_GNU_RELRO);
3992   }
3993 
3994   // PT_TLS must only have SHF_TLS sections.
3995   return Phdr.p_type != ELF::PT_TLS;
3996 }
3997 
3998 template <class ELFT>
3999 static bool checkOffsets(const typename ELFT::Phdr &Phdr,
4000                          const typename ELFT::Shdr &Sec) {
4001   // SHT_NOBITS sections don't need to have an offset inside the segment.
4002   if (Sec.sh_type == ELF::SHT_NOBITS)
4003     return true;
4004 
4005   if (Sec.sh_offset < Phdr.p_offset)
4006     return false;
4007 
4008   // Only non-empty sections can be at the end of a segment.
4009   if (Sec.sh_size == 0)
4010     return (Sec.sh_offset + 1 <= Phdr.p_offset + Phdr.p_filesz);
4011   return Sec.sh_offset + Sec.sh_size <= Phdr.p_offset + Phdr.p_filesz;
4012 }
4013 
4014 // Check that an allocatable section belongs to a virtual address
4015 // space of a segment.
4016 template <class ELFT>
4017 static bool checkVMA(const typename ELFT::Phdr &Phdr,
4018                      const typename ELFT::Shdr &Sec) {
4019   if (!(Sec.sh_flags & ELF::SHF_ALLOC))
4020     return true;
4021 
4022   if (Sec.sh_addr < Phdr.p_vaddr)
4023     return false;
4024 
4025   bool IsTbss =
4026       (Sec.sh_type == ELF::SHT_NOBITS) && ((Sec.sh_flags & ELF::SHF_TLS) != 0);
4027   // .tbss is special, it only has memory in PT_TLS and has NOBITS properties.
4028   bool IsTbssInNonTLS = IsTbss && Phdr.p_type != ELF::PT_TLS;
4029   // Only non-empty sections can be at the end of a segment.
4030   if (Sec.sh_size == 0 || IsTbssInNonTLS)
4031     return Sec.sh_addr + 1 <= Phdr.p_vaddr + Phdr.p_memsz;
4032   return Sec.sh_addr + Sec.sh_size <= Phdr.p_vaddr + Phdr.p_memsz;
4033 }
4034 
4035 template <class ELFT>
4036 static bool checkPTDynamic(const typename ELFT::Phdr &Phdr,
4037                            const typename ELFT::Shdr &Sec) {
4038   if (Phdr.p_type != ELF::PT_DYNAMIC || Phdr.p_memsz == 0 || Sec.sh_size != 0)
4039     return true;
4040 
4041   // We get here when we have an empty section. Only non-empty sections can be
4042   // at the start or at the end of PT_DYNAMIC.
4043   // Is section within the phdr both based on offset and VMA?
4044   bool CheckOffset = (Sec.sh_type == ELF::SHT_NOBITS) ||
4045                      (Sec.sh_offset > Phdr.p_offset &&
4046                       Sec.sh_offset < Phdr.p_offset + Phdr.p_filesz);
4047   bool CheckVA = !(Sec.sh_flags & ELF::SHF_ALLOC) ||
4048                  (Sec.sh_addr > Phdr.p_vaddr && Sec.sh_addr < Phdr.p_memsz);
4049   return CheckOffset && CheckVA;
4050 }
4051 
4052 template <class ELFT>
4053 void GNUELFDumper<ELFT>::printProgramHeaders(
4054     bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
4055   if (PrintProgramHeaders)
4056     printProgramHeaders();
4057 
4058   // Display the section mapping along with the program headers, unless
4059   // -section-mapping is explicitly set to false.
4060   if (PrintSectionMapping != cl::BOU_FALSE)
4061     printSectionMapping();
4062 }
4063 
4064 template <class ELFT> void GNUELFDumper<ELFT>::printProgramHeaders() {
4065   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4066   const Elf_Ehdr &Header = this->Obj.getHeader();
4067   Field Fields[8] = {2,         17,        26,        37 + Bias,
4068                      48 + Bias, 56 + Bias, 64 + Bias, 68 + Bias};
4069   OS << "\nElf file type is "
4070      << printEnum(Header.e_type, makeArrayRef(ElfObjectFileType)) << "\n"
4071      << "Entry point " << format_hex(Header.e_entry, 3) << "\n"
4072      << "There are " << Header.e_phnum << " program headers,"
4073      << " starting at offset " << Header.e_phoff << "\n\n"
4074      << "Program Headers:\n";
4075   if (ELFT::Is64Bits)
4076     OS << "  Type           Offset   VirtAddr           PhysAddr         "
4077        << "  FileSiz  MemSiz   Flg Align\n";
4078   else
4079     OS << "  Type           Offset   VirtAddr   PhysAddr   FileSiz "
4080        << "MemSiz  Flg Align\n";
4081 
4082   unsigned Width = ELFT::Is64Bits ? 18 : 10;
4083   unsigned SizeWidth = ELFT::Is64Bits ? 8 : 7;
4084 
4085   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4086   if (!PhdrsOrErr) {
4087     this->reportUniqueWarning("unable to dump program headers: " +
4088                               toString(PhdrsOrErr.takeError()));
4089     return;
4090   }
4091 
4092   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4093     Fields[0].Str = getGNUPtType(Header.e_machine, Phdr.p_type);
4094     Fields[1].Str = to_string(format_hex(Phdr.p_offset, 8));
4095     Fields[2].Str = to_string(format_hex(Phdr.p_vaddr, Width));
4096     Fields[3].Str = to_string(format_hex(Phdr.p_paddr, Width));
4097     Fields[4].Str = to_string(format_hex(Phdr.p_filesz, SizeWidth));
4098     Fields[5].Str = to_string(format_hex(Phdr.p_memsz, SizeWidth));
4099     Fields[6].Str = printPhdrFlags(Phdr.p_flags);
4100     Fields[7].Str = to_string(format_hex(Phdr.p_align, 1));
4101     for (const Field &F : Fields)
4102       printField(F);
4103     if (Phdr.p_type == ELF::PT_INTERP) {
4104       OS << "\n";
4105       auto ReportBadInterp = [&](const Twine &Msg) {
4106         this->reportUniqueWarning(
4107             "unable to read program interpreter name at offset 0x" +
4108             Twine::utohexstr(Phdr.p_offset) + ": " + Msg);
4109       };
4110 
4111       if (Phdr.p_offset >= this->Obj.getBufSize()) {
4112         ReportBadInterp("it goes past the end of the file (0x" +
4113                         Twine::utohexstr(this->Obj.getBufSize()) + ")");
4114         continue;
4115       }
4116 
4117       const char *Data =
4118           reinterpret_cast<const char *>(this->Obj.base()) + Phdr.p_offset;
4119       size_t MaxSize = this->Obj.getBufSize() - Phdr.p_offset;
4120       size_t Len = strnlen(Data, MaxSize);
4121       if (Len == MaxSize) {
4122         ReportBadInterp("it is not null-terminated");
4123         continue;
4124       }
4125 
4126       OS << "      [Requesting program interpreter: ";
4127       OS << StringRef(Data, Len) << "]";
4128     }
4129     OS << "\n";
4130   }
4131 }
4132 
4133 template <class ELFT> void GNUELFDumper<ELFT>::printSectionMapping() {
4134   OS << "\n Section to Segment mapping:\n  Segment Sections...\n";
4135   DenseSet<const Elf_Shdr *> BelongsToSegment;
4136   int Phnum = 0;
4137 
4138   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4139   if (!PhdrsOrErr) {
4140     this->reportUniqueWarning(
4141         "can't read program headers to build section to segment mapping: " +
4142         toString(PhdrsOrErr.takeError()));
4143     return;
4144   }
4145 
4146   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4147     std::string Sections;
4148     OS << format("   %2.2d     ", Phnum++);
4149     // Check if each section is in a segment and then print mapping.
4150     for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4151       if (Sec.sh_type == ELF::SHT_NULL)
4152         continue;
4153 
4154       // readelf additionally makes sure it does not print zero sized sections
4155       // at end of segments and for PT_DYNAMIC both start and end of section
4156       // .tbss must only be shown in PT_TLS section.
4157       if (checkTLSSections<ELFT>(Phdr, Sec) && checkOffsets<ELFT>(Phdr, Sec) &&
4158           checkVMA<ELFT>(Phdr, Sec) && checkPTDynamic<ELFT>(Phdr, Sec)) {
4159         Sections +=
4160             unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4161             " ";
4162         BelongsToSegment.insert(&Sec);
4163       }
4164     }
4165     OS << Sections << "\n";
4166     OS.flush();
4167   }
4168 
4169   // Display sections that do not belong to a segment.
4170   std::string Sections;
4171   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4172     if (BelongsToSegment.find(&Sec) == BelongsToSegment.end())
4173       Sections +=
4174           unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4175           ' ';
4176   }
4177   if (!Sections.empty()) {
4178     OS << "   None  " << Sections << '\n';
4179     OS.flush();
4180   }
4181 }
4182 
4183 namespace {
4184 
4185 template <class ELFT>
4186 RelSymbol<ELFT> getSymbolForReloc(const ELFDumper<ELFT> &Dumper,
4187                                   const Relocation<ELFT> &Reloc) {
4188   using Elf_Sym = typename ELFT::Sym;
4189   auto WarnAndReturn = [&](const Elf_Sym *Sym,
4190                            const Twine &Reason) -> RelSymbol<ELFT> {
4191     Dumper.reportUniqueWarning(
4192         "unable to get name of the dynamic symbol with index " +
4193         Twine(Reloc.Symbol) + ": " + Reason);
4194     return {Sym, "<corrupt>"};
4195   };
4196 
4197   ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols();
4198   const Elf_Sym *FirstSym = Symbols.begin();
4199   if (!FirstSym)
4200     return WarnAndReturn(nullptr, "no dynamic symbol table found");
4201 
4202   // We might have an object without a section header. In this case the size of
4203   // Symbols is zero, because there is no way to know the size of the dynamic
4204   // table. We should allow this case and not print a warning.
4205   if (!Symbols.empty() && Reloc.Symbol >= Symbols.size())
4206     return WarnAndReturn(
4207         nullptr,
4208         "index is greater than or equal to the number of dynamic symbols (" +
4209             Twine(Symbols.size()) + ")");
4210 
4211   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
4212   const uint64_t FileSize = Obj.getBufSize();
4213   const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) +
4214                              (uint64_t)Reloc.Symbol * sizeof(Elf_Sym);
4215   if (SymOffset + sizeof(Elf_Sym) > FileSize)
4216     return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(SymOffset) +
4217                                       " goes past the end of the file (0x" +
4218                                       Twine::utohexstr(FileSize) + ")");
4219 
4220   const Elf_Sym *Sym = FirstSym + Reloc.Symbol;
4221   Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable());
4222   if (!ErrOrName)
4223     return WarnAndReturn(Sym, toString(ErrOrName.takeError()));
4224 
4225   return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(*ErrOrName)};
4226 }
4227 } // namespace
4228 
4229 template <class ELFT>
4230 static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj,
4231                                    typename ELFT::DynRange Tags) {
4232   size_t Max = 0;
4233   for (const typename ELFT::Dyn &Dyn : Tags)
4234     Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size());
4235   return Max;
4236 }
4237 
4238 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicTable() {
4239   Elf_Dyn_Range Table = this->dynamic_table();
4240   if (Table.empty())
4241     return;
4242 
4243   OS << "Dynamic section at offset "
4244      << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable.Addr) -
4245                        this->Obj.base(),
4246                    1)
4247      << " contains " << Table.size() << " entries:\n";
4248 
4249   // The type name is surrounded with round brackets, hence add 2.
4250   size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2;
4251   // The "Name/Value" column should be indented from the "Type" column by N
4252   // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
4253   // space (1) = 3.
4254   OS << "  Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type"
4255      << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
4256 
4257   std::string ValueFmt = " %-" + std::to_string(MaxTagSize) + "s ";
4258   for (auto Entry : Table) {
4259     uintX_t Tag = Entry.getTag();
4260     std::string Type =
4261         std::string("(") + this->Obj.getDynamicTagAsString(Tag).c_str() + ")";
4262     std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
4263     OS << "  " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10)
4264        << format(ValueFmt.c_str(), Type.c_str()) << Value << "\n";
4265   }
4266 }
4267 
4268 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicRelocations() {
4269   this->printDynamicRelocationsHelper();
4270 }
4271 
4272 template <class ELFT>
4273 void ELFDumper<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) {
4274   printRelRelaReloc(R, getSymbolForReloc(*this, R));
4275 }
4276 
4277 template <class ELFT>
4278 void ELFDumper<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) {
4279   this->forEachRelocationDo(
4280       Sec, opts::RawRelr,
4281       [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
4282           const Elf_Shdr *SymTab) { printReloc(R, Ndx, Sec, SymTab); },
4283       [&](const Elf_Relr &R) { printRelrReloc(R); });
4284 }
4285 
4286 template <class ELFT> void ELFDumper<ELFT>::printDynamicRelocationsHelper() {
4287   const bool IsMips64EL = this->Obj.isMips64EL();
4288   if (this->DynRelaRegion.Size > 0) {
4289     printDynamicRelocHeader(ELF::SHT_RELA, "RELA", this->DynRelaRegion);
4290     for (const Elf_Rela &Rela :
4291          this->DynRelaRegion.template getAsArrayRef<Elf_Rela>())
4292       printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
4293   }
4294 
4295   if (this->DynRelRegion.Size > 0) {
4296     printDynamicRelocHeader(ELF::SHT_REL, "REL", this->DynRelRegion);
4297     for (const Elf_Rel &Rel :
4298          this->DynRelRegion.template getAsArrayRef<Elf_Rel>())
4299       printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4300   }
4301 
4302   if (this->DynRelrRegion.Size > 0) {
4303     printDynamicRelocHeader(ELF::SHT_REL, "RELR", this->DynRelrRegion);
4304     Elf_Relr_Range Relrs =
4305         this->DynRelrRegion.template getAsArrayRef<Elf_Relr>();
4306     for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs))
4307       printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4308   }
4309 
4310   if (this->DynPLTRelRegion.Size) {
4311     if (this->DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) {
4312       printDynamicRelocHeader(ELF::SHT_RELA, "PLT", this->DynPLTRelRegion);
4313       for (const Elf_Rela &Rela :
4314            this->DynPLTRelRegion.template getAsArrayRef<Elf_Rela>())
4315         printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
4316     } else {
4317       printDynamicRelocHeader(ELF::SHT_REL, "PLT", this->DynPLTRelRegion);
4318       for (const Elf_Rel &Rel :
4319            this->DynPLTRelRegion.template getAsArrayRef<Elf_Rel>())
4320         printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4321     }
4322   }
4323 }
4324 
4325 template <class ELFT>
4326 void GNUELFDumper<ELFT>::printGNUVersionSectionProlog(
4327     const typename ELFT::Shdr &Sec, const Twine &Label, unsigned EntriesNum) {
4328   // Don't inline the SecName, because it might report a warning to stderr and
4329   // corrupt the output.
4330   StringRef SecName = this->getPrintableSectionName(Sec);
4331   OS << Label << " section '" << SecName << "' "
4332      << "contains " << EntriesNum << " entries:\n";
4333 
4334   StringRef LinkedSecName = "<corrupt>";
4335   if (Expected<const typename ELFT::Shdr *> LinkedSecOrErr =
4336           this->Obj.getSection(Sec.sh_link))
4337     LinkedSecName = this->getPrintableSectionName(**LinkedSecOrErr);
4338   else
4339     this->reportUniqueWarning("invalid section linked to " +
4340                               this->describe(Sec) + ": " +
4341                               toString(LinkedSecOrErr.takeError()));
4342 
4343   OS << " Addr: " << format_hex_no_prefix(Sec.sh_addr, 16)
4344      << "  Offset: " << format_hex(Sec.sh_offset, 8)
4345      << "  Link: " << Sec.sh_link << " (" << LinkedSecName << ")\n";
4346 }
4347 
4348 template <class ELFT>
4349 void GNUELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
4350   if (!Sec)
4351     return;
4352 
4353   printGNUVersionSectionProlog(*Sec, "Version symbols",
4354                                Sec->sh_size / sizeof(Elf_Versym));
4355   Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
4356       this->getVersionTable(*Sec, /*SymTab=*/nullptr,
4357                             /*StrTab=*/nullptr, /*SymTabSec=*/nullptr);
4358   if (!VerTableOrErr) {
4359     this->reportUniqueWarning(VerTableOrErr.takeError());
4360     return;
4361   }
4362 
4363   SmallVector<Optional<VersionEntry>, 0> *VersionMap = nullptr;
4364   if (Expected<SmallVector<Optional<VersionEntry>, 0> *> MapOrErr =
4365           this->getVersionMap())
4366     VersionMap = *MapOrErr;
4367   else
4368     this->reportUniqueWarning(MapOrErr.takeError());
4369 
4370   ArrayRef<Elf_Versym> VerTable = *VerTableOrErr;
4371   std::vector<StringRef> Versions;
4372   for (size_t I = 0, E = VerTable.size(); I < E; ++I) {
4373     unsigned Ndx = VerTable[I].vs_index;
4374     if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) {
4375       Versions.emplace_back(Ndx == VER_NDX_LOCAL ? "*local*" : "*global*");
4376       continue;
4377     }
4378 
4379     if (!VersionMap) {
4380       Versions.emplace_back("<corrupt>");
4381       continue;
4382     }
4383 
4384     bool IsDefault;
4385     Expected<StringRef> NameOrErr = this->Obj.getSymbolVersionByIndex(
4386         Ndx, IsDefault, *VersionMap, /*IsSymHidden=*/None);
4387     if (!NameOrErr) {
4388       this->reportUniqueWarning("unable to get a version for entry " +
4389                                 Twine(I) + " of " + this->describe(*Sec) +
4390                                 ": " + toString(NameOrErr.takeError()));
4391       Versions.emplace_back("<corrupt>");
4392       continue;
4393     }
4394     Versions.emplace_back(*NameOrErr);
4395   }
4396 
4397   // readelf prints 4 entries per line.
4398   uint64_t Entries = VerTable.size();
4399   for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) {
4400     OS << "  " << format_hex_no_prefix(VersymRow, 3) << ":";
4401     for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) {
4402       unsigned Ndx = VerTable[VersymRow + I].vs_index;
4403       OS << format("%4x%c", Ndx & VERSYM_VERSION,
4404                    Ndx & VERSYM_HIDDEN ? 'h' : ' ');
4405       OS << left_justify("(" + std::string(Versions[VersymRow + I]) + ")", 13);
4406     }
4407     OS << '\n';
4408   }
4409   OS << '\n';
4410 }
4411 
4412 static std::string versionFlagToString(unsigned Flags) {
4413   if (Flags == 0)
4414     return "none";
4415 
4416   std::string Ret;
4417   auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) {
4418     if (!(Flags & Flag))
4419       return;
4420     if (!Ret.empty())
4421       Ret += " | ";
4422     Ret += Name;
4423     Flags &= ~Flag;
4424   };
4425 
4426   AddFlag(VER_FLG_BASE, "BASE");
4427   AddFlag(VER_FLG_WEAK, "WEAK");
4428   AddFlag(VER_FLG_INFO, "INFO");
4429   AddFlag(~0, "<unknown>");
4430   return Ret;
4431 }
4432 
4433 template <class ELFT>
4434 void GNUELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
4435   if (!Sec)
4436     return;
4437 
4438   printGNUVersionSectionProlog(*Sec, "Version definition", Sec->sh_info);
4439 
4440   Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
4441   if (!V) {
4442     this->reportUniqueWarning(V.takeError());
4443     return;
4444   }
4445 
4446   for (const VerDef &Def : *V) {
4447     OS << format("  0x%04x: Rev: %u  Flags: %s  Index: %u  Cnt: %u  Name: %s\n",
4448                  Def.Offset, Def.Version,
4449                  versionFlagToString(Def.Flags).c_str(), Def.Ndx, Def.Cnt,
4450                  Def.Name.data());
4451     unsigned I = 0;
4452     for (const VerdAux &Aux : Def.AuxV)
4453       OS << format("  0x%04x: Parent %u: %s\n", Aux.Offset, ++I,
4454                    Aux.Name.data());
4455   }
4456 
4457   OS << '\n';
4458 }
4459 
4460 template <class ELFT>
4461 void GNUELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
4462   if (!Sec)
4463     return;
4464 
4465   unsigned VerneedNum = Sec->sh_info;
4466   printGNUVersionSectionProlog(*Sec, "Version needs", VerneedNum);
4467 
4468   Expected<std::vector<VerNeed>> V =
4469       this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
4470   if (!V) {
4471     this->reportUniqueWarning(V.takeError());
4472     return;
4473   }
4474 
4475   for (const VerNeed &VN : *V) {
4476     OS << format("  0x%04x: Version: %u  File: %s  Cnt: %u\n", VN.Offset,
4477                  VN.Version, VN.File.data(), VN.Cnt);
4478     for (const VernAux &Aux : VN.AuxV)
4479       OS << format("  0x%04x:   Name: %s  Flags: %s  Version: %u\n", Aux.Offset,
4480                    Aux.Name.data(), versionFlagToString(Aux.Flags).c_str(),
4481                    Aux.Other);
4482   }
4483   OS << '\n';
4484 }
4485 
4486 template <class ELFT>
4487 void GNUELFDumper<ELFT>::printHashHistogram(const Elf_Hash &HashTable) {
4488   size_t NBucket = HashTable.nbucket;
4489   size_t NChain = HashTable.nchain;
4490   ArrayRef<Elf_Word> Buckets = HashTable.buckets();
4491   ArrayRef<Elf_Word> Chains = HashTable.chains();
4492   size_t TotalSyms = 0;
4493   // If hash table is correct, we have at least chains with 0 length
4494   size_t MaxChain = 1;
4495   size_t CumulativeNonZero = 0;
4496 
4497   if (NChain == 0 || NBucket == 0)
4498     return;
4499 
4500   std::vector<size_t> ChainLen(NBucket, 0);
4501   // Go over all buckets and and note chain lengths of each bucket (total
4502   // unique chain lengths).
4503   for (size_t B = 0; B < NBucket; B++) {
4504     std::vector<bool> Visited(NChain);
4505     for (size_t C = Buckets[B]; C < NChain; C = Chains[C]) {
4506       if (C == ELF::STN_UNDEF)
4507         break;
4508       if (Visited[C]) {
4509         this->reportUniqueWarning(".hash section is invalid: bucket " +
4510                                   Twine(C) +
4511                                   ": a cycle was detected in the linked chain");
4512         break;
4513       }
4514       Visited[C] = true;
4515       if (MaxChain <= ++ChainLen[B])
4516         MaxChain++;
4517     }
4518     TotalSyms += ChainLen[B];
4519   }
4520 
4521   if (!TotalSyms)
4522     return;
4523 
4524   std::vector<size_t> Count(MaxChain, 0);
4525   // Count how long is the chain for each bucket
4526   for (size_t B = 0; B < NBucket; B++)
4527     ++Count[ChainLen[B]];
4528   // Print Number of buckets with each chain lengths and their cumulative
4529   // coverage of the symbols
4530   OS << "Histogram for bucket list length (total of " << NBucket
4531      << " buckets)\n"
4532      << " Length  Number     % of total  Coverage\n";
4533   for (size_t I = 0; I < MaxChain; I++) {
4534     CumulativeNonZero += Count[I] * I;
4535     OS << format("%7lu  %-10lu (%5.1f%%)     %5.1f%%\n", I, Count[I],
4536                  (Count[I] * 100.0) / NBucket,
4537                  (CumulativeNonZero * 100.0) / TotalSyms);
4538   }
4539 }
4540 
4541 template <class ELFT>
4542 void GNUELFDumper<ELFT>::printGnuHashHistogram(
4543     const Elf_GnuHash &GnuHashTable) {
4544   Expected<ArrayRef<Elf_Word>> ChainsOrErr =
4545       getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHashTable);
4546   if (!ChainsOrErr) {
4547     this->reportUniqueWarning("unable to print the GNU hash table histogram: " +
4548                               toString(ChainsOrErr.takeError()));
4549     return;
4550   }
4551 
4552   ArrayRef<Elf_Word> Chains = *ChainsOrErr;
4553   size_t Symndx = GnuHashTable.symndx;
4554   size_t TotalSyms = 0;
4555   size_t MaxChain = 1;
4556   size_t CumulativeNonZero = 0;
4557 
4558   size_t NBucket = GnuHashTable.nbuckets;
4559   if (Chains.empty() || NBucket == 0)
4560     return;
4561 
4562   ArrayRef<Elf_Word> Buckets = GnuHashTable.buckets();
4563   std::vector<size_t> ChainLen(NBucket, 0);
4564   for (size_t B = 0; B < NBucket; B++) {
4565     if (!Buckets[B])
4566       continue;
4567     size_t Len = 1;
4568     for (size_t C = Buckets[B] - Symndx;
4569          C < Chains.size() && (Chains[C] & 1) == 0; C++)
4570       if (MaxChain < ++Len)
4571         MaxChain++;
4572     ChainLen[B] = Len;
4573     TotalSyms += Len;
4574   }
4575   MaxChain++;
4576 
4577   if (!TotalSyms)
4578     return;
4579 
4580   std::vector<size_t> Count(MaxChain, 0);
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 `.gnu.hash' 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 // Hash histogram shows statistics of how efficient the hash was for the
4597 // dynamic symbol table. The table shows the number of hash buckets for
4598 // different lengths of chains as an absolute number and percentage of the total
4599 // buckets, and the cumulative coverage of symbols for each set of buckets.
4600 template <class ELFT> void GNUELFDumper<ELFT>::printHashHistograms() {
4601   // Print histogram for the .hash section.
4602   if (this->HashTable) {
4603     if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
4604       this->reportUniqueWarning(std::move(E));
4605     else
4606       printHashHistogram(*this->HashTable);
4607   }
4608 
4609   // Print histogram for the .gnu.hash section.
4610   if (this->GnuHashTable) {
4611     if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
4612       this->reportUniqueWarning(std::move(E));
4613     else
4614       printGnuHashHistogram(*this->GnuHashTable);
4615   }
4616 }
4617 
4618 template <class ELFT> void GNUELFDumper<ELFT>::printCGProfile() {
4619   OS << "GNUStyle::printCGProfile not implemented\n";
4620 }
4621 
4622 template <class ELFT> void GNUELFDumper<ELFT>::printBBAddrMaps() {
4623   OS << "GNUStyle::printBBAddrMaps not implemented\n";
4624 }
4625 
4626 static Expected<std::vector<uint64_t>> toULEB128Array(ArrayRef<uint8_t> Data) {
4627   std::vector<uint64_t> Ret;
4628   const uint8_t *Cur = Data.begin();
4629   const uint8_t *End = Data.end();
4630   while (Cur != End) {
4631     unsigned Size;
4632     const char *Err;
4633     Ret.push_back(decodeULEB128(Cur, &Size, End, &Err));
4634     if (Err)
4635       return createError(Err);
4636     Cur += Size;
4637   }
4638   return Ret;
4639 }
4640 
4641 template <class ELFT>
4642 static Expected<std::vector<uint64_t>>
4643 decodeAddrsigSection(const ELFFile<ELFT> &Obj, const typename ELFT::Shdr &Sec) {
4644   Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Sec);
4645   if (!ContentsOrErr)
4646     return ContentsOrErr.takeError();
4647 
4648   if (Expected<std::vector<uint64_t>> SymsOrErr =
4649           toULEB128Array(*ContentsOrErr))
4650     return *SymsOrErr;
4651   else
4652     return createError("unable to decode " + describe(Obj, Sec) + ": " +
4653                        toString(SymsOrErr.takeError()));
4654 }
4655 
4656 template <class ELFT> void GNUELFDumper<ELFT>::printAddrsig() {
4657   if (!this->DotAddrsigSec)
4658     return;
4659 
4660   Expected<std::vector<uint64_t>> SymsOrErr =
4661       decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
4662   if (!SymsOrErr) {
4663     this->reportUniqueWarning(SymsOrErr.takeError());
4664     return;
4665   }
4666 
4667   StringRef Name = this->getPrintableSectionName(*this->DotAddrsigSec);
4668   OS << "\nAddress-significant symbols section '" << Name << "'"
4669      << " contains " << SymsOrErr->size() << " entries:\n";
4670   OS << "   Num: Name\n";
4671 
4672   Field Fields[2] = {0, 8};
4673   size_t SymIndex = 0;
4674   for (uint64_t Sym : *SymsOrErr) {
4675     Fields[0].Str = to_string(format_decimal(++SymIndex, 6)) + ":";
4676     Fields[1].Str = this->getStaticSymbolName(Sym);
4677     for (const Field &Entry : Fields)
4678       printField(Entry);
4679     OS << "\n";
4680   }
4681 }
4682 
4683 template <typename ELFT>
4684 static std::string getGNUProperty(uint32_t Type, uint32_t DataSize,
4685                                   ArrayRef<uint8_t> Data) {
4686   std::string str;
4687   raw_string_ostream OS(str);
4688   uint32_t PrData;
4689   auto DumpBit = [&](uint32_t Flag, StringRef Name) {
4690     if (PrData & Flag) {
4691       PrData &= ~Flag;
4692       OS << Name;
4693       if (PrData)
4694         OS << ", ";
4695     }
4696   };
4697 
4698   switch (Type) {
4699   default:
4700     OS << format("<application-specific type 0x%x>", Type);
4701     return OS.str();
4702   case GNU_PROPERTY_STACK_SIZE: {
4703     OS << "stack size: ";
4704     if (DataSize == sizeof(typename ELFT::uint))
4705       OS << formatv("{0:x}",
4706                     (uint64_t)(*(const typename ELFT::Addr *)Data.data()));
4707     else
4708       OS << format("<corrupt length: 0x%x>", DataSize);
4709     return OS.str();
4710   }
4711   case GNU_PROPERTY_NO_COPY_ON_PROTECTED:
4712     OS << "no copy on protected";
4713     if (DataSize)
4714       OS << format(" <corrupt length: 0x%x>", DataSize);
4715     return OS.str();
4716   case GNU_PROPERTY_AARCH64_FEATURE_1_AND:
4717   case GNU_PROPERTY_X86_FEATURE_1_AND:
4718     OS << ((Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) ? "aarch64 feature: "
4719                                                         : "x86 feature: ");
4720     if (DataSize != 4) {
4721       OS << format("<corrupt length: 0x%x>", DataSize);
4722       return OS.str();
4723     }
4724     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
4725     if (PrData == 0) {
4726       OS << "<None>";
4727       return OS.str();
4728     }
4729     if (Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) {
4730       DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI, "BTI");
4731       DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC, "PAC");
4732     } else {
4733       DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT, "IBT");
4734       DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK, "SHSTK");
4735     }
4736     if (PrData)
4737       OS << format("<unknown flags: 0x%x>", PrData);
4738     return OS.str();
4739   case GNU_PROPERTY_X86_FEATURE_2_NEEDED:
4740   case GNU_PROPERTY_X86_FEATURE_2_USED:
4741     OS << "x86 feature "
4742        << (Type == GNU_PROPERTY_X86_FEATURE_2_NEEDED ? "needed: " : "used: ");
4743     if (DataSize != 4) {
4744       OS << format("<corrupt length: 0x%x>", DataSize);
4745       return OS.str();
4746     }
4747     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
4748     if (PrData == 0) {
4749       OS << "<None>";
4750       return OS.str();
4751     }
4752     DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86, "x86");
4753     DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87, "x87");
4754     DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX, "MMX");
4755     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM, "XMM");
4756     DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM, "YMM");
4757     DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM, "ZMM");
4758     DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR, "FXSR");
4759     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE, "XSAVE");
4760     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT, "XSAVEOPT");
4761     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC, "XSAVEC");
4762     if (PrData)
4763       OS << format("<unknown flags: 0x%x>", PrData);
4764     return OS.str();
4765   case GNU_PROPERTY_X86_ISA_1_NEEDED:
4766   case GNU_PROPERTY_X86_ISA_1_USED:
4767     OS << "x86 ISA "
4768        << (Type == GNU_PROPERTY_X86_ISA_1_NEEDED ? "needed: " : "used: ");
4769     if (DataSize != 4) {
4770       OS << format("<corrupt length: 0x%x>", DataSize);
4771       return OS.str();
4772     }
4773     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
4774     if (PrData == 0) {
4775       OS << "<None>";
4776       return OS.str();
4777     }
4778     DumpBit(GNU_PROPERTY_X86_ISA_1_BASELINE, "x86-64-baseline");
4779     DumpBit(GNU_PROPERTY_X86_ISA_1_V2, "x86-64-v2");
4780     DumpBit(GNU_PROPERTY_X86_ISA_1_V3, "x86-64-v3");
4781     DumpBit(GNU_PROPERTY_X86_ISA_1_V4, "x86-64-v4");
4782     if (PrData)
4783       OS << format("<unknown flags: 0x%x>", PrData);
4784     return OS.str();
4785   }
4786 }
4787 
4788 template <typename ELFT>
4789 static SmallVector<std::string, 4> getGNUPropertyList(ArrayRef<uint8_t> Arr) {
4790   using Elf_Word = typename ELFT::Word;
4791 
4792   SmallVector<std::string, 4> Properties;
4793   while (Arr.size() >= 8) {
4794     uint32_t Type = *reinterpret_cast<const Elf_Word *>(Arr.data());
4795     uint32_t DataSize = *reinterpret_cast<const Elf_Word *>(Arr.data() + 4);
4796     Arr = Arr.drop_front(8);
4797 
4798     // Take padding size into account if present.
4799     uint64_t PaddedSize = alignTo(DataSize, sizeof(typename ELFT::uint));
4800     std::string str;
4801     raw_string_ostream OS(str);
4802     if (Arr.size() < PaddedSize) {
4803       OS << format("<corrupt type (0x%x) datasz: 0x%x>", Type, DataSize);
4804       Properties.push_back(OS.str());
4805       break;
4806     }
4807     Properties.push_back(
4808         getGNUProperty<ELFT>(Type, DataSize, Arr.take_front(PaddedSize)));
4809     Arr = Arr.drop_front(PaddedSize);
4810   }
4811 
4812   if (!Arr.empty())
4813     Properties.push_back("<corrupted GNU_PROPERTY_TYPE_0>");
4814 
4815   return Properties;
4816 }
4817 
4818 struct GNUAbiTag {
4819   std::string OSName;
4820   std::string ABI;
4821   bool IsValid;
4822 };
4823 
4824 template <typename ELFT> static GNUAbiTag getGNUAbiTag(ArrayRef<uint8_t> Desc) {
4825   typedef typename ELFT::Word Elf_Word;
4826 
4827   ArrayRef<Elf_Word> Words(reinterpret_cast<const Elf_Word *>(Desc.begin()),
4828                            reinterpret_cast<const Elf_Word *>(Desc.end()));
4829 
4830   if (Words.size() < 4)
4831     return {"", "", /*IsValid=*/false};
4832 
4833   static const char *OSNames[] = {
4834       "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable", "NaCl",
4835   };
4836   StringRef OSName = "Unknown";
4837   if (Words[0] < array_lengthof(OSNames))
4838     OSName = OSNames[Words[0]];
4839   uint32_t Major = Words[1], Minor = Words[2], Patch = Words[3];
4840   std::string str;
4841   raw_string_ostream ABI(str);
4842   ABI << Major << "." << Minor << "." << Patch;
4843   return {std::string(OSName), ABI.str(), /*IsValid=*/true};
4844 }
4845 
4846 static std::string getGNUBuildId(ArrayRef<uint8_t> Desc) {
4847   std::string str;
4848   raw_string_ostream OS(str);
4849   for (uint8_t B : Desc)
4850     OS << format_hex_no_prefix(B, 2);
4851   return OS.str();
4852 }
4853 
4854 static StringRef getGNUGoldVersion(ArrayRef<uint8_t> Desc) {
4855   return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
4856 }
4857 
4858 template <typename ELFT>
4859 static bool printGNUNote(raw_ostream &OS, uint32_t NoteType,
4860                          ArrayRef<uint8_t> Desc) {
4861   // Return true if we were able to pretty-print the note, false otherwise.
4862   switch (NoteType) {
4863   default:
4864     return false;
4865   case ELF::NT_GNU_ABI_TAG: {
4866     const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
4867     if (!AbiTag.IsValid)
4868       OS << "    <corrupt GNU_ABI_TAG>";
4869     else
4870       OS << "    OS: " << AbiTag.OSName << ", ABI: " << AbiTag.ABI;
4871     break;
4872   }
4873   case ELF::NT_GNU_BUILD_ID: {
4874     OS << "    Build ID: " << getGNUBuildId(Desc);
4875     break;
4876   }
4877   case ELF::NT_GNU_GOLD_VERSION:
4878     OS << "    Version: " << getGNUGoldVersion(Desc);
4879     break;
4880   case ELF::NT_GNU_PROPERTY_TYPE_0:
4881     OS << "    Properties:";
4882     for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
4883       OS << "    " << Property << "\n";
4884     break;
4885   }
4886   OS << '\n';
4887   return true;
4888 }
4889 
4890 static const EnumEntry<unsigned> FreeBSDFeatureCtlFlags[] = {
4891     {"ASLR_DISABLE", NT_FREEBSD_FCTL_ASLR_DISABLE},
4892     {"PROTMAX_DISABLE", NT_FREEBSD_FCTL_PROTMAX_DISABLE},
4893     {"STKGAP_DISABLE", NT_FREEBSD_FCTL_STKGAP_DISABLE},
4894     {"WXNEEDED", NT_FREEBSD_FCTL_WXNEEDED},
4895     {"LA48", NT_FREEBSD_FCTL_LA48},
4896     {"ASG_DISABLE", NT_FREEBSD_FCTL_ASG_DISABLE},
4897 };
4898 
4899 struct FreeBSDNote {
4900   std::string Type;
4901   std::string Value;
4902 };
4903 
4904 template <typename ELFT>
4905 static Optional<FreeBSDNote>
4906 getFreeBSDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc, bool IsCore) {
4907   if (IsCore)
4908     return None; // No pretty-printing yet.
4909   switch (NoteType) {
4910   case ELF::NT_FREEBSD_ABI_TAG:
4911     if (Desc.size() != 4)
4912       return None;
4913     return FreeBSDNote{
4914         "ABI tag",
4915         utostr(support::endian::read32<ELFT::TargetEndianness>(Desc.data()))};
4916   case ELF::NT_FREEBSD_ARCH_TAG:
4917     return FreeBSDNote{"Arch tag", toStringRef(Desc).str()};
4918   case ELF::NT_FREEBSD_FEATURE_CTL: {
4919     if (Desc.size() != 4)
4920       return None;
4921     unsigned Value =
4922         support::endian::read32<ELFT::TargetEndianness>(Desc.data());
4923     std::string FlagsStr;
4924     raw_string_ostream OS(FlagsStr);
4925     printFlags(Value, makeArrayRef(FreeBSDFeatureCtlFlags), OS);
4926     if (OS.str().empty())
4927       OS << "0x" << utohexstr(Value);
4928     else
4929       OS << "(0x" << utohexstr(Value) << ")";
4930     return FreeBSDNote{"Feature flags", OS.str()};
4931   }
4932   default:
4933     return None;
4934   }
4935 }
4936 
4937 struct AMDNote {
4938   std::string Type;
4939   std::string Value;
4940 };
4941 
4942 template <typename ELFT>
4943 static AMDNote getAMDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
4944   switch (NoteType) {
4945   default:
4946     return {"", ""};
4947   case ELF::NT_AMD_AMDGPU_HSA_METADATA:
4948     return {
4949         "HSA Metadata",
4950         std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
4951   case ELF::NT_AMD_AMDGPU_ISA:
4952     return {
4953         "ISA Version",
4954         std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
4955   }
4956 }
4957 
4958 struct AMDGPUNote {
4959   std::string Type;
4960   std::string Value;
4961 };
4962 
4963 template <typename ELFT>
4964 static AMDGPUNote getAMDGPUNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
4965   switch (NoteType) {
4966   default:
4967     return {"", ""};
4968   case ELF::NT_AMDGPU_METADATA: {
4969     StringRef MsgPackString =
4970         StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
4971     msgpack::Document MsgPackDoc;
4972     if (!MsgPackDoc.readFromBlob(MsgPackString, /*Multi=*/false))
4973       return {"", ""};
4974 
4975     AMDGPU::HSAMD::V3::MetadataVerifier Verifier(true);
4976     std::string HSAMetadataString;
4977     if (!Verifier.verify(MsgPackDoc.getRoot()))
4978       HSAMetadataString = "Invalid AMDGPU Metadata\n";
4979 
4980     raw_string_ostream StrOS(HSAMetadataString);
4981     if (MsgPackDoc.getRoot().isScalar()) {
4982       // TODO: passing a scalar root to toYAML() asserts:
4983       // (PolymorphicTraits<T>::getKind(Val) != NodeKind::Scalar &&
4984       //    "plain scalar documents are not supported")
4985       // To avoid this crash we print the raw data instead.
4986       return {"", ""};
4987     }
4988     MsgPackDoc.toYAML(StrOS);
4989     return {"AMDGPU Metadata", StrOS.str()};
4990   }
4991   }
4992 }
4993 
4994 struct CoreFileMapping {
4995   uint64_t Start, End, Offset;
4996   StringRef Filename;
4997 };
4998 
4999 struct CoreNote {
5000   uint64_t PageSize;
5001   std::vector<CoreFileMapping> Mappings;
5002 };
5003 
5004 static Expected<CoreNote> readCoreNote(DataExtractor Desc) {
5005   // Expected format of the NT_FILE note description:
5006   // 1. # of file mappings (call it N)
5007   // 2. Page size
5008   // 3. N (start, end, offset) triples
5009   // 4. N packed filenames (null delimited)
5010   // Each field is an Elf_Addr, except for filenames which are char* strings.
5011 
5012   CoreNote Ret;
5013   const int Bytes = Desc.getAddressSize();
5014 
5015   if (!Desc.isValidOffsetForAddress(2))
5016     return createError("the note of size 0x" + Twine::utohexstr(Desc.size()) +
5017                        " is too short, expected at least 0x" +
5018                        Twine::utohexstr(Bytes * 2));
5019   if (Desc.getData().back() != 0)
5020     return createError("the note is not NUL terminated");
5021 
5022   uint64_t DescOffset = 0;
5023   uint64_t FileCount = Desc.getAddress(&DescOffset);
5024   Ret.PageSize = Desc.getAddress(&DescOffset);
5025 
5026   if (!Desc.isValidOffsetForAddress(3 * FileCount * Bytes))
5027     return createError("unable to read file mappings (found " +
5028                        Twine(FileCount) + "): the note of size 0x" +
5029                        Twine::utohexstr(Desc.size()) + " is too short");
5030 
5031   uint64_t FilenamesOffset = 0;
5032   DataExtractor Filenames(
5033       Desc.getData().drop_front(DescOffset + 3 * FileCount * Bytes),
5034       Desc.isLittleEndian(), Desc.getAddressSize());
5035 
5036   Ret.Mappings.resize(FileCount);
5037   size_t I = 0;
5038   for (CoreFileMapping &Mapping : Ret.Mappings) {
5039     ++I;
5040     if (!Filenames.isValidOffsetForDataOfSize(FilenamesOffset, 1))
5041       return createError(
5042           "unable to read the file name for the mapping with index " +
5043           Twine(I) + ": the note of size 0x" + Twine::utohexstr(Desc.size()) +
5044           " is truncated");
5045     Mapping.Start = Desc.getAddress(&DescOffset);
5046     Mapping.End = Desc.getAddress(&DescOffset);
5047     Mapping.Offset = Desc.getAddress(&DescOffset);
5048     Mapping.Filename = Filenames.getCStrRef(&FilenamesOffset);
5049   }
5050 
5051   return Ret;
5052 }
5053 
5054 template <typename ELFT>
5055 static void printCoreNote(raw_ostream &OS, const CoreNote &Note) {
5056   // Length of "0x<address>" string.
5057   const int FieldWidth = ELFT::Is64Bits ? 18 : 10;
5058 
5059   OS << "    Page size: " << format_decimal(Note.PageSize, 0) << '\n';
5060   OS << "    " << right_justify("Start", FieldWidth) << "  "
5061      << right_justify("End", FieldWidth) << "  "
5062      << right_justify("Page Offset", FieldWidth) << '\n';
5063   for (const CoreFileMapping &Mapping : Note.Mappings) {
5064     OS << "    " << format_hex(Mapping.Start, FieldWidth) << "  "
5065        << format_hex(Mapping.End, FieldWidth) << "  "
5066        << format_hex(Mapping.Offset, FieldWidth) << "\n        "
5067        << Mapping.Filename << '\n';
5068   }
5069 }
5070 
5071 static const NoteType GenericNoteTypes[] = {
5072     {ELF::NT_VERSION, "NT_VERSION (version)"},
5073     {ELF::NT_ARCH, "NT_ARCH (architecture)"},
5074     {ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN, "OPEN"},
5075     {ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC, "func"},
5076 };
5077 
5078 static const NoteType GNUNoteTypes[] = {
5079     {ELF::NT_GNU_ABI_TAG, "NT_GNU_ABI_TAG (ABI version tag)"},
5080     {ELF::NT_GNU_HWCAP, "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"},
5081     {ELF::NT_GNU_BUILD_ID, "NT_GNU_BUILD_ID (unique build ID bitstring)"},
5082     {ELF::NT_GNU_GOLD_VERSION, "NT_GNU_GOLD_VERSION (gold version)"},
5083     {ELF::NT_GNU_PROPERTY_TYPE_0, "NT_GNU_PROPERTY_TYPE_0 (property note)"},
5084 };
5085 
5086 static const NoteType FreeBSDCoreNoteTypes[] = {
5087     {ELF::NT_FREEBSD_THRMISC, "NT_THRMISC (thrmisc structure)"},
5088     {ELF::NT_FREEBSD_PROCSTAT_PROC, "NT_PROCSTAT_PROC (proc data)"},
5089     {ELF::NT_FREEBSD_PROCSTAT_FILES, "NT_PROCSTAT_FILES (files data)"},
5090     {ELF::NT_FREEBSD_PROCSTAT_VMMAP, "NT_PROCSTAT_VMMAP (vmmap data)"},
5091     {ELF::NT_FREEBSD_PROCSTAT_GROUPS, "NT_PROCSTAT_GROUPS (groups data)"},
5092     {ELF::NT_FREEBSD_PROCSTAT_UMASK, "NT_PROCSTAT_UMASK (umask data)"},
5093     {ELF::NT_FREEBSD_PROCSTAT_RLIMIT, "NT_PROCSTAT_RLIMIT (rlimit data)"},
5094     {ELF::NT_FREEBSD_PROCSTAT_OSREL, "NT_PROCSTAT_OSREL (osreldate data)"},
5095     {ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS,
5096      "NT_PROCSTAT_PSSTRINGS (ps_strings data)"},
5097     {ELF::NT_FREEBSD_PROCSTAT_AUXV, "NT_PROCSTAT_AUXV (auxv data)"},
5098 };
5099 
5100 static const NoteType FreeBSDNoteTypes[] = {
5101     {ELF::NT_FREEBSD_ABI_TAG, "NT_FREEBSD_ABI_TAG (ABI version tag)"},
5102     {ELF::NT_FREEBSD_NOINIT_TAG, "NT_FREEBSD_NOINIT_TAG (no .init tag)"},
5103     {ELF::NT_FREEBSD_ARCH_TAG, "NT_FREEBSD_ARCH_TAG (architecture tag)"},
5104     {ELF::NT_FREEBSD_FEATURE_CTL,
5105      "NT_FREEBSD_FEATURE_CTL (FreeBSD feature control)"},
5106 };
5107 
5108 static const NoteType AMDNoteTypes[] = {
5109     {ELF::NT_AMD_AMDGPU_HSA_METADATA,
5110      "NT_AMD_AMDGPU_HSA_METADATA (HSA Metadata)"},
5111     {ELF::NT_AMD_AMDGPU_ISA, "NT_AMD_AMDGPU_ISA (ISA Version)"},
5112     {ELF::NT_AMD_AMDGPU_PAL_METADATA,
5113      "NT_AMD_AMDGPU_PAL_METADATA (PAL Metadata)"},
5114 };
5115 
5116 static const NoteType AMDGPUNoteTypes[] = {
5117     {ELF::NT_AMDGPU_METADATA, "NT_AMDGPU_METADATA (AMDGPU Metadata)"},
5118 };
5119 
5120 static const NoteType CoreNoteTypes[] = {
5121     {ELF::NT_PRSTATUS, "NT_PRSTATUS (prstatus structure)"},
5122     {ELF::NT_FPREGSET, "NT_FPREGSET (floating point registers)"},
5123     {ELF::NT_PRPSINFO, "NT_PRPSINFO (prpsinfo structure)"},
5124     {ELF::NT_TASKSTRUCT, "NT_TASKSTRUCT (task structure)"},
5125     {ELF::NT_AUXV, "NT_AUXV (auxiliary vector)"},
5126     {ELF::NT_PSTATUS, "NT_PSTATUS (pstatus structure)"},
5127     {ELF::NT_FPREGS, "NT_FPREGS (floating point registers)"},
5128     {ELF::NT_PSINFO, "NT_PSINFO (psinfo structure)"},
5129     {ELF::NT_LWPSTATUS, "NT_LWPSTATUS (lwpstatus_t structure)"},
5130     {ELF::NT_LWPSINFO, "NT_LWPSINFO (lwpsinfo_t structure)"},
5131     {ELF::NT_WIN32PSTATUS, "NT_WIN32PSTATUS (win32_pstatus structure)"},
5132 
5133     {ELF::NT_PPC_VMX, "NT_PPC_VMX (ppc Altivec registers)"},
5134     {ELF::NT_PPC_VSX, "NT_PPC_VSX (ppc VSX registers)"},
5135     {ELF::NT_PPC_TAR, "NT_PPC_TAR (ppc TAR register)"},
5136     {ELF::NT_PPC_PPR, "NT_PPC_PPR (ppc PPR register)"},
5137     {ELF::NT_PPC_DSCR, "NT_PPC_DSCR (ppc DSCR register)"},
5138     {ELF::NT_PPC_EBB, "NT_PPC_EBB (ppc EBB registers)"},
5139     {ELF::NT_PPC_PMU, "NT_PPC_PMU (ppc PMU registers)"},
5140     {ELF::NT_PPC_TM_CGPR, "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"},
5141     {ELF::NT_PPC_TM_CFPR,
5142      "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"},
5143     {ELF::NT_PPC_TM_CVMX,
5144      "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"},
5145     {ELF::NT_PPC_TM_CVSX, "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"},
5146     {ELF::NT_PPC_TM_SPR, "NT_PPC_TM_SPR (ppc TM special purpose registers)"},
5147     {ELF::NT_PPC_TM_CTAR, "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"},
5148     {ELF::NT_PPC_TM_CPPR, "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"},
5149     {ELF::NT_PPC_TM_CDSCR, "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"},
5150 
5151     {ELF::NT_386_TLS, "NT_386_TLS (x86 TLS information)"},
5152     {ELF::NT_386_IOPERM, "NT_386_IOPERM (x86 I/O permissions)"},
5153     {ELF::NT_X86_XSTATE, "NT_X86_XSTATE (x86 XSAVE extended state)"},
5154 
5155     {ELF::NT_S390_HIGH_GPRS, "NT_S390_HIGH_GPRS (s390 upper register halves)"},
5156     {ELF::NT_S390_TIMER, "NT_S390_TIMER (s390 timer register)"},
5157     {ELF::NT_S390_TODCMP, "NT_S390_TODCMP (s390 TOD comparator register)"},
5158     {ELF::NT_S390_TODPREG, "NT_S390_TODPREG (s390 TOD programmable register)"},
5159     {ELF::NT_S390_CTRS, "NT_S390_CTRS (s390 control registers)"},
5160     {ELF::NT_S390_PREFIX, "NT_S390_PREFIX (s390 prefix register)"},
5161     {ELF::NT_S390_LAST_BREAK,
5162      "NT_S390_LAST_BREAK (s390 last breaking event address)"},
5163     {ELF::NT_S390_SYSTEM_CALL,
5164      "NT_S390_SYSTEM_CALL (s390 system call restart data)"},
5165     {ELF::NT_S390_TDB, "NT_S390_TDB (s390 transaction diagnostic block)"},
5166     {ELF::NT_S390_VXRS_LOW,
5167      "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"},
5168     {ELF::NT_S390_VXRS_HIGH, "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"},
5169     {ELF::NT_S390_GS_CB, "NT_S390_GS_CB (s390 guarded-storage registers)"},
5170     {ELF::NT_S390_GS_BC,
5171      "NT_S390_GS_BC (s390 guarded-storage broadcast control)"},
5172 
5173     {ELF::NT_ARM_VFP, "NT_ARM_VFP (arm VFP registers)"},
5174     {ELF::NT_ARM_TLS, "NT_ARM_TLS (AArch TLS registers)"},
5175     {ELF::NT_ARM_HW_BREAK,
5176      "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"},
5177     {ELF::NT_ARM_HW_WATCH,
5178      "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"},
5179 
5180     {ELF::NT_FILE, "NT_FILE (mapped files)"},
5181     {ELF::NT_PRXFPREG, "NT_PRXFPREG (user_xfpregs structure)"},
5182     {ELF::NT_SIGINFO, "NT_SIGINFO (siginfo_t data)"},
5183 };
5184 
5185 template <class ELFT>
5186 StringRef getNoteTypeName(const typename ELFT::Note &Note, unsigned ELFType) {
5187   uint32_t Type = Note.getType();
5188   auto FindNote = [&](ArrayRef<NoteType> V) -> StringRef {
5189     for (const NoteType &N : V)
5190       if (N.ID == Type)
5191         return N.Name;
5192     return "";
5193   };
5194 
5195   StringRef Name = Note.getName();
5196   if (Name == "GNU")
5197     return FindNote(GNUNoteTypes);
5198   if (Name == "FreeBSD") {
5199     if (ELFType == ELF::ET_CORE) {
5200       // FreeBSD also places the generic core notes in the FreeBSD namespace.
5201       StringRef Result = FindNote(FreeBSDCoreNoteTypes);
5202       if (!Result.empty())
5203         return Result;
5204       return FindNote(CoreNoteTypes);
5205     } else {
5206       return FindNote(FreeBSDNoteTypes);
5207     }
5208   }
5209   if (Name == "AMD")
5210     return FindNote(AMDNoteTypes);
5211   if (Name == "AMDGPU")
5212     return FindNote(AMDGPUNoteTypes);
5213 
5214   if (ELFType == ELF::ET_CORE)
5215     return FindNote(CoreNoteTypes);
5216   return FindNote(GenericNoteTypes);
5217 }
5218 
5219 template <class ELFT>
5220 static void printNotesHelper(
5221     const ELFDumper<ELFT> &Dumper,
5222     llvm::function_ref<void(Optional<StringRef>, typename ELFT::Off,
5223                             typename ELFT::Addr)>
5224         StartNotesFn,
5225     llvm::function_ref<Error(const typename ELFT::Note &, bool)> ProcessNoteFn,
5226     llvm::function_ref<void()> FinishNotesFn) {
5227   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
5228   bool IsCoreFile = Obj.getHeader().e_type == ELF::ET_CORE;
5229 
5230   ArrayRef<typename ELFT::Shdr> Sections = cantFail(Obj.sections());
5231   if (!IsCoreFile && !Sections.empty()) {
5232     for (const typename ELFT::Shdr &S : Sections) {
5233       if (S.sh_type != SHT_NOTE)
5234         continue;
5235       StartNotesFn(expectedToOptional(Obj.getSectionName(S)), S.sh_offset,
5236                    S.sh_size);
5237       Error Err = Error::success();
5238       size_t I = 0;
5239       for (const typename ELFT::Note Note : Obj.notes(S, Err)) {
5240         if (Error E = ProcessNoteFn(Note, IsCoreFile))
5241           Dumper.reportUniqueWarning(
5242               "unable to read note with index " + Twine(I) + " from the " +
5243               describe(Obj, S) + ": " + toString(std::move(E)));
5244         ++I;
5245       }
5246       if (Err)
5247         Dumper.reportUniqueWarning("unable to read notes from the " +
5248                                    describe(Obj, S) + ": " +
5249                                    toString(std::move(Err)));
5250       FinishNotesFn();
5251     }
5252     return;
5253   }
5254 
5255   Expected<ArrayRef<typename ELFT::Phdr>> PhdrsOrErr = Obj.program_headers();
5256   if (!PhdrsOrErr) {
5257     Dumper.reportUniqueWarning(
5258         "unable to read program headers to locate the PT_NOTE segment: " +
5259         toString(PhdrsOrErr.takeError()));
5260     return;
5261   }
5262 
5263   for (size_t I = 0, E = (*PhdrsOrErr).size(); I != E; ++I) {
5264     const typename ELFT::Phdr &P = (*PhdrsOrErr)[I];
5265     if (P.p_type != PT_NOTE)
5266       continue;
5267     StartNotesFn(/*SecName=*/None, P.p_offset, P.p_filesz);
5268     Error Err = Error::success();
5269     size_t Index = 0;
5270     for (const typename ELFT::Note Note : Obj.notes(P, Err)) {
5271       if (Error E = ProcessNoteFn(Note, IsCoreFile))
5272         Dumper.reportUniqueWarning("unable to read note with index " +
5273                                    Twine(Index) +
5274                                    " from the PT_NOTE segment with index " +
5275                                    Twine(I) + ": " + toString(std::move(E)));
5276       ++Index;
5277     }
5278     if (Err)
5279       Dumper.reportUniqueWarning(
5280           "unable to read notes from the PT_NOTE segment with index " +
5281           Twine(I) + ": " + toString(std::move(Err)));
5282     FinishNotesFn();
5283   }
5284 }
5285 
5286 template <class ELFT> void GNUELFDumper<ELFT>::printNotes() {
5287   bool IsFirstHeader = true;
5288   auto PrintHeader = [&](Optional<StringRef> SecName,
5289                          const typename ELFT::Off Offset,
5290                          const typename ELFT::Addr Size) {
5291     // Print a newline between notes sections to match GNU readelf.
5292     if (!IsFirstHeader) {
5293       OS << '\n';
5294     } else {
5295       IsFirstHeader = false;
5296     }
5297 
5298     OS << "Displaying notes found ";
5299 
5300     if (SecName)
5301       OS << "in: " << *SecName << "\n";
5302     else
5303       OS << "at file offset " << format_hex(Offset, 10) << " with length "
5304          << format_hex(Size, 10) << ":\n";
5305 
5306     OS << "  Owner                Data size \tDescription\n";
5307   };
5308 
5309   auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
5310     StringRef Name = Note.getName();
5311     ArrayRef<uint8_t> Descriptor = Note.getDesc();
5312     Elf_Word Type = Note.getType();
5313 
5314     // Print the note owner/type.
5315     OS << "  " << left_justify(Name, 20) << ' '
5316        << format_hex(Descriptor.size(), 10) << '\t';
5317 
5318     StringRef NoteType =
5319         getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
5320     if (!NoteType.empty())
5321       OS << NoteType << '\n';
5322     else
5323       OS << "Unknown note type: (" << format_hex(Type, 10) << ")\n";
5324 
5325     // Print the description, or fallback to printing raw bytes for unknown
5326     // owners/if we fail to pretty-print the contents.
5327     if (Name == "GNU") {
5328       if (printGNUNote<ELFT>(OS, Type, Descriptor))
5329         return Error::success();
5330     } else if (Name == "FreeBSD") {
5331       if (Optional<FreeBSDNote> N =
5332               getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
5333         OS << "    " << N->Type << ": " << N->Value << '\n';
5334         return Error::success();
5335       }
5336     } else if (Name == "AMD") {
5337       const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
5338       if (!N.Type.empty()) {
5339         OS << "    " << N.Type << ":\n        " << N.Value << '\n';
5340         return Error::success();
5341       }
5342     } else if (Name == "AMDGPU") {
5343       const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
5344       if (!N.Type.empty()) {
5345         OS << "    " << N.Type << ":\n        " << N.Value << '\n';
5346         return Error::success();
5347       }
5348     } else if (Name == "CORE") {
5349       if (Type == ELF::NT_FILE) {
5350         DataExtractor DescExtractor(Descriptor,
5351                                     ELFT::TargetEndianness == support::little,
5352                                     sizeof(Elf_Addr));
5353         if (Expected<CoreNote> NoteOrErr = readCoreNote(DescExtractor)) {
5354           printCoreNote<ELFT>(OS, *NoteOrErr);
5355           return Error::success();
5356         } else {
5357           return NoteOrErr.takeError();
5358         }
5359       }
5360     }
5361     if (!Descriptor.empty()) {
5362       OS << "   description data:";
5363       for (uint8_t B : Descriptor)
5364         OS << " " << format("%02x", B);
5365       OS << '\n';
5366     }
5367     return Error::success();
5368   };
5369 
5370   printNotesHelper(*this, PrintHeader, ProcessNote, []() {});
5371 }
5372 
5373 template <class ELFT> void GNUELFDumper<ELFT>::printELFLinkerOptions() {
5374   OS << "printELFLinkerOptions not implemented!\n";
5375 }
5376 
5377 template <class ELFT>
5378 void ELFDumper<ELFT>::printDependentLibsHelper(
5379     function_ref<void(const Elf_Shdr &)> OnSectionStart,
5380     function_ref<void(StringRef, uint64_t)> OnLibEntry) {
5381   auto Warn = [this](unsigned SecNdx, StringRef Msg) {
5382     this->reportUniqueWarning("SHT_LLVM_DEPENDENT_LIBRARIES section at index " +
5383                               Twine(SecNdx) + " is broken: " + Msg);
5384   };
5385 
5386   unsigned I = -1;
5387   for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
5388     ++I;
5389     if (Shdr.sh_type != ELF::SHT_LLVM_DEPENDENT_LIBRARIES)
5390       continue;
5391 
5392     OnSectionStart(Shdr);
5393 
5394     Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Shdr);
5395     if (!ContentsOrErr) {
5396       Warn(I, toString(ContentsOrErr.takeError()));
5397       continue;
5398     }
5399 
5400     ArrayRef<uint8_t> Contents = *ContentsOrErr;
5401     if (!Contents.empty() && Contents.back() != 0) {
5402       Warn(I, "the content is not null-terminated");
5403       continue;
5404     }
5405 
5406     for (const uint8_t *I = Contents.begin(), *E = Contents.end(); I < E;) {
5407       StringRef Lib((const char *)I);
5408       OnLibEntry(Lib, I - Contents.begin());
5409       I += Lib.size() + 1;
5410     }
5411   }
5412 }
5413 
5414 template <class ELFT>
5415 void ELFDumper<ELFT>::forEachRelocationDo(
5416     const Elf_Shdr &Sec, bool RawRelr,
5417     llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
5418                             const Elf_Shdr &, const Elf_Shdr *)>
5419         RelRelaFn,
5420     llvm::function_ref<void(const Elf_Relr &)> RelrFn) {
5421   auto Warn = [&](Error &&E,
5422                   const Twine &Prefix = "unable to read relocations from") {
5423     this->reportUniqueWarning(Prefix + " " + describe(Sec) + ": " +
5424                               toString(std::move(E)));
5425   };
5426 
5427   // SHT_RELR/SHT_ANDROID_RELR sections do not have an associated symbol table.
5428   // For them we should not treat the value of the sh_link field as an index of
5429   // a symbol table.
5430   const Elf_Shdr *SymTab;
5431   if (Sec.sh_type != ELF::SHT_RELR && Sec.sh_type != ELF::SHT_ANDROID_RELR) {
5432     Expected<const Elf_Shdr *> SymTabOrErr = Obj.getSection(Sec.sh_link);
5433     if (!SymTabOrErr) {
5434       Warn(SymTabOrErr.takeError(), "unable to locate a symbol table for");
5435       return;
5436     }
5437     SymTab = *SymTabOrErr;
5438   }
5439 
5440   unsigned RelNdx = 0;
5441   const bool IsMips64EL = this->Obj.isMips64EL();
5442   switch (Sec.sh_type) {
5443   case ELF::SHT_REL:
5444     if (Expected<Elf_Rel_Range> RangeOrErr = Obj.rels(Sec)) {
5445       for (const Elf_Rel &R : *RangeOrErr)
5446         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5447     } else {
5448       Warn(RangeOrErr.takeError());
5449     }
5450     break;
5451   case ELF::SHT_RELA:
5452     if (Expected<Elf_Rela_Range> RangeOrErr = Obj.relas(Sec)) {
5453       for (const Elf_Rela &R : *RangeOrErr)
5454         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5455     } else {
5456       Warn(RangeOrErr.takeError());
5457     }
5458     break;
5459   case ELF::SHT_RELR:
5460   case ELF::SHT_ANDROID_RELR: {
5461     Expected<Elf_Relr_Range> RangeOrErr = Obj.relrs(Sec);
5462     if (!RangeOrErr) {
5463       Warn(RangeOrErr.takeError());
5464       break;
5465     }
5466     if (RawRelr) {
5467       for (const Elf_Relr &R : *RangeOrErr)
5468         RelrFn(R);
5469       break;
5470     }
5471 
5472     for (const Elf_Rel &R : Obj.decode_relrs(*RangeOrErr))
5473       RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec,
5474                 /*SymTab=*/nullptr);
5475     break;
5476   }
5477   case ELF::SHT_ANDROID_REL:
5478   case ELF::SHT_ANDROID_RELA:
5479     if (Expected<std::vector<Elf_Rela>> RelasOrErr = Obj.android_relas(Sec)) {
5480       for (const Elf_Rela &R : *RelasOrErr)
5481         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5482     } else {
5483       Warn(RelasOrErr.takeError());
5484     }
5485     break;
5486   }
5487 }
5488 
5489 template <class ELFT>
5490 StringRef ELFDumper<ELFT>::getPrintableSectionName(const Elf_Shdr &Sec) const {
5491   StringRef Name = "<?>";
5492   if (Expected<StringRef> SecNameOrErr =
5493           Obj.getSectionName(Sec, this->WarningHandler))
5494     Name = *SecNameOrErr;
5495   else
5496     this->reportUniqueWarning("unable to get the name of " + describe(Sec) +
5497                               ": " + toString(SecNameOrErr.takeError()));
5498   return Name;
5499 }
5500 
5501 template <class ELFT> void GNUELFDumper<ELFT>::printDependentLibs() {
5502   bool SectionStarted = false;
5503   struct NameOffset {
5504     StringRef Name;
5505     uint64_t Offset;
5506   };
5507   std::vector<NameOffset> SecEntries;
5508   NameOffset Current;
5509   auto PrintSection = [&]() {
5510     OS << "Dependent libraries section " << Current.Name << " at offset "
5511        << format_hex(Current.Offset, 1) << " contains " << SecEntries.size()
5512        << " entries:\n";
5513     for (NameOffset Entry : SecEntries)
5514       OS << "  [" << format("%6" PRIx64, Entry.Offset) << "]  " << Entry.Name
5515          << "\n";
5516     OS << "\n";
5517     SecEntries.clear();
5518   };
5519 
5520   auto OnSectionStart = [&](const Elf_Shdr &Shdr) {
5521     if (SectionStarted)
5522       PrintSection();
5523     SectionStarted = true;
5524     Current.Offset = Shdr.sh_offset;
5525     Current.Name = this->getPrintableSectionName(Shdr);
5526   };
5527   auto OnLibEntry = [&](StringRef Lib, uint64_t Offset) {
5528     SecEntries.push_back(NameOffset{Lib, Offset});
5529   };
5530 
5531   this->printDependentLibsHelper(OnSectionStart, OnLibEntry);
5532   if (SectionStarted)
5533     PrintSection();
5534 }
5535 
5536 template <class ELFT>
5537 bool ELFDumper<ELFT>::printFunctionStackSize(
5538     uint64_t SymValue, Optional<const Elf_Shdr *> FunctionSec,
5539     const Elf_Shdr &StackSizeSec, DataExtractor Data, uint64_t *Offset) {
5540   uint32_t FuncSymIndex = 0;
5541   if (this->DotSymtabSec) {
5542     if (Expected<Elf_Sym_Range> SymsOrError = Obj.symbols(this->DotSymtabSec)) {
5543       uint32_t Index = (uint32_t)-1;
5544       for (const Elf_Sym &Sym : *SymsOrError) {
5545         ++Index;
5546 
5547         if (Sym.st_shndx == ELF::SHN_UNDEF || Sym.getType() != ELF::STT_FUNC)
5548           continue;
5549 
5550         if (Expected<uint64_t> SymAddrOrErr =
5551                 ObjF.toSymbolRef(this->DotSymtabSec, Index).getAddress()) {
5552           if (SymValue != *SymAddrOrErr)
5553             continue;
5554         } else {
5555           std::string Name = this->getStaticSymbolName(Index);
5556           reportUniqueWarning("unable to get address of symbol '" + Name +
5557                               "': " + toString(SymAddrOrErr.takeError()));
5558           break;
5559         }
5560 
5561         // Check if the symbol is in the right section. FunctionSec == None
5562         // means "any section".
5563         if (FunctionSec) {
5564           if (Expected<const Elf_Shdr *> SecOrErr =
5565                   Obj.getSection(Sym, this->DotSymtabSec,
5566                                  this->getShndxTable(this->DotSymtabSec))) {
5567             if (*FunctionSec != *SecOrErr)
5568               continue;
5569           } else {
5570             std::string Name = this->getStaticSymbolName(Index);
5571             // Note: it is impossible to trigger this error currently, it is
5572             // untested.
5573             reportUniqueWarning("unable to get section of symbol '" + Name +
5574                                 "': " + toString(SecOrErr.takeError()));
5575             break;
5576           }
5577         }
5578 
5579         FuncSymIndex = Index;
5580         break;
5581       }
5582     } else {
5583       reportUniqueWarning("unable to read the symbol table: " +
5584                           toString(SymsOrError.takeError()));
5585     }
5586   }
5587 
5588   std::string FuncName = "?";
5589   if (!FuncSymIndex)
5590     reportUniqueWarning(
5591         "could not identify function symbol for stack size entry in " +
5592         describe(StackSizeSec));
5593   else
5594     FuncName = this->getStaticSymbolName(FuncSymIndex);
5595 
5596   // Extract the size. The expectation is that Offset is pointing to the right
5597   // place, i.e. past the function address.
5598   Error Err = Error::success();
5599   uint64_t StackSize = Data.getULEB128(Offset, &Err);
5600   if (Err) {
5601     reportUniqueWarning("could not extract a valid stack size from " +
5602                         describe(StackSizeSec) + ": " +
5603                         toString(std::move(Err)));
5604     return false;
5605   }
5606   printStackSizeEntry(StackSize, FuncName);
5607   return true;
5608 }
5609 
5610 template <class ELFT>
5611 void GNUELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
5612                                              StringRef FuncName) {
5613   OS.PadToColumn(2);
5614   OS << format_decimal(Size, 11);
5615   OS.PadToColumn(18);
5616   OS << FuncName << "\n";
5617 }
5618 
5619 template <class ELFT>
5620 void ELFDumper<ELFT>::printStackSize(const Relocation<ELFT> &R,
5621                                      const Elf_Shdr &RelocSec, unsigned Ndx,
5622                                      const Elf_Shdr *SymTab,
5623                                      const Elf_Shdr *FunctionSec,
5624                                      const Elf_Shdr &StackSizeSec,
5625                                      const RelocationResolver &Resolver,
5626                                      DataExtractor Data) {
5627   // This function ignores potentially erroneous input, unless it is directly
5628   // related to stack size reporting.
5629   const Elf_Sym *Sym = nullptr;
5630   Expected<RelSymbol<ELFT>> TargetOrErr = this->getRelocationTarget(R, SymTab);
5631   if (!TargetOrErr)
5632     reportUniqueWarning("unable to get the target of relocation with index " +
5633                         Twine(Ndx) + " in " + describe(RelocSec) + ": " +
5634                         toString(TargetOrErr.takeError()));
5635   else
5636     Sym = TargetOrErr->Sym;
5637 
5638   uint64_t RelocSymValue = 0;
5639   if (Sym) {
5640     Expected<const Elf_Shdr *> SectionOrErr =
5641         this->Obj.getSection(*Sym, SymTab, this->getShndxTable(SymTab));
5642     if (!SectionOrErr) {
5643       reportUniqueWarning(
5644           "cannot identify the section for relocation symbol '" +
5645           (*TargetOrErr).Name + "': " + toString(SectionOrErr.takeError()));
5646     } else if (*SectionOrErr != FunctionSec) {
5647       reportUniqueWarning("relocation symbol '" + (*TargetOrErr).Name +
5648                           "' is not in the expected section");
5649       // Pretend that the symbol is in the correct section and report its
5650       // stack size anyway.
5651       FunctionSec = *SectionOrErr;
5652     }
5653 
5654     RelocSymValue = Sym->st_value;
5655   }
5656 
5657   uint64_t Offset = R.Offset;
5658   if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
5659     reportUniqueWarning("found invalid relocation offset (0x" +
5660                         Twine::utohexstr(Offset) + ") into " +
5661                         describe(StackSizeSec) +
5662                         " while trying to extract a stack size entry");
5663     return;
5664   }
5665 
5666   uint64_t SymValue =
5667       Resolver(R.Type, Offset, RelocSymValue, Data.getAddress(&Offset),
5668                R.Addend.getValueOr(0));
5669   this->printFunctionStackSize(SymValue, FunctionSec, StackSizeSec, Data,
5670                                &Offset);
5671 }
5672 
5673 template <class ELFT>
5674 void ELFDumper<ELFT>::printNonRelocatableStackSizes(
5675     std::function<void()> PrintHeader) {
5676   // This function ignores potentially erroneous input, unless it is directly
5677   // related to stack size reporting.
5678   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
5679     if (this->getPrintableSectionName(Sec) != ".stack_sizes")
5680       continue;
5681     PrintHeader();
5682     ArrayRef<uint8_t> Contents =
5683         unwrapOrError(this->FileName, Obj.getSectionContents(Sec));
5684     DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
5685     uint64_t Offset = 0;
5686     while (Offset < Contents.size()) {
5687       // The function address is followed by a ULEB representing the stack
5688       // size. Check for an extra byte before we try to process the entry.
5689       if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
5690         reportUniqueWarning(
5691             describe(Sec) +
5692             " ended while trying to extract a stack size entry");
5693         break;
5694       }
5695       uint64_t SymValue = Data.getAddress(&Offset);
5696       if (!printFunctionStackSize(SymValue, /*FunctionSec=*/None, Sec, Data,
5697                                   &Offset))
5698         break;
5699     }
5700   }
5701 }
5702 
5703 template <class ELFT>
5704 void ELFDumper<ELFT>::printRelocatableStackSizes(
5705     std::function<void()> PrintHeader) {
5706   // Build a map between stack size sections and their corresponding relocation
5707   // sections.
5708   llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> StackSizeRelocMap;
5709   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
5710     StringRef SectionName;
5711     if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec))
5712       SectionName = *NameOrErr;
5713     else
5714       consumeError(NameOrErr.takeError());
5715 
5716     // A stack size section that we haven't encountered yet is mapped to the
5717     // null section until we find its corresponding relocation section.
5718     if (SectionName == ".stack_sizes")
5719       if (StackSizeRelocMap
5720               .insert(std::make_pair(&Sec, (const Elf_Shdr *)nullptr))
5721               .second)
5722         continue;
5723 
5724     // Check relocation sections if they are relocating contents of a
5725     // stack sizes section.
5726     if (Sec.sh_type != ELF::SHT_RELA && Sec.sh_type != ELF::SHT_REL)
5727       continue;
5728 
5729     Expected<const Elf_Shdr *> RelSecOrErr = Obj.getSection(Sec.sh_info);
5730     if (!RelSecOrErr) {
5731       reportUniqueWarning(describe(Sec) +
5732                           ": failed to get a relocated section: " +
5733                           toString(RelSecOrErr.takeError()));
5734       continue;
5735     }
5736 
5737     const Elf_Shdr *ContentsSec = *RelSecOrErr;
5738     if (this->getPrintableSectionName(**RelSecOrErr) != ".stack_sizes")
5739       continue;
5740 
5741     // Insert a mapping from the stack sizes section to its relocation section.
5742     StackSizeRelocMap[ContentsSec] = &Sec;
5743   }
5744 
5745   for (const auto &StackSizeMapEntry : StackSizeRelocMap) {
5746     PrintHeader();
5747     const Elf_Shdr *StackSizesELFSec = StackSizeMapEntry.first;
5748     const Elf_Shdr *RelocSec = StackSizeMapEntry.second;
5749 
5750     // Warn about stack size sections without a relocation section.
5751     if (!RelocSec) {
5752       reportWarning(createError(".stack_sizes (" + describe(*StackSizesELFSec) +
5753                                 ") does not have a corresponding "
5754                                 "relocation section"),
5755                     FileName);
5756       continue;
5757     }
5758 
5759     // A .stack_sizes section header's sh_link field is supposed to point
5760     // to the section that contains the functions whose stack sizes are
5761     // described in it.
5762     const Elf_Shdr *FunctionSec = unwrapOrError(
5763         this->FileName, Obj.getSection(StackSizesELFSec->sh_link));
5764 
5765     SupportsRelocation IsSupportedFn;
5766     RelocationResolver Resolver;
5767     std::tie(IsSupportedFn, Resolver) = getRelocationResolver(this->ObjF);
5768     ArrayRef<uint8_t> Contents =
5769         unwrapOrError(this->FileName, Obj.getSectionContents(*StackSizesELFSec));
5770     DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
5771 
5772     forEachRelocationDo(
5773         *RelocSec, /*RawRelr=*/false,
5774         [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
5775             const Elf_Shdr *SymTab) {
5776           if (!IsSupportedFn || !IsSupportedFn(R.Type)) {
5777             reportUniqueWarning(
5778                 describe(*RelocSec) +
5779                 " contains an unsupported relocation with index " + Twine(Ndx) +
5780                 ": " + Obj.getRelocationTypeName(R.Type));
5781             return;
5782           }
5783 
5784           this->printStackSize(R, *RelocSec, Ndx, SymTab, FunctionSec,
5785                                *StackSizesELFSec, Resolver, Data);
5786         },
5787         [](const Elf_Relr &) {
5788           llvm_unreachable("can't get here, because we only support "
5789                            "SHT_REL/SHT_RELA sections");
5790         });
5791   }
5792 }
5793 
5794 template <class ELFT>
5795 void GNUELFDumper<ELFT>::printStackSizes() {
5796   bool HeaderHasBeenPrinted = false;
5797   auto PrintHeader = [&]() {
5798     if (HeaderHasBeenPrinted)
5799       return;
5800     OS << "\nStack Sizes:\n";
5801     OS.PadToColumn(9);
5802     OS << "Size";
5803     OS.PadToColumn(18);
5804     OS << "Function\n";
5805     HeaderHasBeenPrinted = true;
5806   };
5807 
5808   // For non-relocatable objects, look directly for sections whose name starts
5809   // with .stack_sizes and process the contents.
5810   if (this->Obj.getHeader().e_type == ELF::ET_REL)
5811     this->printRelocatableStackSizes(PrintHeader);
5812   else
5813     this->printNonRelocatableStackSizes(PrintHeader);
5814 }
5815 
5816 template <class ELFT>
5817 void GNUELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
5818   size_t Bias = ELFT::Is64Bits ? 8 : 0;
5819   auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
5820     OS.PadToColumn(2);
5821     OS << format_hex_no_prefix(Parser.getGotAddress(E), 8 + Bias);
5822     OS.PadToColumn(11 + Bias);
5823     OS << format_decimal(Parser.getGotOffset(E), 6) << "(gp)";
5824     OS.PadToColumn(22 + Bias);
5825     OS << format_hex_no_prefix(*E, 8 + Bias);
5826     OS.PadToColumn(31 + 2 * Bias);
5827     OS << Purpose << "\n";
5828   };
5829 
5830   OS << (Parser.IsStatic ? "Static GOT:\n" : "Primary GOT:\n");
5831   OS << " Canonical gp value: "
5832      << format_hex_no_prefix(Parser.getGp(), 8 + Bias) << "\n\n";
5833 
5834   OS << " Reserved entries:\n";
5835   if (ELFT::Is64Bits)
5836     OS << "           Address     Access          Initial Purpose\n";
5837   else
5838     OS << "   Address     Access  Initial Purpose\n";
5839   PrintEntry(Parser.getGotLazyResolver(), "Lazy resolver");
5840   if (Parser.getGotModulePointer())
5841     PrintEntry(Parser.getGotModulePointer(), "Module pointer (GNU extension)");
5842 
5843   if (!Parser.getLocalEntries().empty()) {
5844     OS << "\n";
5845     OS << " Local entries:\n";
5846     if (ELFT::Is64Bits)
5847       OS << "           Address     Access          Initial\n";
5848     else
5849       OS << "   Address     Access  Initial\n";
5850     for (auto &E : Parser.getLocalEntries())
5851       PrintEntry(&E, "");
5852   }
5853 
5854   if (Parser.IsStatic)
5855     return;
5856 
5857   if (!Parser.getGlobalEntries().empty()) {
5858     OS << "\n";
5859     OS << " Global entries:\n";
5860     if (ELFT::Is64Bits)
5861       OS << "           Address     Access          Initial         Sym.Val."
5862          << " Type    Ndx Name\n";
5863     else
5864       OS << "   Address     Access  Initial Sym.Val. Type    Ndx Name\n";
5865 
5866     DataRegion<Elf_Word> ShndxTable(
5867         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
5868     for (auto &E : Parser.getGlobalEntries()) {
5869       const Elf_Sym &Sym = *Parser.getGotSym(&E);
5870       const Elf_Sym &FirstSym = this->dynamic_symbols()[0];
5871       std::string SymName = this->getFullSymbolName(
5872           Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
5873 
5874       OS.PadToColumn(2);
5875       OS << to_string(format_hex_no_prefix(Parser.getGotAddress(&E), 8 + Bias));
5876       OS.PadToColumn(11 + Bias);
5877       OS << to_string(format_decimal(Parser.getGotOffset(&E), 6)) + "(gp)";
5878       OS.PadToColumn(22 + Bias);
5879       OS << to_string(format_hex_no_prefix(E, 8 + Bias));
5880       OS.PadToColumn(31 + 2 * Bias);
5881       OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
5882       OS.PadToColumn(40 + 3 * Bias);
5883       OS << printEnum(Sym.getType(), makeArrayRef(ElfSymbolTypes));
5884       OS.PadToColumn(48 + 3 * Bias);
5885       OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
5886                                 ShndxTable);
5887       OS.PadToColumn(52 + 3 * Bias);
5888       OS << SymName << "\n";
5889     }
5890   }
5891 
5892   if (!Parser.getOtherEntries().empty())
5893     OS << "\n Number of TLS and multi-GOT entries "
5894        << Parser.getOtherEntries().size() << "\n";
5895 }
5896 
5897 template <class ELFT>
5898 void GNUELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
5899   size_t Bias = ELFT::Is64Bits ? 8 : 0;
5900   auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
5901     OS.PadToColumn(2);
5902     OS << format_hex_no_prefix(Parser.getPltAddress(E), 8 + Bias);
5903     OS.PadToColumn(11 + Bias);
5904     OS << format_hex_no_prefix(*E, 8 + Bias);
5905     OS.PadToColumn(20 + 2 * Bias);
5906     OS << Purpose << "\n";
5907   };
5908 
5909   OS << "PLT GOT:\n\n";
5910 
5911   OS << " Reserved entries:\n";
5912   OS << "   Address  Initial Purpose\n";
5913   PrintEntry(Parser.getPltLazyResolver(), "PLT lazy resolver");
5914   if (Parser.getPltModulePointer())
5915     PrintEntry(Parser.getPltModulePointer(), "Module pointer");
5916 
5917   if (!Parser.getPltEntries().empty()) {
5918     OS << "\n";
5919     OS << " Entries:\n";
5920     OS << "   Address  Initial Sym.Val. Type    Ndx Name\n";
5921     DataRegion<Elf_Word> ShndxTable(
5922         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
5923     for (auto &E : Parser.getPltEntries()) {
5924       const Elf_Sym &Sym = *Parser.getPltSym(&E);
5925       const Elf_Sym &FirstSym = *cantFail(
5926           this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
5927       std::string SymName = this->getFullSymbolName(
5928           Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
5929 
5930       OS.PadToColumn(2);
5931       OS << to_string(format_hex_no_prefix(Parser.getPltAddress(&E), 8 + Bias));
5932       OS.PadToColumn(11 + Bias);
5933       OS << to_string(format_hex_no_prefix(E, 8 + Bias));
5934       OS.PadToColumn(20 + 2 * Bias);
5935       OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
5936       OS.PadToColumn(29 + 3 * Bias);
5937       OS << printEnum(Sym.getType(), makeArrayRef(ElfSymbolTypes));
5938       OS.PadToColumn(37 + 3 * Bias);
5939       OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
5940                                 ShndxTable);
5941       OS.PadToColumn(41 + 3 * Bias);
5942       OS << SymName << "\n";
5943     }
5944   }
5945 }
5946 
5947 template <class ELFT>
5948 Expected<const Elf_Mips_ABIFlags<ELFT> *>
5949 getMipsAbiFlagsSection(const ELFDumper<ELFT> &Dumper) {
5950   const typename ELFT::Shdr *Sec = Dumper.findSectionByName(".MIPS.abiflags");
5951   if (Sec == nullptr)
5952     return nullptr;
5953 
5954   constexpr StringRef ErrPrefix = "unable to read the .MIPS.abiflags section: ";
5955   Expected<ArrayRef<uint8_t>> DataOrErr =
5956       Dumper.getElfObject().getELFFile().getSectionContents(*Sec);
5957   if (!DataOrErr)
5958     return createError(ErrPrefix + toString(DataOrErr.takeError()));
5959 
5960   if (DataOrErr->size() != sizeof(Elf_Mips_ABIFlags<ELFT>))
5961     return createError(ErrPrefix + "it has a wrong size (" +
5962         Twine(DataOrErr->size()) + ")");
5963   return reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(DataOrErr->data());
5964 }
5965 
5966 template <class ELFT> void GNUELFDumper<ELFT>::printMipsABIFlags() {
5967   const Elf_Mips_ABIFlags<ELFT> *Flags = nullptr;
5968   if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
5969           getMipsAbiFlagsSection(*this))
5970     Flags = *SecOrErr;
5971   else
5972     this->reportUniqueWarning(SecOrErr.takeError());
5973   if (!Flags)
5974     return;
5975 
5976   OS << "MIPS ABI Flags Version: " << Flags->version << "\n\n";
5977   OS << "ISA: MIPS" << int(Flags->isa_level);
5978   if (Flags->isa_rev > 1)
5979     OS << "r" << int(Flags->isa_rev);
5980   OS << "\n";
5981   OS << "GPR size: " << getMipsRegisterSize(Flags->gpr_size) << "\n";
5982   OS << "CPR1 size: " << getMipsRegisterSize(Flags->cpr1_size) << "\n";
5983   OS << "CPR2 size: " << getMipsRegisterSize(Flags->cpr2_size) << "\n";
5984   OS << "FP ABI: " << printEnum(Flags->fp_abi, makeArrayRef(ElfMipsFpABIType))
5985      << "\n";
5986   OS << "ISA Extension: "
5987      << printEnum(Flags->isa_ext, makeArrayRef(ElfMipsISAExtType)) << "\n";
5988   if (Flags->ases == 0)
5989     OS << "ASEs: None\n";
5990   else
5991     // FIXME: Print each flag on a separate line.
5992     OS << "ASEs: " << printFlags(Flags->ases, makeArrayRef(ElfMipsASEFlags))
5993        << "\n";
5994   OS << "FLAGS 1: " << format_hex_no_prefix(Flags->flags1, 8, false) << "\n";
5995   OS << "FLAGS 2: " << format_hex_no_prefix(Flags->flags2, 8, false) << "\n";
5996   OS << "\n";
5997 }
5998 
5999 template <class ELFT> void LLVMELFDumper<ELFT>::printFileHeaders() {
6000   const Elf_Ehdr &E = this->Obj.getHeader();
6001   {
6002     DictScope D(W, "ElfHeader");
6003     {
6004       DictScope D(W, "Ident");
6005       W.printBinary("Magic", makeArrayRef(E.e_ident).slice(ELF::EI_MAG0, 4));
6006       W.printEnum("Class", E.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass));
6007       W.printEnum("DataEncoding", E.e_ident[ELF::EI_DATA],
6008                   makeArrayRef(ElfDataEncoding));
6009       W.printNumber("FileVersion", E.e_ident[ELF::EI_VERSION]);
6010 
6011       auto OSABI = makeArrayRef(ElfOSABI);
6012       if (E.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH &&
6013           E.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) {
6014         switch (E.e_machine) {
6015         case ELF::EM_AMDGPU:
6016           OSABI = makeArrayRef(AMDGPUElfOSABI);
6017           break;
6018         case ELF::EM_ARM:
6019           OSABI = makeArrayRef(ARMElfOSABI);
6020           break;
6021         case ELF::EM_TI_C6000:
6022           OSABI = makeArrayRef(C6000ElfOSABI);
6023           break;
6024         }
6025       }
6026       W.printEnum("OS/ABI", E.e_ident[ELF::EI_OSABI], OSABI);
6027       W.printNumber("ABIVersion", E.e_ident[ELF::EI_ABIVERSION]);
6028       W.printBinary("Unused", makeArrayRef(E.e_ident).slice(ELF::EI_PAD));
6029     }
6030 
6031     std::string TypeStr;
6032     if (const EnumEntry<unsigned> *Ent = getObjectFileEnumEntry(E.e_type)) {
6033       TypeStr = Ent->Name.str();
6034     } else {
6035       if (E.e_type >= ET_LOPROC)
6036         TypeStr = "Processor Specific";
6037       else if (E.e_type >= ET_LOOS)
6038         TypeStr = "OS Specific";
6039       else
6040         TypeStr = "Unknown";
6041     }
6042     W.printString("Type", TypeStr + " (0x" + to_hexString(E.e_type) + ")");
6043 
6044     W.printEnum("Machine", E.e_machine, makeArrayRef(ElfMachineType));
6045     W.printNumber("Version", E.e_version);
6046     W.printHex("Entry", E.e_entry);
6047     W.printHex("ProgramHeaderOffset", E.e_phoff);
6048     W.printHex("SectionHeaderOffset", E.e_shoff);
6049     if (E.e_machine == EM_MIPS)
6050       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderMipsFlags),
6051                    unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
6052                    unsigned(ELF::EF_MIPS_MACH));
6053     else if (E.e_machine == EM_AMDGPU)
6054       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderAMDGPUFlags),
6055                    unsigned(ELF::EF_AMDGPU_MACH));
6056     else if (E.e_machine == EM_RISCV)
6057       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderRISCVFlags));
6058     else
6059       W.printFlags("Flags", E.e_flags);
6060     W.printNumber("HeaderSize", E.e_ehsize);
6061     W.printNumber("ProgramHeaderEntrySize", E.e_phentsize);
6062     W.printNumber("ProgramHeaderCount", E.e_phnum);
6063     W.printNumber("SectionHeaderEntrySize", E.e_shentsize);
6064     W.printString("SectionHeaderCount",
6065                   getSectionHeadersNumString(this->Obj, this->FileName));
6066     W.printString("StringTableSectionIndex",
6067                   getSectionHeaderTableIndexString(this->Obj, this->FileName));
6068   }
6069 }
6070 
6071 template <class ELFT> void LLVMELFDumper<ELFT>::printGroupSections() {
6072   DictScope Lists(W, "Groups");
6073   std::vector<GroupSection> V = this->getGroups();
6074   DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
6075   for (const GroupSection &G : V) {
6076     DictScope D(W, "Group");
6077     W.printNumber("Name", G.Name, G.ShName);
6078     W.printNumber("Index", G.Index);
6079     W.printNumber("Link", G.Link);
6080     W.printNumber("Info", G.Info);
6081     W.printHex("Type", getGroupType(G.Type), G.Type);
6082     W.startLine() << "Signature: " << G.Signature << "\n";
6083 
6084     ListScope L(W, "Section(s) in group");
6085     for (const GroupMember &GM : G.Members) {
6086       const GroupSection *MainGroup = Map[GM.Index];
6087       if (MainGroup != &G)
6088         this->reportUniqueWarning(
6089             "section with index " + Twine(GM.Index) +
6090             ", included in the group section with index " +
6091             Twine(MainGroup->Index) +
6092             ", was also found in the group section with index " +
6093             Twine(G.Index));
6094       W.startLine() << GM.Name << " (" << GM.Index << ")\n";
6095     }
6096   }
6097 
6098   if (V.empty())
6099     W.startLine() << "There are no group sections in the file.\n";
6100 }
6101 
6102 template <class ELFT> void LLVMELFDumper<ELFT>::printRelocations() {
6103   ListScope D(W, "Relocations");
6104 
6105   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6106     if (!isRelocationSec<ELFT>(Sec))
6107       continue;
6108 
6109     StringRef Name = this->getPrintableSectionName(Sec);
6110     unsigned SecNdx = &Sec - &cantFail(this->Obj.sections()).front();
6111     W.startLine() << "Section (" << SecNdx << ") " << Name << " {\n";
6112     W.indent();
6113     this->printRelocationsHelper(Sec);
6114     W.unindent();
6115     W.startLine() << "}\n";
6116   }
6117 }
6118 
6119 template <class ELFT>
6120 void LLVMELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
6121   W.startLine() << W.hex(R) << "\n";
6122 }
6123 
6124 template <class ELFT>
6125 void LLVMELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
6126                                             const RelSymbol<ELFT> &RelSym) {
6127   StringRef SymbolName = RelSym.Name;
6128   SmallString<32> RelocName;
6129   this->Obj.getRelocationTypeName(R.Type, RelocName);
6130 
6131   if (opts::ExpandRelocs) {
6132     DictScope Group(W, "Relocation");
6133     W.printHex("Offset", R.Offset);
6134     W.printNumber("Type", RelocName, R.Type);
6135     W.printNumber("Symbol", !SymbolName.empty() ? SymbolName : "-", R.Symbol);
6136     if (R.Addend)
6137       W.printHex("Addend", (uintX_t)*R.Addend);
6138   } else {
6139     raw_ostream &OS = W.startLine();
6140     OS << W.hex(R.Offset) << " " << RelocName << " "
6141        << (!SymbolName.empty() ? SymbolName : "-");
6142     if (R.Addend)
6143       OS << " " << W.hex((uintX_t)*R.Addend);
6144     OS << "\n";
6145   }
6146 }
6147 
6148 template <class ELFT> void LLVMELFDumper<ELFT>::printSectionHeaders() {
6149   ListScope SectionsD(W, "Sections");
6150 
6151   int SectionIndex = -1;
6152   std::vector<EnumEntry<unsigned>> FlagsList =
6153       getSectionFlagsForTarget(this->Obj.getHeader().e_machine);
6154   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6155     DictScope SectionD(W, "Section");
6156     W.printNumber("Index", ++SectionIndex);
6157     W.printNumber("Name", this->getPrintableSectionName(Sec), Sec.sh_name);
6158     W.printHex("Type",
6159                object::getELFSectionTypeName(this->Obj.getHeader().e_machine,
6160                                              Sec.sh_type),
6161                Sec.sh_type);
6162     W.printFlags("Flags", Sec.sh_flags, makeArrayRef(FlagsList));
6163     W.printHex("Address", Sec.sh_addr);
6164     W.printHex("Offset", Sec.sh_offset);
6165     W.printNumber("Size", Sec.sh_size);
6166     W.printNumber("Link", Sec.sh_link);
6167     W.printNumber("Info", Sec.sh_info);
6168     W.printNumber("AddressAlignment", Sec.sh_addralign);
6169     W.printNumber("EntrySize", Sec.sh_entsize);
6170 
6171     if (opts::SectionRelocations) {
6172       ListScope D(W, "Relocations");
6173       this->printRelocationsHelper(Sec);
6174     }
6175 
6176     if (opts::SectionSymbols) {
6177       ListScope D(W, "Symbols");
6178       if (this->DotSymtabSec) {
6179         StringRef StrTable = unwrapOrError(
6180             this->FileName,
6181             this->Obj.getStringTableForSymtab(*this->DotSymtabSec));
6182         ArrayRef<Elf_Word> ShndxTable = this->getShndxTable(this->DotSymtabSec);
6183 
6184         typename ELFT::SymRange Symbols = unwrapOrError(
6185             this->FileName, this->Obj.symbols(this->DotSymtabSec));
6186         for (const Elf_Sym &Sym : Symbols) {
6187           const Elf_Shdr *SymSec = unwrapOrError(
6188               this->FileName,
6189               this->Obj.getSection(Sym, this->DotSymtabSec, ShndxTable));
6190           if (SymSec == &Sec)
6191             printSymbol(Sym, &Sym - &Symbols[0], ShndxTable, StrTable, false,
6192                         false);
6193         }
6194       }
6195     }
6196 
6197     if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) {
6198       ArrayRef<uint8_t> Data =
6199           unwrapOrError(this->FileName, this->Obj.getSectionContents(Sec));
6200       W.printBinaryBlock(
6201           "SectionData",
6202           StringRef(reinterpret_cast<const char *>(Data.data()), Data.size()));
6203     }
6204   }
6205 }
6206 
6207 template <class ELFT>
6208 void LLVMELFDumper<ELFT>::printSymbolSection(
6209     const Elf_Sym &Symbol, unsigned SymIndex,
6210     DataRegion<Elf_Word> ShndxTable) const {
6211   auto GetSectionSpecialType = [&]() -> Optional<StringRef> {
6212     if (Symbol.isUndefined())
6213       return StringRef("Undefined");
6214     if (Symbol.isProcessorSpecific())
6215       return StringRef("Processor Specific");
6216     if (Symbol.isOSSpecific())
6217       return StringRef("Operating System Specific");
6218     if (Symbol.isAbsolute())
6219       return StringRef("Absolute");
6220     if (Symbol.isCommon())
6221       return StringRef("Common");
6222     if (Symbol.isReserved() && Symbol.st_shndx != SHN_XINDEX)
6223       return StringRef("Reserved");
6224     return None;
6225   };
6226 
6227   if (Optional<StringRef> Type = GetSectionSpecialType()) {
6228     W.printHex("Section", *Type, Symbol.st_shndx);
6229     return;
6230   }
6231 
6232   Expected<unsigned> SectionIndex =
6233       this->getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
6234   if (!SectionIndex) {
6235     assert(Symbol.st_shndx == SHN_XINDEX &&
6236            "getSymbolSectionIndex should only fail due to an invalid "
6237            "SHT_SYMTAB_SHNDX table/reference");
6238     this->reportUniqueWarning(SectionIndex.takeError());
6239     W.printHex("Section", "Reserved", SHN_XINDEX);
6240     return;
6241   }
6242 
6243   Expected<StringRef> SectionName =
6244       this->getSymbolSectionName(Symbol, *SectionIndex);
6245   if (!SectionName) {
6246     // Don't report an invalid section name if the section headers are missing.
6247     // In such situations, all sections will be "invalid".
6248     if (!this->ObjF.sections().empty())
6249       this->reportUniqueWarning(SectionName.takeError());
6250     else
6251       consumeError(SectionName.takeError());
6252     W.printHex("Section", "<?>", *SectionIndex);
6253   } else {
6254     W.printHex("Section", *SectionName, *SectionIndex);
6255   }
6256 }
6257 
6258 template <class ELFT>
6259 void LLVMELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
6260                                       DataRegion<Elf_Word> ShndxTable,
6261                                       Optional<StringRef> StrTable,
6262                                       bool IsDynamic,
6263                                       bool /*NonVisibilityBitsUsed*/) const {
6264   std::string FullSymbolName = this->getFullSymbolName(
6265       Symbol, SymIndex, ShndxTable, StrTable, IsDynamic);
6266   unsigned char SymbolType = Symbol.getType();
6267 
6268   DictScope D(W, "Symbol");
6269   W.printNumber("Name", FullSymbolName, Symbol.st_name);
6270   W.printHex("Value", Symbol.st_value);
6271   W.printNumber("Size", Symbol.st_size);
6272   W.printEnum("Binding", Symbol.getBinding(), makeArrayRef(ElfSymbolBindings));
6273   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
6274       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
6275     W.printEnum("Type", SymbolType, makeArrayRef(AMDGPUSymbolTypes));
6276   else
6277     W.printEnum("Type", SymbolType, makeArrayRef(ElfSymbolTypes));
6278   if (Symbol.st_other == 0)
6279     // Usually st_other flag is zero. Do not pollute the output
6280     // by flags enumeration in that case.
6281     W.printNumber("Other", 0);
6282   else {
6283     std::vector<EnumEntry<unsigned>> SymOtherFlags(std::begin(ElfSymOtherFlags),
6284                                                    std::end(ElfSymOtherFlags));
6285     if (this->Obj.getHeader().e_machine == EM_MIPS) {
6286       // Someones in their infinite wisdom decided to make STO_MIPS_MIPS16
6287       // flag overlapped with other ST_MIPS_xxx flags. So consider both
6288       // cases separately.
6289       if ((Symbol.st_other & STO_MIPS_MIPS16) == STO_MIPS_MIPS16)
6290         SymOtherFlags.insert(SymOtherFlags.end(),
6291                              std::begin(ElfMips16SymOtherFlags),
6292                              std::end(ElfMips16SymOtherFlags));
6293       else
6294         SymOtherFlags.insert(SymOtherFlags.end(),
6295                              std::begin(ElfMipsSymOtherFlags),
6296                              std::end(ElfMipsSymOtherFlags));
6297     } else if (this->Obj.getHeader().e_machine == EM_AARCH64) {
6298       SymOtherFlags.insert(SymOtherFlags.end(),
6299                            std::begin(ElfAArch64SymOtherFlags),
6300                            std::end(ElfAArch64SymOtherFlags));
6301     }
6302     W.printFlags("Other", Symbol.st_other, makeArrayRef(SymOtherFlags), 0x3u);
6303   }
6304   printSymbolSection(Symbol, SymIndex, ShndxTable);
6305 }
6306 
6307 template <class ELFT>
6308 void LLVMELFDumper<ELFT>::printSymbols(bool PrintSymbols,
6309                                        bool PrintDynamicSymbols) {
6310   if (PrintSymbols) {
6311     ListScope Group(W, "Symbols");
6312     this->printSymbolsHelper(false);
6313   }
6314   if (PrintDynamicSymbols) {
6315     ListScope Group(W, "DynamicSymbols");
6316     this->printSymbolsHelper(true);
6317   }
6318 }
6319 
6320 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicTable() {
6321   Elf_Dyn_Range Table = this->dynamic_table();
6322   if (Table.empty())
6323     return;
6324 
6325   W.startLine() << "DynamicSection [ (" << Table.size() << " entries)\n";
6326 
6327   size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table);
6328   // The "Name/Value" column should be indented from the "Type" column by N
6329   // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
6330   // space (1) = -3.
6331   W.startLine() << "  Tag" << std::string(ELFT::Is64Bits ? 16 : 8, ' ')
6332                 << "Type" << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
6333 
6334   std::string ValueFmt = "%-" + std::to_string(MaxTagSize) + "s ";
6335   for (auto Entry : Table) {
6336     uintX_t Tag = Entry.getTag();
6337     std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
6338     W.startLine() << "  " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10, true)
6339                   << " "
6340                   << format(ValueFmt.c_str(),
6341                             this->Obj.getDynamicTagAsString(Tag).c_str())
6342                   << Value << "\n";
6343   }
6344   W.startLine() << "]\n";
6345 }
6346 
6347 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicRelocations() {
6348   W.startLine() << "Dynamic Relocations {\n";
6349   W.indent();
6350   this->printDynamicRelocationsHelper();
6351   W.unindent();
6352   W.startLine() << "}\n";
6353 }
6354 
6355 template <class ELFT>
6356 void LLVMELFDumper<ELFT>::printProgramHeaders(
6357     bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
6358   if (PrintProgramHeaders)
6359     printProgramHeaders();
6360   if (PrintSectionMapping == cl::BOU_TRUE)
6361     printSectionMapping();
6362 }
6363 
6364 template <class ELFT> void LLVMELFDumper<ELFT>::printProgramHeaders() {
6365   ListScope L(W, "ProgramHeaders");
6366 
6367   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
6368   if (!PhdrsOrErr) {
6369     this->reportUniqueWarning("unable to dump program headers: " +
6370                               toString(PhdrsOrErr.takeError()));
6371     return;
6372   }
6373 
6374   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
6375     DictScope P(W, "ProgramHeader");
6376     StringRef Type =
6377         segmentTypeToString(this->Obj.getHeader().e_machine, Phdr.p_type);
6378 
6379     W.printHex("Type", Type.empty() ? "Unknown" : Type, Phdr.p_type);
6380     W.printHex("Offset", Phdr.p_offset);
6381     W.printHex("VirtualAddress", Phdr.p_vaddr);
6382     W.printHex("PhysicalAddress", Phdr.p_paddr);
6383     W.printNumber("FileSize", Phdr.p_filesz);
6384     W.printNumber("MemSize", Phdr.p_memsz);
6385     W.printFlags("Flags", Phdr.p_flags, makeArrayRef(ElfSegmentFlags));
6386     W.printNumber("Alignment", Phdr.p_align);
6387   }
6388 }
6389 
6390 template <class ELFT>
6391 void LLVMELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
6392   ListScope SS(W, "VersionSymbols");
6393   if (!Sec)
6394     return;
6395 
6396   StringRef StrTable;
6397   ArrayRef<Elf_Sym> Syms;
6398   const Elf_Shdr *SymTabSec;
6399   Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
6400       this->getVersionTable(*Sec, &Syms, &StrTable, &SymTabSec);
6401   if (!VerTableOrErr) {
6402     this->reportUniqueWarning(VerTableOrErr.takeError());
6403     return;
6404   }
6405 
6406   if (StrTable.empty() || Syms.empty() || Syms.size() != VerTableOrErr->size())
6407     return;
6408 
6409   ArrayRef<Elf_Word> ShNdxTable = this->getShndxTable(SymTabSec);
6410   for (size_t I = 0, E = Syms.size(); I < E; ++I) {
6411     DictScope S(W, "Symbol");
6412     W.printNumber("Version", (*VerTableOrErr)[I].vs_index & VERSYM_VERSION);
6413     W.printString("Name",
6414                   this->getFullSymbolName(Syms[I], I, ShNdxTable, StrTable,
6415                                           /*IsDynamic=*/true));
6416   }
6417 }
6418 
6419 static const EnumEntry<unsigned> SymVersionFlags[] = {
6420     {"Base", "BASE", VER_FLG_BASE},
6421     {"Weak", "WEAK", VER_FLG_WEAK},
6422     {"Info", "INFO", VER_FLG_INFO}};
6423 
6424 template <class ELFT>
6425 void LLVMELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
6426   ListScope SD(W, "VersionDefinitions");
6427   if (!Sec)
6428     return;
6429 
6430   Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
6431   if (!V) {
6432     this->reportUniqueWarning(V.takeError());
6433     return;
6434   }
6435 
6436   for (const VerDef &D : *V) {
6437     DictScope Def(W, "Definition");
6438     W.printNumber("Version", D.Version);
6439     W.printFlags("Flags", D.Flags, makeArrayRef(SymVersionFlags));
6440     W.printNumber("Index", D.Ndx);
6441     W.printNumber("Hash", D.Hash);
6442     W.printString("Name", D.Name.c_str());
6443     W.printList(
6444         "Predecessors", D.AuxV,
6445         [](raw_ostream &OS, const VerdAux &Aux) { OS << Aux.Name.c_str(); });
6446   }
6447 }
6448 
6449 template <class ELFT>
6450 void LLVMELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
6451   ListScope SD(W, "VersionRequirements");
6452   if (!Sec)
6453     return;
6454 
6455   Expected<std::vector<VerNeed>> V =
6456       this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
6457   if (!V) {
6458     this->reportUniqueWarning(V.takeError());
6459     return;
6460   }
6461 
6462   for (const VerNeed &VN : *V) {
6463     DictScope Entry(W, "Dependency");
6464     W.printNumber("Version", VN.Version);
6465     W.printNumber("Count", VN.Cnt);
6466     W.printString("FileName", VN.File.c_str());
6467 
6468     ListScope L(W, "Entries");
6469     for (const VernAux &Aux : VN.AuxV) {
6470       DictScope Entry(W, "Entry");
6471       W.printNumber("Hash", Aux.Hash);
6472       W.printFlags("Flags", Aux.Flags, makeArrayRef(SymVersionFlags));
6473       W.printNumber("Index", Aux.Other);
6474       W.printString("Name", Aux.Name.c_str());
6475     }
6476   }
6477 }
6478 
6479 template <class ELFT> void LLVMELFDumper<ELFT>::printHashHistograms() {
6480   W.startLine() << "Hash Histogram not implemented!\n";
6481 }
6482 
6483 template <class ELFT> void LLVMELFDumper<ELFT>::printCGProfile() {
6484   ListScope L(W, "CGProfile");
6485   if (!this->DotCGProfileSec)
6486     return;
6487 
6488   Expected<ArrayRef<Elf_CGProfile>> CGProfileOrErr =
6489       this->Obj.template getSectionContentsAsArray<Elf_CGProfile>(
6490           *this->DotCGProfileSec);
6491   if (!CGProfileOrErr) {
6492     this->reportUniqueWarning(
6493         "unable to dump the SHT_LLVM_CALL_GRAPH_PROFILE section: " +
6494         toString(CGProfileOrErr.takeError()));
6495     return;
6496   }
6497 
6498   for (const Elf_CGProfile &CGPE : *CGProfileOrErr) {
6499     DictScope D(W, "CGProfileEntry");
6500     W.printNumber("From", this->getStaticSymbolName(CGPE.cgp_from),
6501                   CGPE.cgp_from);
6502     W.printNumber("To", this->getStaticSymbolName(CGPE.cgp_to),
6503                   CGPE.cgp_to);
6504     W.printNumber("Weight", CGPE.cgp_weight);
6505   }
6506 }
6507 
6508 template <class ELFT> void LLVMELFDumper<ELFT>::printBBAddrMaps() {
6509   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6510     if (Sec.sh_type != SHT_LLVM_BB_ADDR_MAP)
6511       continue;
6512     ListScope L(W, "BBAddrMap");
6513     Expected<std::vector<Elf_BBAddrMap>> BBAddrMapOrErr =
6514         this->Obj.decodeBBAddrMap(Sec);
6515     if (!BBAddrMapOrErr) {
6516       this->reportUniqueWarning("unable to dump " + this->describe(Sec) + ": " +
6517                                 toString(BBAddrMapOrErr.takeError()));
6518       continue;
6519     }
6520     for (const Elf_BBAddrMap &AM : *BBAddrMapOrErr) {
6521       DictScope D(W, "Function");
6522       W.printHex("At", AM.Addr);
6523       ListScope L(W, "BB entries");
6524       for (const typename Elf_BBAddrMap::BBEntry &BBE : AM.BBEntries) {
6525         DictScope L(W);
6526         W.printHex("Offset", BBE.Offset);
6527         W.printHex("Size", BBE.Size);
6528         W.printBoolean("HasReturn", BBE.HasReturn);
6529         W.printBoolean("HasTailCall", BBE.HasTailCall);
6530         W.printBoolean("IsEHPad", BBE.IsEHPad);
6531         W.printBoolean("CanFallThrough", BBE.CanFallThrough);
6532       }
6533     }
6534   }
6535 }
6536 
6537 template <class ELFT> void LLVMELFDumper<ELFT>::printAddrsig() {
6538   ListScope L(W, "Addrsig");
6539   if (!this->DotAddrsigSec)
6540     return;
6541 
6542   Expected<std::vector<uint64_t>> SymsOrErr =
6543       decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
6544   if (!SymsOrErr) {
6545     this->reportUniqueWarning(SymsOrErr.takeError());
6546     return;
6547   }
6548 
6549   for (uint64_t Sym : *SymsOrErr)
6550     W.printNumber("Sym", this->getStaticSymbolName(Sym), Sym);
6551 }
6552 
6553 template <typename ELFT>
6554 static bool printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
6555                                   ScopedPrinter &W) {
6556   // Return true if we were able to pretty-print the note, false otherwise.
6557   switch (NoteType) {
6558   default:
6559     return false;
6560   case ELF::NT_GNU_ABI_TAG: {
6561     const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
6562     if (!AbiTag.IsValid) {
6563       W.printString("ABI", "<corrupt GNU_ABI_TAG>");
6564       return false;
6565     } else {
6566       W.printString("OS", AbiTag.OSName);
6567       W.printString("ABI", AbiTag.ABI);
6568     }
6569     break;
6570   }
6571   case ELF::NT_GNU_BUILD_ID: {
6572     W.printString("Build ID", getGNUBuildId(Desc));
6573     break;
6574   }
6575   case ELF::NT_GNU_GOLD_VERSION:
6576     W.printString("Version", getGNUGoldVersion(Desc));
6577     break;
6578   case ELF::NT_GNU_PROPERTY_TYPE_0:
6579     ListScope D(W, "Property");
6580     for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
6581       W.printString(Property);
6582     break;
6583   }
6584   return true;
6585 }
6586 
6587 static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) {
6588   W.printNumber("Page Size", Note.PageSize);
6589   for (const CoreFileMapping &Mapping : Note.Mappings) {
6590     ListScope D(W, "Mapping");
6591     W.printHex("Start", Mapping.Start);
6592     W.printHex("End", Mapping.End);
6593     W.printHex("Offset", Mapping.Offset);
6594     W.printString("Filename", Mapping.Filename);
6595   }
6596 }
6597 
6598 template <class ELFT> void LLVMELFDumper<ELFT>::printNotes() {
6599   ListScope L(W, "Notes");
6600 
6601   std::unique_ptr<DictScope> NoteScope;
6602   auto StartNotes = [&](Optional<StringRef> SecName,
6603                         const typename ELFT::Off Offset,
6604                         const typename ELFT::Addr Size) {
6605     NoteScope = std::make_unique<DictScope>(W, "NoteSection");
6606     W.printString("Name", SecName ? *SecName : "<?>");
6607     W.printHex("Offset", Offset);
6608     W.printHex("Size", Size);
6609   };
6610 
6611   auto EndNotes = [&] { NoteScope.reset(); };
6612 
6613   auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
6614     DictScope D2(W, "Note");
6615     StringRef Name = Note.getName();
6616     ArrayRef<uint8_t> Descriptor = Note.getDesc();
6617     Elf_Word Type = Note.getType();
6618 
6619     // Print the note owner/type.
6620     W.printString("Owner", Name);
6621     W.printHex("Data size", Descriptor.size());
6622 
6623     StringRef NoteType =
6624         getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
6625     if (!NoteType.empty())
6626       W.printString("Type", NoteType);
6627     else
6628       W.printString("Type",
6629                     "Unknown (" + to_string(format_hex(Type, 10)) + ")");
6630 
6631     // Print the description, or fallback to printing raw bytes for unknown
6632     // owners/if we fail to pretty-print the contents.
6633     if (Name == "GNU") {
6634       if (printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W))
6635         return Error::success();
6636     } else if (Name == "FreeBSD") {
6637       if (Optional<FreeBSDNote> N =
6638               getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
6639         W.printString(N->Type, N->Value);
6640         return Error::success();
6641       }
6642     } else if (Name == "AMD") {
6643       const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
6644       if (!N.Type.empty()) {
6645         W.printString(N.Type, N.Value);
6646         return Error::success();
6647       }
6648     } else if (Name == "AMDGPU") {
6649       const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
6650       if (!N.Type.empty()) {
6651         W.printString(N.Type, N.Value);
6652         return Error::success();
6653       }
6654     } else if (Name == "CORE") {
6655       if (Type == ELF::NT_FILE) {
6656         DataExtractor DescExtractor(Descriptor,
6657                                     ELFT::TargetEndianness == support::little,
6658                                     sizeof(Elf_Addr));
6659         if (Expected<CoreNote> N = readCoreNote(DescExtractor)) {
6660           printCoreNoteLLVMStyle(*N, W);
6661           return Error::success();
6662         } else {
6663           return N.takeError();
6664         }
6665       }
6666     }
6667     if (!Descriptor.empty()) {
6668       W.printBinaryBlock("Description data", Descriptor);
6669     }
6670     return Error::success();
6671   };
6672 
6673   printNotesHelper(*this, StartNotes, ProcessNote, EndNotes);
6674 }
6675 
6676 template <class ELFT> void LLVMELFDumper<ELFT>::printELFLinkerOptions() {
6677   ListScope L(W, "LinkerOptions");
6678 
6679   unsigned I = -1;
6680   for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) {
6681     ++I;
6682     if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS)
6683       continue;
6684 
6685     Expected<ArrayRef<uint8_t>> ContentsOrErr =
6686         this->Obj.getSectionContents(Shdr);
6687     if (!ContentsOrErr) {
6688       this->reportUniqueWarning("unable to read the content of the "
6689                                 "SHT_LLVM_LINKER_OPTIONS section: " +
6690                                 toString(ContentsOrErr.takeError()));
6691       continue;
6692     }
6693     if (ContentsOrErr->empty())
6694       continue;
6695 
6696     if (ContentsOrErr->back() != 0) {
6697       this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " +
6698                                 Twine(I) +
6699                                 " is broken: the "
6700                                 "content is not null-terminated");
6701       continue;
6702     }
6703 
6704     SmallVector<StringRef, 16> Strings;
6705     toStringRef(ContentsOrErr->drop_back()).split(Strings, '\0');
6706     if (Strings.size() % 2 != 0) {
6707       this->reportUniqueWarning(
6708           "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) +
6709           " is broken: an incomplete "
6710           "key-value pair was found. The last possible key was: \"" +
6711           Strings.back() + "\"");
6712       continue;
6713     }
6714 
6715     for (size_t I = 0; I < Strings.size(); I += 2)
6716       W.printString(Strings[I], Strings[I + 1]);
6717   }
6718 }
6719 
6720 template <class ELFT> void LLVMELFDumper<ELFT>::printDependentLibs() {
6721   ListScope L(W, "DependentLibs");
6722   this->printDependentLibsHelper(
6723       [](const Elf_Shdr &) {},
6724       [this](StringRef Lib, uint64_t) { W.printString(Lib); });
6725 }
6726 
6727 template <class ELFT> void LLVMELFDumper<ELFT>::printStackSizes() {
6728   ListScope L(W, "StackSizes");
6729   if (this->Obj.getHeader().e_type == ELF::ET_REL)
6730     this->printRelocatableStackSizes([]() {});
6731   else
6732     this->printNonRelocatableStackSizes([]() {});
6733 }
6734 
6735 template <class ELFT>
6736 void LLVMELFDumper<ELFT>::printStackSizeEntry(uint64_t Size, StringRef FuncName) {
6737   DictScope D(W, "Entry");
6738   W.printString("Function", FuncName);
6739   W.printHex("Size", Size);
6740 }
6741 
6742 template <class ELFT>
6743 void LLVMELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
6744   auto PrintEntry = [&](const Elf_Addr *E) {
6745     W.printHex("Address", Parser.getGotAddress(E));
6746     W.printNumber("Access", Parser.getGotOffset(E));
6747     W.printHex("Initial", *E);
6748   };
6749 
6750   DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT");
6751 
6752   W.printHex("Canonical gp value", Parser.getGp());
6753   {
6754     ListScope RS(W, "Reserved entries");
6755     {
6756       DictScope D(W, "Entry");
6757       PrintEntry(Parser.getGotLazyResolver());
6758       W.printString("Purpose", StringRef("Lazy resolver"));
6759     }
6760 
6761     if (Parser.getGotModulePointer()) {
6762       DictScope D(W, "Entry");
6763       PrintEntry(Parser.getGotModulePointer());
6764       W.printString("Purpose", StringRef("Module pointer (GNU extension)"));
6765     }
6766   }
6767   {
6768     ListScope LS(W, "Local entries");
6769     for (auto &E : Parser.getLocalEntries()) {
6770       DictScope D(W, "Entry");
6771       PrintEntry(&E);
6772     }
6773   }
6774 
6775   if (Parser.IsStatic)
6776     return;
6777 
6778   {
6779     ListScope GS(W, "Global entries");
6780     for (auto &E : Parser.getGlobalEntries()) {
6781       DictScope D(W, "Entry");
6782 
6783       PrintEntry(&E);
6784 
6785       const Elf_Sym &Sym = *Parser.getGotSym(&E);
6786       W.printHex("Value", Sym.st_value);
6787       W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes));
6788 
6789       const unsigned SymIndex = &Sym - this->dynamic_symbols().begin();
6790       DataRegion<Elf_Word> ShndxTable(
6791           (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6792       printSymbolSection(Sym, SymIndex, ShndxTable);
6793 
6794       std::string SymName = this->getFullSymbolName(
6795           Sym, SymIndex, ShndxTable, this->DynamicStringTable, true);
6796       W.printNumber("Name", SymName, Sym.st_name);
6797     }
6798   }
6799 
6800   W.printNumber("Number of TLS and multi-GOT entries",
6801                 uint64_t(Parser.getOtherEntries().size()));
6802 }
6803 
6804 template <class ELFT>
6805 void LLVMELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
6806   auto PrintEntry = [&](const Elf_Addr *E) {
6807     W.printHex("Address", Parser.getPltAddress(E));
6808     W.printHex("Initial", *E);
6809   };
6810 
6811   DictScope GS(W, "PLT GOT");
6812 
6813   {
6814     ListScope RS(W, "Reserved entries");
6815     {
6816       DictScope D(W, "Entry");
6817       PrintEntry(Parser.getPltLazyResolver());
6818       W.printString("Purpose", StringRef("PLT lazy resolver"));
6819     }
6820 
6821     if (auto E = Parser.getPltModulePointer()) {
6822       DictScope D(W, "Entry");
6823       PrintEntry(E);
6824       W.printString("Purpose", StringRef("Module pointer"));
6825     }
6826   }
6827   {
6828     ListScope LS(W, "Entries");
6829     DataRegion<Elf_Word> ShndxTable(
6830         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6831     for (auto &E : Parser.getPltEntries()) {
6832       DictScope D(W, "Entry");
6833       PrintEntry(&E);
6834 
6835       const Elf_Sym &Sym = *Parser.getPltSym(&E);
6836       W.printHex("Value", Sym.st_value);
6837       W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes));
6838       printSymbolSection(Sym, &Sym - this->dynamic_symbols().begin(),
6839                          ShndxTable);
6840 
6841       const Elf_Sym *FirstSym = cantFail(
6842           this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
6843       std::string SymName = this->getFullSymbolName(
6844           Sym, &Sym - FirstSym, ShndxTable, Parser.getPltStrTable(), true);
6845       W.printNumber("Name", SymName, Sym.st_name);
6846     }
6847   }
6848 }
6849 
6850 template <class ELFT> void LLVMELFDumper<ELFT>::printMipsABIFlags() {
6851   const Elf_Mips_ABIFlags<ELFT> *Flags;
6852   if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
6853           getMipsAbiFlagsSection(*this)) {
6854     Flags = *SecOrErr;
6855     if (!Flags) {
6856       W.startLine() << "There is no .MIPS.abiflags section in the file.\n";
6857       return;
6858     }
6859   } else {
6860     this->reportUniqueWarning(SecOrErr.takeError());
6861     return;
6862   }
6863 
6864   raw_ostream &OS = W.getOStream();
6865   DictScope GS(W, "MIPS ABI Flags");
6866 
6867   W.printNumber("Version", Flags->version);
6868   W.startLine() << "ISA: ";
6869   if (Flags->isa_rev <= 1)
6870     OS << format("MIPS%u", Flags->isa_level);
6871   else
6872     OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev);
6873   OS << "\n";
6874   W.printEnum("ISA Extension", Flags->isa_ext, makeArrayRef(ElfMipsISAExtType));
6875   W.printFlags("ASEs", Flags->ases, makeArrayRef(ElfMipsASEFlags));
6876   W.printEnum("FP ABI", Flags->fp_abi, makeArrayRef(ElfMipsFpABIType));
6877   W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size));
6878   W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size));
6879   W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size));
6880   W.printFlags("Flags 1", Flags->flags1, makeArrayRef(ElfMipsFlags1));
6881   W.printHex("Flags 2", Flags->flags2);
6882 }
6883