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