xref: /freebsd-src/contrib/llvm-project/llvm/tools/llvm-readobj/ELFDumper.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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 const EnumEntry<unsigned> ElfClass[] = {
970   {"None",   "none",   ELF::ELFCLASSNONE},
971   {"32-bit", "ELF32",  ELF::ELFCLASS32},
972   {"64-bit", "ELF64",  ELF::ELFCLASS64},
973 };
974 
975 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 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 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 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 const EnumEntry<unsigned> ARMElfOSABI[] = {
1017   {"ARM", "ARM", ELF::ELFOSABI_ARM}
1018 };
1019 
1020 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 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 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 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 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 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 const EnumEntry<unsigned> ElfXCoreSectionFlags[] = {
1231   ENUM_ENT(XCORE_SHF_CP_SECTION, ""),
1232   ENUM_ENT(XCORE_SHF_DP_SECTION, "")
1233 };
1234 
1235 const EnumEntry<unsigned> ElfARMSectionFlags[] = {
1236   ENUM_ENT(SHF_ARM_PURECODE, "y")
1237 };
1238 
1239 const EnumEntry<unsigned> ElfHexagonSectionFlags[] = {
1240   ENUM_ENT(SHF_HEX_GPREL, "")
1241 };
1242 
1243 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 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 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 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 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 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 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 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 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 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 const EnumEntry<unsigned> ElfAArch64SymOtherFlags[] = {
1610   LLVM_READOBJ_ENUM_ENT(ELF, STO_AARCH64_VARIANT_PCS)
1611 };
1612 
1613 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 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 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 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 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_RELRSZ:
2302   case DT_RELRENT:
2303   case DT_ANDROID_RELSZ:
2304   case DT_ANDROID_RELASZ:
2305     return std::to_string(Value) + " (bytes)";
2306   case DT_NEEDED:
2307   case DT_SONAME:
2308   case DT_AUXILIARY:
2309   case DT_USED:
2310   case DT_FILTER:
2311   case DT_RPATH:
2312   case DT_RUNPATH: {
2313     const std::map<uint64_t, const char *> TagNames = {
2314         {DT_NEEDED, "Shared library"},       {DT_SONAME, "Library soname"},
2315         {DT_AUXILIARY, "Auxiliary library"}, {DT_USED, "Not needed object"},
2316         {DT_FILTER, "Filter library"},       {DT_RPATH, "Library rpath"},
2317         {DT_RUNPATH, "Library runpath"},
2318     };
2319 
2320     return (Twine(TagNames.at(Type)) + ": [" + getDynamicString(Value) + "]")
2321         .str();
2322   }
2323   case DT_FLAGS:
2324     return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags));
2325   case DT_FLAGS_1:
2326     return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags1));
2327   default:
2328     return FormatHexValue(Value);
2329   }
2330 }
2331 
2332 template <class ELFT>
2333 StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const {
2334   if (DynamicStringTable.empty() && !DynamicStringTable.data()) {
2335     reportUniqueWarning("string table was not found");
2336     return "<?>";
2337   }
2338 
2339   auto WarnAndReturn = [this](const Twine &Msg, uint64_t Offset) {
2340     reportUniqueWarning("string table at offset 0x" + Twine::utohexstr(Offset) +
2341                         Msg);
2342     return "<?>";
2343   };
2344 
2345   const uint64_t FileSize = Obj.getBufSize();
2346   const uint64_t Offset =
2347       (const uint8_t *)DynamicStringTable.data() - Obj.base();
2348   if (DynamicStringTable.size() > FileSize - Offset)
2349     return WarnAndReturn(" with size 0x" +
2350                              Twine::utohexstr(DynamicStringTable.size()) +
2351                              " goes past the end of the file (0x" +
2352                              Twine::utohexstr(FileSize) + ")",
2353                          Offset);
2354 
2355   if (Value >= DynamicStringTable.size())
2356     return WarnAndReturn(
2357         ": unable to read the string at 0x" + Twine::utohexstr(Offset + Value) +
2358             ": it goes past the end of the table (0x" +
2359             Twine::utohexstr(Offset + DynamicStringTable.size()) + ")",
2360         Offset);
2361 
2362   if (DynamicStringTable.back() != '\0')
2363     return WarnAndReturn(": unable to read the string at 0x" +
2364                              Twine::utohexstr(Offset + Value) +
2365                              ": the string table is not null-terminated",
2366                          Offset);
2367 
2368   return DynamicStringTable.data() + Value;
2369 }
2370 
2371 template <class ELFT> void ELFDumper<ELFT>::printUnwindInfo() {
2372   DwarfCFIEH::PrinterContext<ELFT> Ctx(W, ObjF);
2373   Ctx.printUnwindInformation();
2374 }
2375 
2376 // The namespace is needed to fix the compilation with GCC older than 7.0+.
2377 namespace {
2378 template <> void ELFDumper<ELF32LE>::printUnwindInfo() {
2379   if (Obj.getHeader().e_machine == EM_ARM) {
2380     ARM::EHABI::PrinterContext<ELF32LE> Ctx(W, Obj, ObjF.getFileName(),
2381                                             DotSymtabSec);
2382     Ctx.PrintUnwindInformation();
2383   }
2384   DwarfCFIEH::PrinterContext<ELF32LE> Ctx(W, ObjF);
2385   Ctx.printUnwindInformation();
2386 }
2387 } // namespace
2388 
2389 template <class ELFT> void ELFDumper<ELFT>::printNeededLibraries() {
2390   ListScope D(W, "NeededLibraries");
2391 
2392   std::vector<StringRef> Libs;
2393   for (const auto &Entry : dynamic_table())
2394     if (Entry.d_tag == ELF::DT_NEEDED)
2395       Libs.push_back(getDynamicString(Entry.d_un.d_val));
2396 
2397   llvm::sort(Libs);
2398 
2399   for (StringRef L : Libs)
2400     W.startLine() << L << "\n";
2401 }
2402 
2403 template <class ELFT>
2404 static Error checkHashTable(const ELFDumper<ELFT> &Dumper,
2405                             const typename ELFT::Hash *H,
2406                             bool *IsHeaderValid = nullptr) {
2407   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
2408   const uint64_t SecOffset = (const uint8_t *)H - Obj.base();
2409   if (Dumper.getHashTableEntSize() == 8) {
2410     auto It = llvm::find_if(ElfMachineType, [&](const EnumEntry<unsigned> &E) {
2411       return E.Value == Obj.getHeader().e_machine;
2412     });
2413     if (IsHeaderValid)
2414       *IsHeaderValid = false;
2415     return createError("the hash table at 0x" + Twine::utohexstr(SecOffset) +
2416                        " is not supported: it contains non-standard 8 "
2417                        "byte entries on " +
2418                        It->AltName + " platform");
2419   }
2420 
2421   auto MakeError = [&](const Twine &Msg = "") {
2422     return createError("the hash table at offset 0x" +
2423                        Twine::utohexstr(SecOffset) +
2424                        " goes past the end of the file (0x" +
2425                        Twine::utohexstr(Obj.getBufSize()) + ")" + Msg);
2426   };
2427 
2428   // Each SHT_HASH section starts from two 32-bit fields: nbucket and nchain.
2429   const unsigned HeaderSize = 2 * sizeof(typename ELFT::Word);
2430 
2431   if (IsHeaderValid)
2432     *IsHeaderValid = Obj.getBufSize() - SecOffset >= HeaderSize;
2433 
2434   if (Obj.getBufSize() - SecOffset < HeaderSize)
2435     return MakeError();
2436 
2437   if (Obj.getBufSize() - SecOffset - HeaderSize <
2438       ((uint64_t)H->nbucket + H->nchain) * sizeof(typename ELFT::Word))
2439     return MakeError(", nbucket = " + Twine(H->nbucket) +
2440                      ", nchain = " + Twine(H->nchain));
2441   return Error::success();
2442 }
2443 
2444 template <class ELFT>
2445 static Error checkGNUHashTable(const ELFFile<ELFT> &Obj,
2446                                const typename ELFT::GnuHash *GnuHashTable,
2447                                bool *IsHeaderValid = nullptr) {
2448   const uint8_t *TableData = reinterpret_cast<const uint8_t *>(GnuHashTable);
2449   assert(TableData >= Obj.base() && TableData < Obj.base() + Obj.getBufSize() &&
2450          "GnuHashTable must always point to a location inside the file");
2451 
2452   uint64_t TableOffset = TableData - Obj.base();
2453   if (IsHeaderValid)
2454     *IsHeaderValid = TableOffset + /*Header size:*/ 16 < Obj.getBufSize();
2455   if (TableOffset + 16 + (uint64_t)GnuHashTable->nbuckets * 4 +
2456           (uint64_t)GnuHashTable->maskwords * sizeof(typename ELFT::Off) >=
2457       Obj.getBufSize())
2458     return createError("unable to dump the SHT_GNU_HASH "
2459                        "section at 0x" +
2460                        Twine::utohexstr(TableOffset) +
2461                        ": it goes past the end of the file");
2462   return Error::success();
2463 }
2464 
2465 template <typename ELFT> void ELFDumper<ELFT>::printHashTable() {
2466   DictScope D(W, "HashTable");
2467   if (!HashTable)
2468     return;
2469 
2470   bool IsHeaderValid;
2471   Error Err = checkHashTable(*this, HashTable, &IsHeaderValid);
2472   if (IsHeaderValid) {
2473     W.printNumber("Num Buckets", HashTable->nbucket);
2474     W.printNumber("Num Chains", HashTable->nchain);
2475   }
2476 
2477   if (Err) {
2478     reportUniqueWarning(std::move(Err));
2479     return;
2480   }
2481 
2482   W.printList("Buckets", HashTable->buckets());
2483   W.printList("Chains", HashTable->chains());
2484 }
2485 
2486 template <class ELFT>
2487 static Expected<ArrayRef<typename ELFT::Word>>
2488 getGnuHashTableChains(Optional<DynRegionInfo> DynSymRegion,
2489                       const typename ELFT::GnuHash *GnuHashTable) {
2490   if (!DynSymRegion)
2491     return createError("no dynamic symbol table found");
2492 
2493   ArrayRef<typename ELFT::Sym> DynSymTable =
2494       DynSymRegion->template getAsArrayRef<typename ELFT::Sym>();
2495   size_t NumSyms = DynSymTable.size();
2496   if (!NumSyms)
2497     return createError("the dynamic symbol table is empty");
2498 
2499   if (GnuHashTable->symndx < NumSyms)
2500     return GnuHashTable->values(NumSyms);
2501 
2502   // A normal empty GNU hash table section produced by linker might have
2503   // symndx set to the number of dynamic symbols + 1 (for the zero symbol)
2504   // and have dummy null values in the Bloom filter and in the buckets
2505   // vector (or no values at all). It happens because the value of symndx is not
2506   // important for dynamic loaders when the GNU hash table is empty. They just
2507   // skip the whole object during symbol lookup. In such cases, the symndx value
2508   // is irrelevant and we should not report a warning.
2509   ArrayRef<typename ELFT::Word> Buckets = GnuHashTable->buckets();
2510   if (!llvm::all_of(Buckets, [](typename ELFT::Word V) { return V == 0; }))
2511     return createError(
2512         "the first hashed symbol index (" + Twine(GnuHashTable->symndx) +
2513         ") is greater than or equal to the number of dynamic symbols (" +
2514         Twine(NumSyms) + ")");
2515   // There is no way to represent an array of (dynamic symbols count - symndx)
2516   // length.
2517   return ArrayRef<typename ELFT::Word>();
2518 }
2519 
2520 template <typename ELFT>
2521 void ELFDumper<ELFT>::printGnuHashTable() {
2522   DictScope D(W, "GnuHashTable");
2523   if (!GnuHashTable)
2524     return;
2525 
2526   bool IsHeaderValid;
2527   Error Err = checkGNUHashTable<ELFT>(Obj, GnuHashTable, &IsHeaderValid);
2528   if (IsHeaderValid) {
2529     W.printNumber("Num Buckets", GnuHashTable->nbuckets);
2530     W.printNumber("First Hashed Symbol Index", GnuHashTable->symndx);
2531     W.printNumber("Num Mask Words", GnuHashTable->maskwords);
2532     W.printNumber("Shift Count", GnuHashTable->shift2);
2533   }
2534 
2535   if (Err) {
2536     reportUniqueWarning(std::move(Err));
2537     return;
2538   }
2539 
2540   ArrayRef<typename ELFT::Off> BloomFilter = GnuHashTable->filter();
2541   W.printHexList("Bloom Filter", BloomFilter);
2542 
2543   ArrayRef<Elf_Word> Buckets = GnuHashTable->buckets();
2544   W.printList("Buckets", Buckets);
2545 
2546   Expected<ArrayRef<Elf_Word>> Chains =
2547       getGnuHashTableChains<ELFT>(DynSymRegion, GnuHashTable);
2548   if (!Chains) {
2549     reportUniqueWarning("unable to dump 'Values' for the SHT_GNU_HASH "
2550                         "section: " +
2551                         toString(Chains.takeError()));
2552     return;
2553   }
2554 
2555   W.printHexList("Values", *Chains);
2556 }
2557 
2558 template <typename ELFT> void ELFDumper<ELFT>::printLoadName() {
2559   StringRef SOName = "<Not found>";
2560   if (SONameOffset)
2561     SOName = getDynamicString(*SONameOffset);
2562   W.printString("LoadName", SOName);
2563 }
2564 
2565 template <class ELFT> void ELFDumper<ELFT>::printArchSpecificInfo() {
2566   switch (Obj.getHeader().e_machine) {
2567   case EM_ARM:
2568     if (Obj.isLE())
2569       printAttributes(ELF::SHT_ARM_ATTRIBUTES,
2570                       std::make_unique<ARMAttributeParser>(&W),
2571                       support::little);
2572     else
2573       reportUniqueWarning("attribute printing not implemented for big-endian "
2574                           "ARM objects");
2575     break;
2576   case EM_RISCV:
2577     if (Obj.isLE())
2578       printAttributes(ELF::SHT_RISCV_ATTRIBUTES,
2579                       std::make_unique<RISCVAttributeParser>(&W),
2580                       support::little);
2581     else
2582       reportUniqueWarning("attribute printing not implemented for big-endian "
2583                           "RISC-V objects");
2584     break;
2585   case EM_MSP430:
2586     printAttributes(ELF::SHT_MSP430_ATTRIBUTES,
2587                     std::make_unique<MSP430AttributeParser>(&W),
2588                     support::little);
2589     break;
2590   case EM_MIPS: {
2591     printMipsABIFlags();
2592     printMipsOptions();
2593     printMipsReginfo();
2594     MipsGOTParser<ELFT> Parser(*this);
2595     if (Error E = Parser.findGOT(dynamic_table(), dynamic_symbols()))
2596       reportUniqueWarning(std::move(E));
2597     else if (!Parser.isGotEmpty())
2598       printMipsGOT(Parser);
2599 
2600     if (Error E = Parser.findPLT(dynamic_table()))
2601       reportUniqueWarning(std::move(E));
2602     else if (!Parser.isPltEmpty())
2603       printMipsPLT(Parser);
2604     break;
2605   }
2606   default:
2607     break;
2608   }
2609 }
2610 
2611 template <class ELFT>
2612 void ELFDumper<ELFT>::printAttributes(
2613     unsigned AttrShType, std::unique_ptr<ELFAttributeParser> AttrParser,
2614     support::endianness Endianness) {
2615   assert((AttrShType != ELF::SHT_NULL) && AttrParser &&
2616          "Incomplete ELF attribute implementation");
2617   DictScope BA(W, "BuildAttributes");
2618   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
2619     if (Sec.sh_type != AttrShType)
2620       continue;
2621 
2622     ArrayRef<uint8_t> Contents;
2623     if (Expected<ArrayRef<uint8_t>> ContentOrErr =
2624             Obj.getSectionContents(Sec)) {
2625       Contents = *ContentOrErr;
2626       if (Contents.empty()) {
2627         reportUniqueWarning("the " + describe(Sec) + " is empty");
2628         continue;
2629       }
2630     } else {
2631       reportUniqueWarning("unable to read the content of the " + describe(Sec) +
2632                           ": " + toString(ContentOrErr.takeError()));
2633       continue;
2634     }
2635 
2636     W.printHex("FormatVersion", Contents[0]);
2637 
2638     if (Error E = AttrParser->parse(Contents, Endianness))
2639       reportUniqueWarning("unable to dump attributes from the " +
2640                           describe(Sec) + ": " + toString(std::move(E)));
2641   }
2642 }
2643 
2644 namespace {
2645 
2646 template <class ELFT> class MipsGOTParser {
2647 public:
2648   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
2649   using Entry = typename ELFT::Addr;
2650   using Entries = ArrayRef<Entry>;
2651 
2652   const bool IsStatic;
2653   const ELFFile<ELFT> &Obj;
2654   const ELFDumper<ELFT> &Dumper;
2655 
2656   MipsGOTParser(const ELFDumper<ELFT> &D);
2657   Error findGOT(Elf_Dyn_Range DynTable, Elf_Sym_Range DynSyms);
2658   Error findPLT(Elf_Dyn_Range DynTable);
2659 
2660   bool isGotEmpty() const { return GotEntries.empty(); }
2661   bool isPltEmpty() const { return PltEntries.empty(); }
2662 
2663   uint64_t getGp() const;
2664 
2665   const Entry *getGotLazyResolver() const;
2666   const Entry *getGotModulePointer() const;
2667   const Entry *getPltLazyResolver() const;
2668   const Entry *getPltModulePointer() const;
2669 
2670   Entries getLocalEntries() const;
2671   Entries getGlobalEntries() const;
2672   Entries getOtherEntries() const;
2673   Entries getPltEntries() const;
2674 
2675   uint64_t getGotAddress(const Entry * E) const;
2676   int64_t getGotOffset(const Entry * E) const;
2677   const Elf_Sym *getGotSym(const Entry *E) const;
2678 
2679   uint64_t getPltAddress(const Entry * E) const;
2680   const Elf_Sym *getPltSym(const Entry *E) const;
2681 
2682   StringRef getPltStrTable() const { return PltStrTable; }
2683   const Elf_Shdr *getPltSymTable() const { return PltSymTable; }
2684 
2685 private:
2686   const Elf_Shdr *GotSec;
2687   size_t LocalNum;
2688   size_t GlobalNum;
2689 
2690   const Elf_Shdr *PltSec;
2691   const Elf_Shdr *PltRelSec;
2692   const Elf_Shdr *PltSymTable;
2693   StringRef FileName;
2694 
2695   Elf_Sym_Range GotDynSyms;
2696   StringRef PltStrTable;
2697 
2698   Entries GotEntries;
2699   Entries PltEntries;
2700 };
2701 
2702 } // end anonymous namespace
2703 
2704 template <class ELFT>
2705 MipsGOTParser<ELFT>::MipsGOTParser(const ELFDumper<ELFT> &D)
2706     : IsStatic(D.dynamic_table().empty()), Obj(D.getElfObject().getELFFile()),
2707       Dumper(D), GotSec(nullptr), LocalNum(0), GlobalNum(0), PltSec(nullptr),
2708       PltRelSec(nullptr), PltSymTable(nullptr),
2709       FileName(D.getElfObject().getFileName()) {}
2710 
2711 template <class ELFT>
2712 Error MipsGOTParser<ELFT>::findGOT(Elf_Dyn_Range DynTable,
2713                                    Elf_Sym_Range DynSyms) {
2714   // See "Global Offset Table" in Chapter 5 in the following document
2715   // for detailed GOT description.
2716   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
2717 
2718   // Find static GOT secton.
2719   if (IsStatic) {
2720     GotSec = Dumper.findSectionByName(".got");
2721     if (!GotSec)
2722       return Error::success();
2723 
2724     ArrayRef<uint8_t> Content =
2725         unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
2726     GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
2727                          Content.size() / sizeof(Entry));
2728     LocalNum = GotEntries.size();
2729     return Error::success();
2730   }
2731 
2732   // Lookup dynamic table tags which define the GOT layout.
2733   Optional<uint64_t> DtPltGot;
2734   Optional<uint64_t> DtLocalGotNum;
2735   Optional<uint64_t> DtGotSym;
2736   for (const auto &Entry : DynTable) {
2737     switch (Entry.getTag()) {
2738     case ELF::DT_PLTGOT:
2739       DtPltGot = Entry.getVal();
2740       break;
2741     case ELF::DT_MIPS_LOCAL_GOTNO:
2742       DtLocalGotNum = Entry.getVal();
2743       break;
2744     case ELF::DT_MIPS_GOTSYM:
2745       DtGotSym = Entry.getVal();
2746       break;
2747     }
2748   }
2749 
2750   if (!DtPltGot && !DtLocalGotNum && !DtGotSym)
2751     return Error::success();
2752 
2753   if (!DtPltGot)
2754     return createError("cannot find PLTGOT dynamic tag");
2755   if (!DtLocalGotNum)
2756     return createError("cannot find MIPS_LOCAL_GOTNO dynamic tag");
2757   if (!DtGotSym)
2758     return createError("cannot find MIPS_GOTSYM dynamic tag");
2759 
2760   size_t DynSymTotal = DynSyms.size();
2761   if (*DtGotSym > DynSymTotal)
2762     return createError("DT_MIPS_GOTSYM value (" + Twine(*DtGotSym) +
2763                        ") exceeds the number of dynamic symbols (" +
2764                        Twine(DynSymTotal) + ")");
2765 
2766   GotSec = findNotEmptySectionByAddress(Obj, FileName, *DtPltGot);
2767   if (!GotSec)
2768     return createError("there is no non-empty GOT section at 0x" +
2769                        Twine::utohexstr(*DtPltGot));
2770 
2771   LocalNum = *DtLocalGotNum;
2772   GlobalNum = DynSymTotal - *DtGotSym;
2773 
2774   ArrayRef<uint8_t> Content =
2775       unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
2776   GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
2777                        Content.size() / sizeof(Entry));
2778   GotDynSyms = DynSyms.drop_front(*DtGotSym);
2779 
2780   return Error::success();
2781 }
2782 
2783 template <class ELFT>
2784 Error MipsGOTParser<ELFT>::findPLT(Elf_Dyn_Range DynTable) {
2785   // Lookup dynamic table tags which define the PLT layout.
2786   Optional<uint64_t> DtMipsPltGot;
2787   Optional<uint64_t> DtJmpRel;
2788   for (const auto &Entry : DynTable) {
2789     switch (Entry.getTag()) {
2790     case ELF::DT_MIPS_PLTGOT:
2791       DtMipsPltGot = Entry.getVal();
2792       break;
2793     case ELF::DT_JMPREL:
2794       DtJmpRel = Entry.getVal();
2795       break;
2796     }
2797   }
2798 
2799   if (!DtMipsPltGot && !DtJmpRel)
2800     return Error::success();
2801 
2802   // Find PLT section.
2803   if (!DtMipsPltGot)
2804     return createError("cannot find MIPS_PLTGOT dynamic tag");
2805   if (!DtJmpRel)
2806     return createError("cannot find JMPREL dynamic tag");
2807 
2808   PltSec = findNotEmptySectionByAddress(Obj, FileName, *DtMipsPltGot);
2809   if (!PltSec)
2810     return createError("there is no non-empty PLTGOT section at 0x" +
2811                        Twine::utohexstr(*DtMipsPltGot));
2812 
2813   PltRelSec = findNotEmptySectionByAddress(Obj, FileName, *DtJmpRel);
2814   if (!PltRelSec)
2815     return createError("there is no non-empty RELPLT section at 0x" +
2816                        Twine::utohexstr(*DtJmpRel));
2817 
2818   if (Expected<ArrayRef<uint8_t>> PltContentOrErr =
2819           Obj.getSectionContents(*PltSec))
2820     PltEntries =
2821         Entries(reinterpret_cast<const Entry *>(PltContentOrErr->data()),
2822                 PltContentOrErr->size() / sizeof(Entry));
2823   else
2824     return createError("unable to read PLTGOT section content: " +
2825                        toString(PltContentOrErr.takeError()));
2826 
2827   if (Expected<const Elf_Shdr *> PltSymTableOrErr =
2828           Obj.getSection(PltRelSec->sh_link))
2829     PltSymTable = *PltSymTableOrErr;
2830   else
2831     return createError("unable to get a symbol table linked to the " +
2832                        describe(Obj, *PltRelSec) + ": " +
2833                        toString(PltSymTableOrErr.takeError()));
2834 
2835   if (Expected<StringRef> StrTabOrErr =
2836           Obj.getStringTableForSymtab(*PltSymTable))
2837     PltStrTable = *StrTabOrErr;
2838   else
2839     return createError("unable to get a string table for the " +
2840                        describe(Obj, *PltSymTable) + ": " +
2841                        toString(StrTabOrErr.takeError()));
2842 
2843   return Error::success();
2844 }
2845 
2846 template <class ELFT> uint64_t MipsGOTParser<ELFT>::getGp() const {
2847   return GotSec->sh_addr + 0x7ff0;
2848 }
2849 
2850 template <class ELFT>
2851 const typename MipsGOTParser<ELFT>::Entry *
2852 MipsGOTParser<ELFT>::getGotLazyResolver() const {
2853   return LocalNum > 0 ? &GotEntries[0] : nullptr;
2854 }
2855 
2856 template <class ELFT>
2857 const typename MipsGOTParser<ELFT>::Entry *
2858 MipsGOTParser<ELFT>::getGotModulePointer() const {
2859   if (LocalNum < 2)
2860     return nullptr;
2861   const Entry &E = GotEntries[1];
2862   if ((E >> (sizeof(Entry) * 8 - 1)) == 0)
2863     return nullptr;
2864   return &E;
2865 }
2866 
2867 template <class ELFT>
2868 typename MipsGOTParser<ELFT>::Entries
2869 MipsGOTParser<ELFT>::getLocalEntries() const {
2870   size_t Skip = getGotModulePointer() ? 2 : 1;
2871   if (LocalNum - Skip <= 0)
2872     return Entries();
2873   return GotEntries.slice(Skip, LocalNum - Skip);
2874 }
2875 
2876 template <class ELFT>
2877 typename MipsGOTParser<ELFT>::Entries
2878 MipsGOTParser<ELFT>::getGlobalEntries() const {
2879   if (GlobalNum == 0)
2880     return Entries();
2881   return GotEntries.slice(LocalNum, GlobalNum);
2882 }
2883 
2884 template <class ELFT>
2885 typename MipsGOTParser<ELFT>::Entries
2886 MipsGOTParser<ELFT>::getOtherEntries() const {
2887   size_t OtherNum = GotEntries.size() - LocalNum - GlobalNum;
2888   if (OtherNum == 0)
2889     return Entries();
2890   return GotEntries.slice(LocalNum + GlobalNum, OtherNum);
2891 }
2892 
2893 template <class ELFT>
2894 uint64_t MipsGOTParser<ELFT>::getGotAddress(const Entry *E) const {
2895   int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
2896   return GotSec->sh_addr + Offset;
2897 }
2898 
2899 template <class ELFT>
2900 int64_t MipsGOTParser<ELFT>::getGotOffset(const Entry *E) const {
2901   int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
2902   return Offset - 0x7ff0;
2903 }
2904 
2905 template <class ELFT>
2906 const typename MipsGOTParser<ELFT>::Elf_Sym *
2907 MipsGOTParser<ELFT>::getGotSym(const Entry *E) const {
2908   int64_t Offset = std::distance(GotEntries.data(), E);
2909   return &GotDynSyms[Offset - LocalNum];
2910 }
2911 
2912 template <class ELFT>
2913 const typename MipsGOTParser<ELFT>::Entry *
2914 MipsGOTParser<ELFT>::getPltLazyResolver() const {
2915   return PltEntries.empty() ? nullptr : &PltEntries[0];
2916 }
2917 
2918 template <class ELFT>
2919 const typename MipsGOTParser<ELFT>::Entry *
2920 MipsGOTParser<ELFT>::getPltModulePointer() const {
2921   return PltEntries.size() < 2 ? nullptr : &PltEntries[1];
2922 }
2923 
2924 template <class ELFT>
2925 typename MipsGOTParser<ELFT>::Entries
2926 MipsGOTParser<ELFT>::getPltEntries() const {
2927   if (PltEntries.size() <= 2)
2928     return Entries();
2929   return PltEntries.slice(2, PltEntries.size() - 2);
2930 }
2931 
2932 template <class ELFT>
2933 uint64_t MipsGOTParser<ELFT>::getPltAddress(const Entry *E) const {
2934   int64_t Offset = std::distance(PltEntries.data(), E) * sizeof(Entry);
2935   return PltSec->sh_addr + Offset;
2936 }
2937 
2938 template <class ELFT>
2939 const typename MipsGOTParser<ELFT>::Elf_Sym *
2940 MipsGOTParser<ELFT>::getPltSym(const Entry *E) const {
2941   int64_t Offset = std::distance(getPltEntries().data(), E);
2942   if (PltRelSec->sh_type == ELF::SHT_REL) {
2943     Elf_Rel_Range Rels = unwrapOrError(FileName, Obj.rels(*PltRelSec));
2944     return unwrapOrError(FileName,
2945                          Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
2946   } else {
2947     Elf_Rela_Range Rels = unwrapOrError(FileName, Obj.relas(*PltRelSec));
2948     return unwrapOrError(FileName,
2949                          Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
2950   }
2951 }
2952 
2953 const EnumEntry<unsigned> ElfMipsISAExtType[] = {
2954   {"None",                    Mips::AFL_EXT_NONE},
2955   {"Broadcom SB-1",           Mips::AFL_EXT_SB1},
2956   {"Cavium Networks Octeon",  Mips::AFL_EXT_OCTEON},
2957   {"Cavium Networks Octeon2", Mips::AFL_EXT_OCTEON2},
2958   {"Cavium Networks OcteonP", Mips::AFL_EXT_OCTEONP},
2959   {"Cavium Networks Octeon3", Mips::AFL_EXT_OCTEON3},
2960   {"LSI R4010",               Mips::AFL_EXT_4010},
2961   {"Loongson 2E",             Mips::AFL_EXT_LOONGSON_2E},
2962   {"Loongson 2F",             Mips::AFL_EXT_LOONGSON_2F},
2963   {"Loongson 3A",             Mips::AFL_EXT_LOONGSON_3A},
2964   {"MIPS R4650",              Mips::AFL_EXT_4650},
2965   {"MIPS R5900",              Mips::AFL_EXT_5900},
2966   {"MIPS R10000",             Mips::AFL_EXT_10000},
2967   {"NEC VR4100",              Mips::AFL_EXT_4100},
2968   {"NEC VR4111/VR4181",       Mips::AFL_EXT_4111},
2969   {"NEC VR4120",              Mips::AFL_EXT_4120},
2970   {"NEC VR5400",              Mips::AFL_EXT_5400},
2971   {"NEC VR5500",              Mips::AFL_EXT_5500},
2972   {"RMI Xlr",                 Mips::AFL_EXT_XLR},
2973   {"Toshiba R3900",           Mips::AFL_EXT_3900}
2974 };
2975 
2976 const EnumEntry<unsigned> ElfMipsASEFlags[] = {
2977   {"DSP",                Mips::AFL_ASE_DSP},
2978   {"DSPR2",              Mips::AFL_ASE_DSPR2},
2979   {"Enhanced VA Scheme", Mips::AFL_ASE_EVA},
2980   {"MCU",                Mips::AFL_ASE_MCU},
2981   {"MDMX",               Mips::AFL_ASE_MDMX},
2982   {"MIPS-3D",            Mips::AFL_ASE_MIPS3D},
2983   {"MT",                 Mips::AFL_ASE_MT},
2984   {"SmartMIPS",          Mips::AFL_ASE_SMARTMIPS},
2985   {"VZ",                 Mips::AFL_ASE_VIRT},
2986   {"MSA",                Mips::AFL_ASE_MSA},
2987   {"MIPS16",             Mips::AFL_ASE_MIPS16},
2988   {"microMIPS",          Mips::AFL_ASE_MICROMIPS},
2989   {"XPA",                Mips::AFL_ASE_XPA},
2990   {"CRC",                Mips::AFL_ASE_CRC},
2991   {"GINV",               Mips::AFL_ASE_GINV},
2992 };
2993 
2994 const EnumEntry<unsigned> ElfMipsFpABIType[] = {
2995   {"Hard or soft float",                  Mips::Val_GNU_MIPS_ABI_FP_ANY},
2996   {"Hard float (double precision)",       Mips::Val_GNU_MIPS_ABI_FP_DOUBLE},
2997   {"Hard float (single precision)",       Mips::Val_GNU_MIPS_ABI_FP_SINGLE},
2998   {"Soft float",                          Mips::Val_GNU_MIPS_ABI_FP_SOFT},
2999   {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)",
3000    Mips::Val_GNU_MIPS_ABI_FP_OLD_64},
3001   {"Hard float (32-bit CPU, Any FPU)",    Mips::Val_GNU_MIPS_ABI_FP_XX},
3002   {"Hard float (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64},
3003   {"Hard float compat (32-bit CPU, 64-bit FPU)",
3004    Mips::Val_GNU_MIPS_ABI_FP_64A}
3005 };
3006 
3007 static const EnumEntry<unsigned> ElfMipsFlags1[] {
3008   {"ODDSPREG", Mips::AFL_FLAGS1_ODDSPREG},
3009 };
3010 
3011 static int getMipsRegisterSize(uint8_t Flag) {
3012   switch (Flag) {
3013   case Mips::AFL_REG_NONE:
3014     return 0;
3015   case Mips::AFL_REG_32:
3016     return 32;
3017   case Mips::AFL_REG_64:
3018     return 64;
3019   case Mips::AFL_REG_128:
3020     return 128;
3021   default:
3022     return -1;
3023   }
3024 }
3025 
3026 template <class ELFT>
3027 static void printMipsReginfoData(ScopedPrinter &W,
3028                                  const Elf_Mips_RegInfo<ELFT> &Reginfo) {
3029   W.printHex("GP", Reginfo.ri_gp_value);
3030   W.printHex("General Mask", Reginfo.ri_gprmask);
3031   W.printHex("Co-Proc Mask0", Reginfo.ri_cprmask[0]);
3032   W.printHex("Co-Proc Mask1", Reginfo.ri_cprmask[1]);
3033   W.printHex("Co-Proc Mask2", Reginfo.ri_cprmask[2]);
3034   W.printHex("Co-Proc Mask3", Reginfo.ri_cprmask[3]);
3035 }
3036 
3037 template <class ELFT> void ELFDumper<ELFT>::printMipsReginfo() {
3038   const Elf_Shdr *RegInfoSec = findSectionByName(".reginfo");
3039   if (!RegInfoSec) {
3040     W.startLine() << "There is no .reginfo section in the file.\n";
3041     return;
3042   }
3043 
3044   Expected<ArrayRef<uint8_t>> ContentsOrErr =
3045       Obj.getSectionContents(*RegInfoSec);
3046   if (!ContentsOrErr) {
3047     this->reportUniqueWarning(
3048         "unable to read the content of the .reginfo section (" +
3049         describe(*RegInfoSec) + "): " + toString(ContentsOrErr.takeError()));
3050     return;
3051   }
3052 
3053   if (ContentsOrErr->size() < sizeof(Elf_Mips_RegInfo<ELFT>)) {
3054     this->reportUniqueWarning("the .reginfo section has an invalid size (0x" +
3055                               Twine::utohexstr(ContentsOrErr->size()) + ")");
3056     return;
3057   }
3058 
3059   DictScope GS(W, "MIPS RegInfo");
3060   printMipsReginfoData(W, *reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(
3061                               ContentsOrErr->data()));
3062 }
3063 
3064 template <class ELFT>
3065 static Expected<const Elf_Mips_Options<ELFT> *>
3066 readMipsOptions(const uint8_t *SecBegin, ArrayRef<uint8_t> &SecData,
3067                 bool &IsSupported) {
3068   if (SecData.size() < sizeof(Elf_Mips_Options<ELFT>))
3069     return createError("the .MIPS.options section has an invalid size (0x" +
3070                        Twine::utohexstr(SecData.size()) + ")");
3071 
3072   const Elf_Mips_Options<ELFT> *O =
3073       reinterpret_cast<const Elf_Mips_Options<ELFT> *>(SecData.data());
3074   const uint8_t Size = O->size;
3075   if (Size > SecData.size()) {
3076     const uint64_t Offset = SecData.data() - SecBegin;
3077     const uint64_t SecSize = Offset + SecData.size();
3078     return createError("a descriptor of size 0x" + Twine::utohexstr(Size) +
3079                        " at offset 0x" + Twine::utohexstr(Offset) +
3080                        " goes past the end of the .MIPS.options "
3081                        "section of size 0x" +
3082                        Twine::utohexstr(SecSize));
3083   }
3084 
3085   IsSupported = O->kind == ODK_REGINFO;
3086   const size_t ExpectedSize =
3087       sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>);
3088 
3089   if (IsSupported)
3090     if (Size < ExpectedSize)
3091       return createError(
3092           "a .MIPS.options entry of kind " +
3093           Twine(getElfMipsOptionsOdkType(O->kind)) +
3094           " has an invalid size (0x" + Twine::utohexstr(Size) +
3095           "), the expected size is 0x" + Twine::utohexstr(ExpectedSize));
3096 
3097   SecData = SecData.drop_front(Size);
3098   return O;
3099 }
3100 
3101 template <class ELFT> void ELFDumper<ELFT>::printMipsOptions() {
3102   const Elf_Shdr *MipsOpts = findSectionByName(".MIPS.options");
3103   if (!MipsOpts) {
3104     W.startLine() << "There is no .MIPS.options section in the file.\n";
3105     return;
3106   }
3107 
3108   DictScope GS(W, "MIPS Options");
3109 
3110   ArrayRef<uint8_t> Data =
3111       unwrapOrError(ObjF.getFileName(), Obj.getSectionContents(*MipsOpts));
3112   const uint8_t *const SecBegin = Data.begin();
3113   while (!Data.empty()) {
3114     bool IsSupported;
3115     Expected<const Elf_Mips_Options<ELFT> *> OptsOrErr =
3116         readMipsOptions<ELFT>(SecBegin, Data, IsSupported);
3117     if (!OptsOrErr) {
3118       reportUniqueWarning(OptsOrErr.takeError());
3119       break;
3120     }
3121 
3122     unsigned Kind = (*OptsOrErr)->kind;
3123     const char *Type = getElfMipsOptionsOdkType(Kind);
3124     if (!IsSupported) {
3125       W.startLine() << "Unsupported MIPS options tag: " << Type << " (" << Kind
3126                     << ")\n";
3127       continue;
3128     }
3129 
3130     DictScope GS(W, Type);
3131     if (Kind == ODK_REGINFO)
3132       printMipsReginfoData(W, (*OptsOrErr)->getRegInfo());
3133     else
3134       llvm_unreachable("unexpected .MIPS.options section descriptor kind");
3135   }
3136 }
3137 
3138 template <class ELFT> void ELFDumper<ELFT>::printStackMap() const {
3139   const Elf_Shdr *StackMapSection = findSectionByName(".llvm_stackmaps");
3140   if (!StackMapSection)
3141     return;
3142 
3143   auto Warn = [&](Error &&E) {
3144     this->reportUniqueWarning("unable to read the stack map from " +
3145                               describe(*StackMapSection) + ": " +
3146                               toString(std::move(E)));
3147   };
3148 
3149   Expected<ArrayRef<uint8_t>> ContentOrErr =
3150       Obj.getSectionContents(*StackMapSection);
3151   if (!ContentOrErr) {
3152     Warn(ContentOrErr.takeError());
3153     return;
3154   }
3155 
3156   if (Error E = StackMapParser<ELFT::TargetEndianness>::validateHeader(
3157           *ContentOrErr)) {
3158     Warn(std::move(E));
3159     return;
3160   }
3161 
3162   prettyPrintStackMap(W, StackMapParser<ELFT::TargetEndianness>(*ContentOrErr));
3163 }
3164 
3165 template <class ELFT>
3166 void ELFDumper<ELFT>::printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
3167                                  const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
3168   Expected<RelSymbol<ELFT>> Target = getRelocationTarget(R, SymTab);
3169   if (!Target)
3170     reportUniqueWarning("unable to print relocation " + Twine(RelIndex) +
3171                         " in " + describe(Sec) + ": " +
3172                         toString(Target.takeError()));
3173   else
3174     printRelRelaReloc(R, *Target);
3175 }
3176 
3177 static inline void printFields(formatted_raw_ostream &OS, StringRef Str1,
3178                                StringRef Str2) {
3179   OS.PadToColumn(2u);
3180   OS << Str1;
3181   OS.PadToColumn(37u);
3182   OS << Str2 << "\n";
3183   OS.flush();
3184 }
3185 
3186 template <class ELFT>
3187 static std::string getSectionHeadersNumString(const ELFFile<ELFT> &Obj,
3188                                               StringRef FileName) {
3189   const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3190   if (ElfHeader.e_shnum != 0)
3191     return to_string(ElfHeader.e_shnum);
3192 
3193   Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3194   if (!ArrOrErr) {
3195     // In this case we can ignore an error, because we have already reported a
3196     // warning about the broken section header table earlier.
3197     consumeError(ArrOrErr.takeError());
3198     return "<?>";
3199   }
3200 
3201   if (ArrOrErr->empty())
3202     return "0";
3203   return "0 (" + to_string((*ArrOrErr)[0].sh_size) + ")";
3204 }
3205 
3206 template <class ELFT>
3207 static std::string getSectionHeaderTableIndexString(const ELFFile<ELFT> &Obj,
3208                                                     StringRef FileName) {
3209   const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3210   if (ElfHeader.e_shstrndx != SHN_XINDEX)
3211     return to_string(ElfHeader.e_shstrndx);
3212 
3213   Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3214   if (!ArrOrErr) {
3215     // In this case we can ignore an error, because we have already reported a
3216     // warning about the broken section header table earlier.
3217     consumeError(ArrOrErr.takeError());
3218     return "<?>";
3219   }
3220 
3221   if (ArrOrErr->empty())
3222     return "65535 (corrupt: out of range)";
3223   return to_string(ElfHeader.e_shstrndx) + " (" +
3224          to_string((*ArrOrErr)[0].sh_link) + ")";
3225 }
3226 
3227 static const EnumEntry<unsigned> *getObjectFileEnumEntry(unsigned Type) {
3228   auto It = llvm::find_if(ElfObjectFileType, [&](const EnumEntry<unsigned> &E) {
3229     return E.Value == Type;
3230   });
3231   if (It != makeArrayRef(ElfObjectFileType).end())
3232     return It;
3233   return nullptr;
3234 }
3235 
3236 template <class ELFT> void GNUELFDumper<ELFT>::printFileHeaders() {
3237   const Elf_Ehdr &e = this->Obj.getHeader();
3238   OS << "ELF Header:\n";
3239   OS << "  Magic:  ";
3240   std::string Str;
3241   for (int i = 0; i < ELF::EI_NIDENT; i++)
3242     OS << format(" %02x", static_cast<int>(e.e_ident[i]));
3243   OS << "\n";
3244   Str = printEnum(e.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass));
3245   printFields(OS, "Class:", Str);
3246   Str = printEnum(e.e_ident[ELF::EI_DATA], makeArrayRef(ElfDataEncoding));
3247   printFields(OS, "Data:", Str);
3248   OS.PadToColumn(2u);
3249   OS << "Version:";
3250   OS.PadToColumn(37u);
3251   OS << to_hexString(e.e_ident[ELF::EI_VERSION]);
3252   if (e.e_version == ELF::EV_CURRENT)
3253     OS << " (current)";
3254   OS << "\n";
3255   Str = printEnum(e.e_ident[ELF::EI_OSABI], makeArrayRef(ElfOSABI));
3256   printFields(OS, "OS/ABI:", Str);
3257   printFields(OS,
3258               "ABI Version:", std::to_string(e.e_ident[ELF::EI_ABIVERSION]));
3259 
3260   if (const EnumEntry<unsigned> *E = getObjectFileEnumEntry(e.e_type)) {
3261     Str = E->AltName.str();
3262   } else {
3263     if (e.e_type >= ET_LOPROC)
3264       Str = "Processor Specific: (" + to_hexString(e.e_type, false) + ")";
3265     else if (e.e_type >= ET_LOOS)
3266       Str = "OS Specific: (" + to_hexString(e.e_type, false) + ")";
3267     else
3268       Str = "<unknown>: " + to_hexString(e.e_type, false);
3269   }
3270   printFields(OS, "Type:", Str);
3271 
3272   Str = printEnum(e.e_machine, makeArrayRef(ElfMachineType));
3273   printFields(OS, "Machine:", Str);
3274   Str = "0x" + to_hexString(e.e_version);
3275   printFields(OS, "Version:", Str);
3276   Str = "0x" + to_hexString(e.e_entry);
3277   printFields(OS, "Entry point address:", Str);
3278   Str = to_string(e.e_phoff) + " (bytes into file)";
3279   printFields(OS, "Start of program headers:", Str);
3280   Str = to_string(e.e_shoff) + " (bytes into file)";
3281   printFields(OS, "Start of section headers:", Str);
3282   std::string ElfFlags;
3283   if (e.e_machine == EM_MIPS)
3284     ElfFlags =
3285         printFlags(e.e_flags, makeArrayRef(ElfHeaderMipsFlags),
3286                    unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
3287                    unsigned(ELF::EF_MIPS_MACH));
3288   else if (e.e_machine == EM_RISCV)
3289     ElfFlags = printFlags(e.e_flags, makeArrayRef(ElfHeaderRISCVFlags));
3290   else if (e.e_machine == EM_AVR)
3291     ElfFlags = printFlags(e.e_flags, makeArrayRef(ElfHeaderAVRFlags),
3292                           unsigned(ELF::EF_AVR_ARCH_MASK));
3293   Str = "0x" + to_hexString(e.e_flags);
3294   if (!ElfFlags.empty())
3295     Str = Str + ", " + ElfFlags;
3296   printFields(OS, "Flags:", Str);
3297   Str = to_string(e.e_ehsize) + " (bytes)";
3298   printFields(OS, "Size of this header:", Str);
3299   Str = to_string(e.e_phentsize) + " (bytes)";
3300   printFields(OS, "Size of program headers:", Str);
3301   Str = to_string(e.e_phnum);
3302   printFields(OS, "Number of program headers:", Str);
3303   Str = to_string(e.e_shentsize) + " (bytes)";
3304   printFields(OS, "Size of section headers:", Str);
3305   Str = getSectionHeadersNumString(this->Obj, this->FileName);
3306   printFields(OS, "Number of section headers:", Str);
3307   Str = getSectionHeaderTableIndexString(this->Obj, this->FileName);
3308   printFields(OS, "Section header string table index:", Str);
3309 }
3310 
3311 template <class ELFT> std::vector<GroupSection> ELFDumper<ELFT>::getGroups() {
3312   auto GetSignature = [&](const Elf_Sym &Sym, unsigned SymNdx,
3313                           const Elf_Shdr &Symtab) -> StringRef {
3314     Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(Symtab);
3315     if (!StrTableOrErr) {
3316       reportUniqueWarning("unable to get the string table for " +
3317                           describe(Symtab) + ": " +
3318                           toString(StrTableOrErr.takeError()));
3319       return "<?>";
3320     }
3321 
3322     StringRef Strings = *StrTableOrErr;
3323     if (Sym.st_name >= Strings.size()) {
3324       reportUniqueWarning("unable to get the name of the symbol with index " +
3325                           Twine(SymNdx) + ": st_name (0x" +
3326                           Twine::utohexstr(Sym.st_name) +
3327                           ") is past the end of the string table of size 0x" +
3328                           Twine::utohexstr(Strings.size()));
3329       return "<?>";
3330     }
3331 
3332     return StrTableOrErr->data() + Sym.st_name;
3333   };
3334 
3335   std::vector<GroupSection> Ret;
3336   uint64_t I = 0;
3337   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
3338     ++I;
3339     if (Sec.sh_type != ELF::SHT_GROUP)
3340       continue;
3341 
3342     StringRef Signature = "<?>";
3343     if (Expected<const Elf_Shdr *> SymtabOrErr = Obj.getSection(Sec.sh_link)) {
3344       if (Expected<const Elf_Sym *> SymOrErr =
3345               Obj.template getEntry<Elf_Sym>(**SymtabOrErr, Sec.sh_info))
3346         Signature = GetSignature(**SymOrErr, Sec.sh_info, **SymtabOrErr);
3347       else
3348         reportUniqueWarning("unable to get the signature symbol for " +
3349                             describe(Sec) + ": " +
3350                             toString(SymOrErr.takeError()));
3351     } else {
3352       reportUniqueWarning("unable to get the symbol table for " +
3353                           describe(Sec) + ": " +
3354                           toString(SymtabOrErr.takeError()));
3355     }
3356 
3357     ArrayRef<Elf_Word> Data;
3358     if (Expected<ArrayRef<Elf_Word>> ContentsOrErr =
3359             Obj.template getSectionContentsAsArray<Elf_Word>(Sec)) {
3360       if (ContentsOrErr->empty())
3361         reportUniqueWarning("unable to read the section group flag from the " +
3362                             describe(Sec) + ": the section is empty");
3363       else
3364         Data = *ContentsOrErr;
3365     } else {
3366       reportUniqueWarning("unable to get the content of the " + describe(Sec) +
3367                           ": " + toString(ContentsOrErr.takeError()));
3368     }
3369 
3370     Ret.push_back({getPrintableSectionName(Sec),
3371                    maybeDemangle(Signature),
3372                    Sec.sh_name,
3373                    I - 1,
3374                    Sec.sh_link,
3375                    Sec.sh_info,
3376                    Data.empty() ? Elf_Word(0) : Data[0],
3377                    {}});
3378 
3379     if (Data.empty())
3380       continue;
3381 
3382     std::vector<GroupMember> &GM = Ret.back().Members;
3383     for (uint32_t Ndx : Data.slice(1)) {
3384       if (Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(Ndx)) {
3385         GM.push_back({getPrintableSectionName(**SecOrErr), Ndx});
3386       } else {
3387         reportUniqueWarning("unable to get the section with index " +
3388                             Twine(Ndx) + " when dumping the " + describe(Sec) +
3389                             ": " + toString(SecOrErr.takeError()));
3390         GM.push_back({"<?>", Ndx});
3391       }
3392     }
3393   }
3394   return Ret;
3395 }
3396 
3397 static DenseMap<uint64_t, const GroupSection *>
3398 mapSectionsToGroups(ArrayRef<GroupSection> Groups) {
3399   DenseMap<uint64_t, const GroupSection *> Ret;
3400   for (const GroupSection &G : Groups)
3401     for (const GroupMember &GM : G.Members)
3402       Ret.insert({GM.Index, &G});
3403   return Ret;
3404 }
3405 
3406 template <class ELFT> void GNUELFDumper<ELFT>::printGroupSections() {
3407   std::vector<GroupSection> V = this->getGroups();
3408   DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
3409   for (const GroupSection &G : V) {
3410     OS << "\n"
3411        << getGroupType(G.Type) << " group section ["
3412        << format_decimal(G.Index, 5) << "] `" << G.Name << "' [" << G.Signature
3413        << "] contains " << G.Members.size() << " sections:\n"
3414        << "   [Index]    Name\n";
3415     for (const GroupMember &GM : G.Members) {
3416       const GroupSection *MainGroup = Map[GM.Index];
3417       if (MainGroup != &G)
3418         this->reportUniqueWarning(
3419             "section with index " + Twine(GM.Index) +
3420             ", included in the group section with index " +
3421             Twine(MainGroup->Index) +
3422             ", was also found in the group section with index " +
3423             Twine(G.Index));
3424       OS << "   [" << format_decimal(GM.Index, 5) << "]   " << GM.Name << "\n";
3425     }
3426   }
3427 
3428   if (V.empty())
3429     OS << "There are no section groups in this file.\n";
3430 }
3431 
3432 template <class ELFT>
3433 void GNUELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
3434   OS << to_string(format_hex_no_prefix(R, ELFT::Is64Bits ? 16 : 8)) << "\n";
3435 }
3436 
3437 template <class ELFT>
3438 void GNUELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
3439                                            const RelSymbol<ELFT> &RelSym) {
3440   // First two fields are bit width dependent. The rest of them are fixed width.
3441   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3442   Field Fields[5] = {0, 10 + Bias, 19 + 2 * Bias, 42 + 2 * Bias, 53 + 2 * Bias};
3443   unsigned Width = ELFT::Is64Bits ? 16 : 8;
3444 
3445   Fields[0].Str = to_string(format_hex_no_prefix(R.Offset, Width));
3446   Fields[1].Str = to_string(format_hex_no_prefix(R.Info, Width));
3447 
3448   SmallString<32> RelocName;
3449   this->Obj.getRelocationTypeName(R.Type, RelocName);
3450   Fields[2].Str = RelocName.c_str();
3451 
3452   if (RelSym.Sym)
3453     Fields[3].Str =
3454         to_string(format_hex_no_prefix(RelSym.Sym->getValue(), Width));
3455 
3456   Fields[4].Str = std::string(RelSym.Name);
3457   for (const Field &F : Fields)
3458     printField(F);
3459 
3460   std::string Addend;
3461   if (Optional<int64_t> A = R.Addend) {
3462     int64_t RelAddend = *A;
3463     if (!RelSym.Name.empty()) {
3464       if (RelAddend < 0) {
3465         Addend = " - ";
3466         RelAddend = std::abs(RelAddend);
3467       } else {
3468         Addend = " + ";
3469       }
3470     }
3471     Addend += to_hexString(RelAddend, false);
3472   }
3473   OS << Addend << "\n";
3474 }
3475 
3476 template <class ELFT>
3477 static void printRelocHeaderFields(formatted_raw_ostream &OS, unsigned SType) {
3478   bool IsRela = SType == ELF::SHT_RELA || SType == ELF::SHT_ANDROID_RELA;
3479   bool IsRelr = SType == ELF::SHT_RELR || SType == ELF::SHT_ANDROID_RELR;
3480   if (ELFT::Is64Bits)
3481     OS << "    ";
3482   else
3483     OS << " ";
3484   if (IsRelr && opts::RawRelr)
3485     OS << "Data  ";
3486   else
3487     OS << "Offset";
3488   if (ELFT::Is64Bits)
3489     OS << "             Info             Type"
3490        << "               Symbol's Value  Symbol's Name";
3491   else
3492     OS << "     Info    Type                Sym. Value  Symbol's Name";
3493   if (IsRela)
3494     OS << " + Addend";
3495   OS << "\n";
3496 }
3497 
3498 template <class ELFT>
3499 void GNUELFDumper<ELFT>::printDynamicRelocHeader(unsigned Type, StringRef Name,
3500                                                  const DynRegionInfo &Reg) {
3501   uint64_t Offset = Reg.Addr - this->Obj.base();
3502   OS << "\n'" << Name.str().c_str() << "' relocation section at offset 0x"
3503      << to_hexString(Offset, false) << " contains " << Reg.Size << " bytes:\n";
3504   printRelocHeaderFields<ELFT>(OS, Type);
3505 }
3506 
3507 template <class ELFT>
3508 static bool isRelocationSec(const typename ELFT::Shdr &Sec) {
3509   return Sec.sh_type == ELF::SHT_REL || Sec.sh_type == ELF::SHT_RELA ||
3510          Sec.sh_type == ELF::SHT_RELR || Sec.sh_type == ELF::SHT_ANDROID_REL ||
3511          Sec.sh_type == ELF::SHT_ANDROID_RELA ||
3512          Sec.sh_type == ELF::SHT_ANDROID_RELR;
3513 }
3514 
3515 template <class ELFT> void GNUELFDumper<ELFT>::printRelocations() {
3516   auto GetEntriesNum = [&](const Elf_Shdr &Sec) -> Expected<size_t> {
3517     // Android's packed relocation section needs to be unpacked first
3518     // to get the actual number of entries.
3519     if (Sec.sh_type == ELF::SHT_ANDROID_REL ||
3520         Sec.sh_type == ELF::SHT_ANDROID_RELA) {
3521       Expected<std::vector<typename ELFT::Rela>> RelasOrErr =
3522           this->Obj.android_relas(Sec);
3523       if (!RelasOrErr)
3524         return RelasOrErr.takeError();
3525       return RelasOrErr->size();
3526     }
3527 
3528     if (!opts::RawRelr && (Sec.sh_type == ELF::SHT_RELR ||
3529                            Sec.sh_type == ELF::SHT_ANDROID_RELR)) {
3530       Expected<Elf_Relr_Range> RelrsOrErr = this->Obj.relrs(Sec);
3531       if (!RelrsOrErr)
3532         return RelrsOrErr.takeError();
3533       return this->Obj.decode_relrs(*RelrsOrErr).size();
3534     }
3535 
3536     return Sec.getEntityCount();
3537   };
3538 
3539   bool HasRelocSections = false;
3540   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
3541     if (!isRelocationSec<ELFT>(Sec))
3542       continue;
3543     HasRelocSections = true;
3544 
3545     std::string EntriesNum = "<?>";
3546     if (Expected<size_t> NumOrErr = GetEntriesNum(Sec))
3547       EntriesNum = std::to_string(*NumOrErr);
3548     else
3549       this->reportUniqueWarning("unable to get the number of relocations in " +
3550                                 this->describe(Sec) + ": " +
3551                                 toString(NumOrErr.takeError()));
3552 
3553     uintX_t Offset = Sec.sh_offset;
3554     StringRef Name = this->getPrintableSectionName(Sec);
3555     OS << "\nRelocation section '" << Name << "' at offset 0x"
3556        << to_hexString(Offset, false) << " contains " << EntriesNum
3557        << " entries:\n";
3558     printRelocHeaderFields<ELFT>(OS, Sec.sh_type);
3559     this->printRelocationsHelper(Sec);
3560   }
3561   if (!HasRelocSections)
3562     OS << "\nThere are no relocations in this file.\n";
3563 }
3564 
3565 // Print the offset of a particular section from anyone of the ranges:
3566 // [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER].
3567 // If 'Type' does not fall within any of those ranges, then a string is
3568 // returned as '<unknown>' followed by the type value.
3569 static std::string getSectionTypeOffsetString(unsigned Type) {
3570   if (Type >= SHT_LOOS && Type <= SHT_HIOS)
3571     return "LOOS+0x" + to_hexString(Type - SHT_LOOS);
3572   else if (Type >= SHT_LOPROC && Type <= SHT_HIPROC)
3573     return "LOPROC+0x" + to_hexString(Type - SHT_LOPROC);
3574   else if (Type >= SHT_LOUSER && Type <= SHT_HIUSER)
3575     return "LOUSER+0x" + to_hexString(Type - SHT_LOUSER);
3576   return "0x" + to_hexString(Type) + ": <unknown>";
3577 }
3578 
3579 static std::string getSectionTypeString(unsigned Machine, unsigned Type) {
3580   StringRef Name = getELFSectionTypeName(Machine, Type);
3581 
3582   // Handle SHT_GNU_* type names.
3583   if (Name.startswith("SHT_GNU_")) {
3584     if (Name == "SHT_GNU_HASH")
3585       return "GNU_HASH";
3586     // E.g. SHT_GNU_verneed -> VERNEED.
3587     return Name.drop_front(8).upper();
3588   }
3589 
3590   if (Name == "SHT_SYMTAB_SHNDX")
3591     return "SYMTAB SECTION INDICES";
3592 
3593   if (Name.startswith("SHT_"))
3594     return Name.drop_front(4).str();
3595   return getSectionTypeOffsetString(Type);
3596 }
3597 
3598 static void printSectionDescription(formatted_raw_ostream &OS,
3599                                     unsigned EMachine) {
3600   OS << "Key to Flags:\n";
3601   OS << "  W (write), A (alloc), X (execute), M (merge), S (strings), I "
3602         "(info),\n";
3603   OS << "  L (link order), O (extra OS processing required), G (group), T "
3604         "(TLS),\n";
3605   OS << "  C (compressed), x (unknown), o (OS specific), E (exclude),\n";
3606   OS << "  R (retain)";
3607 
3608   if (EMachine == EM_X86_64)
3609     OS << ", l (large)";
3610   else if (EMachine == EM_ARM)
3611     OS << ", y (purecode)";
3612 
3613   OS << ", p (processor specific)\n";
3614 }
3615 
3616 template <class ELFT> void GNUELFDumper<ELFT>::printSectionHeaders() {
3617   unsigned Bias = ELFT::Is64Bits ? 0 : 8;
3618   ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
3619   OS << "There are " << to_string(Sections.size())
3620      << " section headers, starting at offset "
3621      << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n";
3622   OS << "Section Headers:\n";
3623   Field Fields[11] = {
3624       {"[Nr]", 2},        {"Name", 7},        {"Type", 25},
3625       {"Address", 41},    {"Off", 58 - Bias}, {"Size", 65 - Bias},
3626       {"ES", 72 - Bias},  {"Flg", 75 - Bias}, {"Lk", 79 - Bias},
3627       {"Inf", 82 - Bias}, {"Al", 86 - Bias}};
3628   for (const Field &F : Fields)
3629     printField(F);
3630   OS << "\n";
3631 
3632   StringRef SecStrTable;
3633   if (Expected<StringRef> SecStrTableOrErr =
3634           this->Obj.getSectionStringTable(Sections, this->WarningHandler))
3635     SecStrTable = *SecStrTableOrErr;
3636   else
3637     this->reportUniqueWarning(SecStrTableOrErr.takeError());
3638 
3639   size_t SectionIndex = 0;
3640   for (const Elf_Shdr &Sec : Sections) {
3641     Fields[0].Str = to_string(SectionIndex);
3642     if (SecStrTable.empty())
3643       Fields[1].Str = "<no-strings>";
3644     else
3645       Fields[1].Str = std::string(unwrapOrError<StringRef>(
3646           this->FileName, this->Obj.getSectionName(Sec, SecStrTable)));
3647     Fields[2].Str =
3648         getSectionTypeString(this->Obj.getHeader().e_machine, Sec.sh_type);
3649     Fields[3].Str =
3650         to_string(format_hex_no_prefix(Sec.sh_addr, ELFT::Is64Bits ? 16 : 8));
3651     Fields[4].Str = to_string(format_hex_no_prefix(Sec.sh_offset, 6));
3652     Fields[5].Str = to_string(format_hex_no_prefix(Sec.sh_size, 6));
3653     Fields[6].Str = to_string(format_hex_no_prefix(Sec.sh_entsize, 2));
3654     Fields[7].Str = getGNUFlags(this->Obj.getHeader().e_machine, Sec.sh_flags);
3655     Fields[8].Str = to_string(Sec.sh_link);
3656     Fields[9].Str = to_string(Sec.sh_info);
3657     Fields[10].Str = to_string(Sec.sh_addralign);
3658 
3659     OS.PadToColumn(Fields[0].Column);
3660     OS << "[" << right_justify(Fields[0].Str, 2) << "]";
3661     for (int i = 1; i < 7; i++)
3662       printField(Fields[i]);
3663     OS.PadToColumn(Fields[7].Column);
3664     OS << right_justify(Fields[7].Str, 3);
3665     OS.PadToColumn(Fields[8].Column);
3666     OS << right_justify(Fields[8].Str, 2);
3667     OS.PadToColumn(Fields[9].Column);
3668     OS << right_justify(Fields[9].Str, 3);
3669     OS.PadToColumn(Fields[10].Column);
3670     OS << right_justify(Fields[10].Str, 2);
3671     OS << "\n";
3672     ++SectionIndex;
3673   }
3674   printSectionDescription(OS, this->Obj.getHeader().e_machine);
3675 }
3676 
3677 template <class ELFT>
3678 void GNUELFDumper<ELFT>::printSymtabMessage(const Elf_Shdr *Symtab,
3679                                             size_t Entries,
3680                                             bool NonVisibilityBitsUsed) const {
3681   StringRef Name;
3682   if (Symtab)
3683     Name = this->getPrintableSectionName(*Symtab);
3684   if (!Name.empty())
3685     OS << "\nSymbol table '" << Name << "'";
3686   else
3687     OS << "\nSymbol table for image";
3688   OS << " contains " << Entries << " entries:\n";
3689 
3690   if (ELFT::Is64Bits)
3691     OS << "   Num:    Value          Size Type    Bind   Vis";
3692   else
3693     OS << "   Num:    Value  Size Type    Bind   Vis";
3694 
3695   if (NonVisibilityBitsUsed)
3696     OS << "             ";
3697   OS << "       Ndx Name\n";
3698 }
3699 
3700 template <class ELFT>
3701 std::string
3702 GNUELFDumper<ELFT>::getSymbolSectionNdx(const Elf_Sym &Symbol,
3703                                         unsigned SymIndex,
3704                                         DataRegion<Elf_Word> ShndxTable) const {
3705   unsigned SectionIndex = Symbol.st_shndx;
3706   switch (SectionIndex) {
3707   case ELF::SHN_UNDEF:
3708     return "UND";
3709   case ELF::SHN_ABS:
3710     return "ABS";
3711   case ELF::SHN_COMMON:
3712     return "COM";
3713   case ELF::SHN_XINDEX: {
3714     Expected<uint32_t> IndexOrErr =
3715         object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, ShndxTable);
3716     if (!IndexOrErr) {
3717       assert(Symbol.st_shndx == SHN_XINDEX &&
3718              "getExtendedSymbolTableIndex should only fail due to an invalid "
3719              "SHT_SYMTAB_SHNDX table/reference");
3720       this->reportUniqueWarning(IndexOrErr.takeError());
3721       return "RSV[0xffff]";
3722     }
3723     return to_string(format_decimal(*IndexOrErr, 3));
3724   }
3725   default:
3726     // Find if:
3727     // Processor specific
3728     if (SectionIndex >= ELF::SHN_LOPROC && SectionIndex <= ELF::SHN_HIPROC)
3729       return std::string("PRC[0x") +
3730              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3731     // OS specific
3732     if (SectionIndex >= ELF::SHN_LOOS && SectionIndex <= ELF::SHN_HIOS)
3733       return std::string("OS[0x") +
3734              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3735     // Architecture reserved:
3736     if (SectionIndex >= ELF::SHN_LORESERVE &&
3737         SectionIndex <= ELF::SHN_HIRESERVE)
3738       return std::string("RSV[0x") +
3739              to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
3740     // A normal section with an index
3741     return to_string(format_decimal(SectionIndex, 3));
3742   }
3743 }
3744 
3745 template <class ELFT>
3746 void GNUELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
3747                                      DataRegion<Elf_Word> ShndxTable,
3748                                      Optional<StringRef> StrTable,
3749                                      bool IsDynamic,
3750                                      bool NonVisibilityBitsUsed) const {
3751   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3752   Field Fields[8] = {0,         8,         17 + Bias, 23 + Bias,
3753                      31 + Bias, 38 + Bias, 48 + Bias, 51 + Bias};
3754   Fields[0].Str = to_string(format_decimal(SymIndex, 6)) + ":";
3755   Fields[1].Str =
3756       to_string(format_hex_no_prefix(Symbol.st_value, ELFT::Is64Bits ? 16 : 8));
3757   Fields[2].Str = to_string(format_decimal(Symbol.st_size, 5));
3758 
3759   unsigned char SymbolType = Symbol.getType();
3760   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
3761       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
3762     Fields[3].Str = printEnum(SymbolType, makeArrayRef(AMDGPUSymbolTypes));
3763   else
3764     Fields[3].Str = printEnum(SymbolType, makeArrayRef(ElfSymbolTypes));
3765 
3766   Fields[4].Str =
3767       printEnum(Symbol.getBinding(), makeArrayRef(ElfSymbolBindings));
3768   Fields[5].Str =
3769       printEnum(Symbol.getVisibility(), makeArrayRef(ElfSymbolVisibilities));
3770 
3771   if (Symbol.st_other & ~0x3) {
3772     if (this->Obj.getHeader().e_machine == ELF::EM_AARCH64) {
3773       uint8_t Other = Symbol.st_other & ~0x3;
3774       if (Other & STO_AARCH64_VARIANT_PCS) {
3775         Other &= ~STO_AARCH64_VARIANT_PCS;
3776         Fields[5].Str += " [VARIANT_PCS";
3777         if (Other != 0)
3778           Fields[5].Str.append(" | " + to_hexString(Other, false));
3779         Fields[5].Str.append("]");
3780       }
3781     } else if (this->Obj.getHeader().e_machine == ELF::EM_RISCV) {
3782       uint8_t Other = Symbol.st_other & ~0x3;
3783       if (Other & STO_RISCV_VARIANT_CC) {
3784         Other &= ~STO_RISCV_VARIANT_CC;
3785         Fields[5].Str += " [VARIANT_CC";
3786         if (Other != 0)
3787           Fields[5].Str.append(" | " + to_hexString(Other, false));
3788         Fields[5].Str.append("]");
3789       }
3790     } else {
3791       Fields[5].Str +=
3792           " [<other: " + to_string(format_hex(Symbol.st_other, 2)) + ">]";
3793     }
3794   }
3795 
3796   Fields[6].Column += NonVisibilityBitsUsed ? 13 : 0;
3797   Fields[6].Str = getSymbolSectionNdx(Symbol, SymIndex, ShndxTable);
3798 
3799   Fields[7].Str = this->getFullSymbolName(Symbol, SymIndex, ShndxTable,
3800                                           StrTable, IsDynamic);
3801   for (const Field &Entry : Fields)
3802     printField(Entry);
3803   OS << "\n";
3804 }
3805 
3806 template <class ELFT>
3807 void GNUELFDumper<ELFT>::printHashedSymbol(const Elf_Sym *Symbol,
3808                                            unsigned SymIndex,
3809                                            DataRegion<Elf_Word> ShndxTable,
3810                                            StringRef StrTable,
3811                                            uint32_t Bucket) {
3812   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3813   Field Fields[9] = {0,         6,         11,        20 + Bias, 25 + Bias,
3814                      34 + Bias, 41 + Bias, 49 + Bias, 53 + Bias};
3815   Fields[0].Str = to_string(format_decimal(SymIndex, 5));
3816   Fields[1].Str = to_string(format_decimal(Bucket, 3)) + ":";
3817 
3818   Fields[2].Str = to_string(
3819       format_hex_no_prefix(Symbol->st_value, ELFT::Is64Bits ? 16 : 8));
3820   Fields[3].Str = to_string(format_decimal(Symbol->st_size, 5));
3821 
3822   unsigned char SymbolType = Symbol->getType();
3823   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
3824       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
3825     Fields[4].Str = printEnum(SymbolType, makeArrayRef(AMDGPUSymbolTypes));
3826   else
3827     Fields[4].Str = printEnum(SymbolType, makeArrayRef(ElfSymbolTypes));
3828 
3829   Fields[5].Str =
3830       printEnum(Symbol->getBinding(), makeArrayRef(ElfSymbolBindings));
3831   Fields[6].Str =
3832       printEnum(Symbol->getVisibility(), makeArrayRef(ElfSymbolVisibilities));
3833   Fields[7].Str = getSymbolSectionNdx(*Symbol, SymIndex, ShndxTable);
3834   Fields[8].Str =
3835       this->getFullSymbolName(*Symbol, SymIndex, ShndxTable, StrTable, true);
3836 
3837   for (const Field &Entry : Fields)
3838     printField(Entry);
3839   OS << "\n";
3840 }
3841 
3842 template <class ELFT>
3843 void GNUELFDumper<ELFT>::printSymbols(bool PrintSymbols,
3844                                       bool PrintDynamicSymbols) {
3845   if (!PrintSymbols && !PrintDynamicSymbols)
3846     return;
3847   // GNU readelf prints both the .dynsym and .symtab with --symbols.
3848   this->printSymbolsHelper(true);
3849   if (PrintSymbols)
3850     this->printSymbolsHelper(false);
3851 }
3852 
3853 template <class ELFT>
3854 void GNUELFDumper<ELFT>::printHashTableSymbols(const Elf_Hash &SysVHash) {
3855   if (this->DynamicStringTable.empty())
3856     return;
3857 
3858   if (ELFT::Is64Bits)
3859     OS << "  Num Buc:    Value          Size   Type   Bind Vis      Ndx Name";
3860   else
3861     OS << "  Num Buc:    Value  Size   Type   Bind Vis      Ndx Name";
3862   OS << "\n";
3863 
3864   Elf_Sym_Range DynSyms = this->dynamic_symbols();
3865   const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
3866   if (!FirstSym) {
3867     this->reportUniqueWarning(
3868         Twine("unable to print symbols for the .hash table: the "
3869               "dynamic symbol table ") +
3870         (this->DynSymRegion ? "is empty" : "was not found"));
3871     return;
3872   }
3873 
3874   DataRegion<Elf_Word> ShndxTable(
3875       (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
3876   auto Buckets = SysVHash.buckets();
3877   auto Chains = SysVHash.chains();
3878   for (uint32_t Buc = 0; Buc < SysVHash.nbucket; Buc++) {
3879     if (Buckets[Buc] == ELF::STN_UNDEF)
3880       continue;
3881     std::vector<bool> Visited(SysVHash.nchain);
3882     for (uint32_t Ch = Buckets[Buc]; Ch < SysVHash.nchain; Ch = Chains[Ch]) {
3883       if (Ch == ELF::STN_UNDEF)
3884         break;
3885 
3886       if (Visited[Ch]) {
3887         this->reportUniqueWarning(".hash section is invalid: bucket " +
3888                                   Twine(Ch) +
3889                                   ": a cycle was detected in the linked chain");
3890         break;
3891       }
3892 
3893       printHashedSymbol(FirstSym + Ch, Ch, ShndxTable, this->DynamicStringTable,
3894                         Buc);
3895       Visited[Ch] = true;
3896     }
3897   }
3898 }
3899 
3900 template <class ELFT>
3901 void GNUELFDumper<ELFT>::printGnuHashTableSymbols(const Elf_GnuHash &GnuHash) {
3902   if (this->DynamicStringTable.empty())
3903     return;
3904 
3905   Elf_Sym_Range DynSyms = this->dynamic_symbols();
3906   const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
3907   if (!FirstSym) {
3908     this->reportUniqueWarning(
3909         Twine("unable to print symbols for the .gnu.hash table: the "
3910               "dynamic symbol table ") +
3911         (this->DynSymRegion ? "is empty" : "was not found"));
3912     return;
3913   }
3914 
3915   auto GetSymbol = [&](uint64_t SymIndex,
3916                        uint64_t SymsTotal) -> const Elf_Sym * {
3917     if (SymIndex >= SymsTotal) {
3918       this->reportUniqueWarning(
3919           "unable to print hashed symbol with index " + Twine(SymIndex) +
3920           ", which is greater than or equal to the number of dynamic symbols "
3921           "(" +
3922           Twine::utohexstr(SymsTotal) + ")");
3923       return nullptr;
3924     }
3925     return FirstSym + SymIndex;
3926   };
3927 
3928   Expected<ArrayRef<Elf_Word>> ValuesOrErr =
3929       getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHash);
3930   ArrayRef<Elf_Word> Values;
3931   if (!ValuesOrErr)
3932     this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH "
3933                               "section: " +
3934                               toString(ValuesOrErr.takeError()));
3935   else
3936     Values = *ValuesOrErr;
3937 
3938   DataRegion<Elf_Word> ShndxTable(
3939       (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
3940   ArrayRef<Elf_Word> Buckets = GnuHash.buckets();
3941   for (uint32_t Buc = 0; Buc < GnuHash.nbuckets; Buc++) {
3942     if (Buckets[Buc] == ELF::STN_UNDEF)
3943       continue;
3944     uint32_t Index = Buckets[Buc];
3945     // Print whole chain.
3946     while (true) {
3947       uint32_t SymIndex = Index++;
3948       if (const Elf_Sym *Sym = GetSymbol(SymIndex, DynSyms.size()))
3949         printHashedSymbol(Sym, SymIndex, ShndxTable, this->DynamicStringTable,
3950                           Buc);
3951       else
3952         break;
3953 
3954       if (SymIndex < GnuHash.symndx) {
3955         this->reportUniqueWarning(
3956             "unable to read the hash value for symbol with index " +
3957             Twine(SymIndex) +
3958             ", which is less than the index of the first hashed symbol (" +
3959             Twine(GnuHash.symndx) + ")");
3960         break;
3961       }
3962 
3963        // Chain ends at symbol with stopper bit.
3964       if ((Values[SymIndex - GnuHash.symndx] & 1) == 1)
3965         break;
3966     }
3967   }
3968 }
3969 
3970 template <class ELFT> void GNUELFDumper<ELFT>::printHashSymbols() {
3971   if (this->HashTable) {
3972     OS << "\n Symbol table of .hash for image:\n";
3973     if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
3974       this->reportUniqueWarning(std::move(E));
3975     else
3976       printHashTableSymbols(*this->HashTable);
3977   }
3978 
3979   // Try printing the .gnu.hash table.
3980   if (this->GnuHashTable) {
3981     OS << "\n Symbol table of .gnu.hash for image:\n";
3982     if (ELFT::Is64Bits)
3983       OS << "  Num Buc:    Value          Size   Type   Bind Vis      Ndx Name";
3984     else
3985       OS << "  Num Buc:    Value  Size   Type   Bind Vis      Ndx Name";
3986     OS << "\n";
3987 
3988     if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
3989       this->reportUniqueWarning(std::move(E));
3990     else
3991       printGnuHashTableSymbols(*this->GnuHashTable);
3992   }
3993 }
3994 
3995 template <class ELFT> void GNUELFDumper<ELFT>::printSectionDetails() {
3996   ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
3997   OS << "There are " << to_string(Sections.size())
3998      << " section headers, starting at offset "
3999      << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n";
4000 
4001   OS << "Section Headers:\n";
4002 
4003   auto PrintFields = [&](ArrayRef<Field> V) {
4004     for (const Field &F : V)
4005       printField(F);
4006     OS << "\n";
4007   };
4008 
4009   PrintFields({{"[Nr]", 2}, {"Name", 7}});
4010 
4011   constexpr bool Is64 = ELFT::Is64Bits;
4012   PrintFields({{"Type", 7},
4013                {Is64 ? "Address" : "Addr", 23},
4014                {"Off", Is64 ? 40 : 32},
4015                {"Size", Is64 ? 47 : 39},
4016                {"ES", Is64 ? 54 : 46},
4017                {"Lk", Is64 ? 59 : 51},
4018                {"Inf", Is64 ? 62 : 54},
4019                {"Al", Is64 ? 66 : 57}});
4020   PrintFields({{"Flags", 7}});
4021 
4022   StringRef SecStrTable;
4023   if (Expected<StringRef> SecStrTableOrErr =
4024           this->Obj.getSectionStringTable(Sections, this->WarningHandler))
4025     SecStrTable = *SecStrTableOrErr;
4026   else
4027     this->reportUniqueWarning(SecStrTableOrErr.takeError());
4028 
4029   size_t SectionIndex = 0;
4030   const unsigned AddrSize = Is64 ? 16 : 8;
4031   for (const Elf_Shdr &S : Sections) {
4032     StringRef Name = "<?>";
4033     if (Expected<StringRef> NameOrErr =
4034             this->Obj.getSectionName(S, SecStrTable))
4035       Name = *NameOrErr;
4036     else
4037       this->reportUniqueWarning(NameOrErr.takeError());
4038 
4039     OS.PadToColumn(2);
4040     OS << "[" << right_justify(to_string(SectionIndex), 2) << "]";
4041     PrintFields({{Name, 7}});
4042     PrintFields(
4043         {{getSectionTypeString(this->Obj.getHeader().e_machine, S.sh_type), 7},
4044          {to_string(format_hex_no_prefix(S.sh_addr, AddrSize)), 23},
4045          {to_string(format_hex_no_prefix(S.sh_offset, 6)), Is64 ? 39 : 32},
4046          {to_string(format_hex_no_prefix(S.sh_size, 6)), Is64 ? 47 : 39},
4047          {to_string(format_hex_no_prefix(S.sh_entsize, 2)), Is64 ? 54 : 46},
4048          {to_string(S.sh_link), Is64 ? 59 : 51},
4049          {to_string(S.sh_info), Is64 ? 63 : 55},
4050          {to_string(S.sh_addralign), Is64 ? 66 : 58}});
4051 
4052     OS.PadToColumn(7);
4053     OS << "[" << to_string(format_hex_no_prefix(S.sh_flags, AddrSize)) << "]: ";
4054 
4055     DenseMap<unsigned, StringRef> FlagToName = {
4056         {SHF_WRITE, "WRITE"},           {SHF_ALLOC, "ALLOC"},
4057         {SHF_EXECINSTR, "EXEC"},        {SHF_MERGE, "MERGE"},
4058         {SHF_STRINGS, "STRINGS"},       {SHF_INFO_LINK, "INFO LINK"},
4059         {SHF_LINK_ORDER, "LINK ORDER"}, {SHF_OS_NONCONFORMING, "OS NONCONF"},
4060         {SHF_GROUP, "GROUP"},           {SHF_TLS, "TLS"},
4061         {SHF_COMPRESSED, "COMPRESSED"}, {SHF_EXCLUDE, "EXCLUDE"}};
4062 
4063     uint64_t Flags = S.sh_flags;
4064     uint64_t UnknownFlags = 0;
4065     ListSeparator LS;
4066     while (Flags) {
4067       // Take the least significant bit as a flag.
4068       uint64_t Flag = Flags & -Flags;
4069       Flags -= Flag;
4070 
4071       auto It = FlagToName.find(Flag);
4072       if (It != FlagToName.end())
4073         OS << LS << It->second;
4074       else
4075         UnknownFlags |= Flag;
4076     }
4077 
4078     auto PrintUnknownFlags = [&](uint64_t Mask, StringRef Name) {
4079       uint64_t FlagsToPrint = UnknownFlags & Mask;
4080       if (!FlagsToPrint)
4081         return;
4082 
4083       OS << LS << Name << " ("
4084          << to_string(format_hex_no_prefix(FlagsToPrint, AddrSize)) << ")";
4085       UnknownFlags &= ~Mask;
4086     };
4087 
4088     PrintUnknownFlags(SHF_MASKOS, "OS");
4089     PrintUnknownFlags(SHF_MASKPROC, "PROC");
4090     PrintUnknownFlags(uint64_t(-1), "UNKNOWN");
4091 
4092     OS << "\n";
4093     ++SectionIndex;
4094   }
4095 }
4096 
4097 static inline std::string printPhdrFlags(unsigned Flag) {
4098   std::string Str;
4099   Str = (Flag & PF_R) ? "R" : " ";
4100   Str += (Flag & PF_W) ? "W" : " ";
4101   Str += (Flag & PF_X) ? "E" : " ";
4102   return Str;
4103 }
4104 
4105 template <class ELFT>
4106 static bool checkTLSSections(const typename ELFT::Phdr &Phdr,
4107                              const typename ELFT::Shdr &Sec) {
4108   if (Sec.sh_flags & ELF::SHF_TLS) {
4109     // .tbss must only be shown in the PT_TLS segment.
4110     if (Sec.sh_type == ELF::SHT_NOBITS)
4111       return Phdr.p_type == ELF::PT_TLS;
4112 
4113     // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO
4114     // segments.
4115     return (Phdr.p_type == ELF::PT_TLS) || (Phdr.p_type == ELF::PT_LOAD) ||
4116            (Phdr.p_type == ELF::PT_GNU_RELRO);
4117   }
4118 
4119   // PT_TLS must only have SHF_TLS sections.
4120   return Phdr.p_type != ELF::PT_TLS;
4121 }
4122 
4123 template <class ELFT>
4124 static bool checkOffsets(const typename ELFT::Phdr &Phdr,
4125                          const typename ELFT::Shdr &Sec) {
4126   // SHT_NOBITS sections don't need to have an offset inside the segment.
4127   if (Sec.sh_type == ELF::SHT_NOBITS)
4128     return true;
4129 
4130   if (Sec.sh_offset < Phdr.p_offset)
4131     return false;
4132 
4133   // Only non-empty sections can be at the end of a segment.
4134   if (Sec.sh_size == 0)
4135     return (Sec.sh_offset + 1 <= Phdr.p_offset + Phdr.p_filesz);
4136   return Sec.sh_offset + Sec.sh_size <= Phdr.p_offset + Phdr.p_filesz;
4137 }
4138 
4139 // Check that an allocatable section belongs to a virtual address
4140 // space of a segment.
4141 template <class ELFT>
4142 static bool checkVMA(const typename ELFT::Phdr &Phdr,
4143                      const typename ELFT::Shdr &Sec) {
4144   if (!(Sec.sh_flags & ELF::SHF_ALLOC))
4145     return true;
4146 
4147   if (Sec.sh_addr < Phdr.p_vaddr)
4148     return false;
4149 
4150   bool IsTbss =
4151       (Sec.sh_type == ELF::SHT_NOBITS) && ((Sec.sh_flags & ELF::SHF_TLS) != 0);
4152   // .tbss is special, it only has memory in PT_TLS and has NOBITS properties.
4153   bool IsTbssInNonTLS = IsTbss && Phdr.p_type != ELF::PT_TLS;
4154   // Only non-empty sections can be at the end of a segment.
4155   if (Sec.sh_size == 0 || IsTbssInNonTLS)
4156     return Sec.sh_addr + 1 <= Phdr.p_vaddr + Phdr.p_memsz;
4157   return Sec.sh_addr + Sec.sh_size <= Phdr.p_vaddr + Phdr.p_memsz;
4158 }
4159 
4160 template <class ELFT>
4161 static bool checkPTDynamic(const typename ELFT::Phdr &Phdr,
4162                            const typename ELFT::Shdr &Sec) {
4163   if (Phdr.p_type != ELF::PT_DYNAMIC || Phdr.p_memsz == 0 || Sec.sh_size != 0)
4164     return true;
4165 
4166   // We get here when we have an empty section. Only non-empty sections can be
4167   // at the start or at the end of PT_DYNAMIC.
4168   // Is section within the phdr both based on offset and VMA?
4169   bool CheckOffset = (Sec.sh_type == ELF::SHT_NOBITS) ||
4170                      (Sec.sh_offset > Phdr.p_offset &&
4171                       Sec.sh_offset < Phdr.p_offset + Phdr.p_filesz);
4172   bool CheckVA = !(Sec.sh_flags & ELF::SHF_ALLOC) ||
4173                  (Sec.sh_addr > Phdr.p_vaddr && Sec.sh_addr < Phdr.p_memsz);
4174   return CheckOffset && CheckVA;
4175 }
4176 
4177 template <class ELFT>
4178 void GNUELFDumper<ELFT>::printProgramHeaders(
4179     bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
4180   if (PrintProgramHeaders)
4181     printProgramHeaders();
4182 
4183   // Display the section mapping along with the program headers, unless
4184   // -section-mapping is explicitly set to false.
4185   if (PrintSectionMapping != cl::BOU_FALSE)
4186     printSectionMapping();
4187 }
4188 
4189 template <class ELFT> void GNUELFDumper<ELFT>::printProgramHeaders() {
4190   unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4191   const Elf_Ehdr &Header = this->Obj.getHeader();
4192   Field Fields[8] = {2,         17,        26,        37 + Bias,
4193                      48 + Bias, 56 + Bias, 64 + Bias, 68 + Bias};
4194   OS << "\nElf file type is "
4195      << printEnum(Header.e_type, makeArrayRef(ElfObjectFileType)) << "\n"
4196      << "Entry point " << format_hex(Header.e_entry, 3) << "\n"
4197      << "There are " << Header.e_phnum << " program headers,"
4198      << " starting at offset " << Header.e_phoff << "\n\n"
4199      << "Program Headers:\n";
4200   if (ELFT::Is64Bits)
4201     OS << "  Type           Offset   VirtAddr           PhysAddr         "
4202        << "  FileSiz  MemSiz   Flg Align\n";
4203   else
4204     OS << "  Type           Offset   VirtAddr   PhysAddr   FileSiz "
4205        << "MemSiz  Flg Align\n";
4206 
4207   unsigned Width = ELFT::Is64Bits ? 18 : 10;
4208   unsigned SizeWidth = ELFT::Is64Bits ? 8 : 7;
4209 
4210   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4211   if (!PhdrsOrErr) {
4212     this->reportUniqueWarning("unable to dump program headers: " +
4213                               toString(PhdrsOrErr.takeError()));
4214     return;
4215   }
4216 
4217   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4218     Fields[0].Str = getGNUPtType(Header.e_machine, Phdr.p_type);
4219     Fields[1].Str = to_string(format_hex(Phdr.p_offset, 8));
4220     Fields[2].Str = to_string(format_hex(Phdr.p_vaddr, Width));
4221     Fields[3].Str = to_string(format_hex(Phdr.p_paddr, Width));
4222     Fields[4].Str = to_string(format_hex(Phdr.p_filesz, SizeWidth));
4223     Fields[5].Str = to_string(format_hex(Phdr.p_memsz, SizeWidth));
4224     Fields[6].Str = printPhdrFlags(Phdr.p_flags);
4225     Fields[7].Str = to_string(format_hex(Phdr.p_align, 1));
4226     for (const Field &F : Fields)
4227       printField(F);
4228     if (Phdr.p_type == ELF::PT_INTERP) {
4229       OS << "\n";
4230       auto ReportBadInterp = [&](const Twine &Msg) {
4231         this->reportUniqueWarning(
4232             "unable to read program interpreter name at offset 0x" +
4233             Twine::utohexstr(Phdr.p_offset) + ": " + Msg);
4234       };
4235 
4236       if (Phdr.p_offset >= this->Obj.getBufSize()) {
4237         ReportBadInterp("it goes past the end of the file (0x" +
4238                         Twine::utohexstr(this->Obj.getBufSize()) + ")");
4239         continue;
4240       }
4241 
4242       const char *Data =
4243           reinterpret_cast<const char *>(this->Obj.base()) + Phdr.p_offset;
4244       size_t MaxSize = this->Obj.getBufSize() - Phdr.p_offset;
4245       size_t Len = strnlen(Data, MaxSize);
4246       if (Len == MaxSize) {
4247         ReportBadInterp("it is not null-terminated");
4248         continue;
4249       }
4250 
4251       OS << "      [Requesting program interpreter: ";
4252       OS << StringRef(Data, Len) << "]";
4253     }
4254     OS << "\n";
4255   }
4256 }
4257 
4258 template <class ELFT> void GNUELFDumper<ELFT>::printSectionMapping() {
4259   OS << "\n Section to Segment mapping:\n  Segment Sections...\n";
4260   DenseSet<const Elf_Shdr *> BelongsToSegment;
4261   int Phnum = 0;
4262 
4263   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4264   if (!PhdrsOrErr) {
4265     this->reportUniqueWarning(
4266         "can't read program headers to build section to segment mapping: " +
4267         toString(PhdrsOrErr.takeError()));
4268     return;
4269   }
4270 
4271   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4272     std::string Sections;
4273     OS << format("   %2.2d     ", Phnum++);
4274     // Check if each section is in a segment and then print mapping.
4275     for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4276       if (Sec.sh_type == ELF::SHT_NULL)
4277         continue;
4278 
4279       // readelf additionally makes sure it does not print zero sized sections
4280       // at end of segments and for PT_DYNAMIC both start and end of section
4281       // .tbss must only be shown in PT_TLS section.
4282       if (checkTLSSections<ELFT>(Phdr, Sec) && checkOffsets<ELFT>(Phdr, Sec) &&
4283           checkVMA<ELFT>(Phdr, Sec) && checkPTDynamic<ELFT>(Phdr, Sec)) {
4284         Sections +=
4285             unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4286             " ";
4287         BelongsToSegment.insert(&Sec);
4288       }
4289     }
4290     OS << Sections << "\n";
4291     OS.flush();
4292   }
4293 
4294   // Display sections that do not belong to a segment.
4295   std::string Sections;
4296   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4297     if (BelongsToSegment.find(&Sec) == BelongsToSegment.end())
4298       Sections +=
4299           unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4300           ' ';
4301   }
4302   if (!Sections.empty()) {
4303     OS << "   None  " << Sections << '\n';
4304     OS.flush();
4305   }
4306 }
4307 
4308 namespace {
4309 
4310 template <class ELFT>
4311 RelSymbol<ELFT> getSymbolForReloc(const ELFDumper<ELFT> &Dumper,
4312                                   const Relocation<ELFT> &Reloc) {
4313   using Elf_Sym = typename ELFT::Sym;
4314   auto WarnAndReturn = [&](const Elf_Sym *Sym,
4315                            const Twine &Reason) -> RelSymbol<ELFT> {
4316     Dumper.reportUniqueWarning(
4317         "unable to get name of the dynamic symbol with index " +
4318         Twine(Reloc.Symbol) + ": " + Reason);
4319     return {Sym, "<corrupt>"};
4320   };
4321 
4322   ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols();
4323   const Elf_Sym *FirstSym = Symbols.begin();
4324   if (!FirstSym)
4325     return WarnAndReturn(nullptr, "no dynamic symbol table found");
4326 
4327   // We might have an object without a section header. In this case the size of
4328   // Symbols is zero, because there is no way to know the size of the dynamic
4329   // table. We should allow this case and not print a warning.
4330   if (!Symbols.empty() && Reloc.Symbol >= Symbols.size())
4331     return WarnAndReturn(
4332         nullptr,
4333         "index is greater than or equal to the number of dynamic symbols (" +
4334             Twine(Symbols.size()) + ")");
4335 
4336   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
4337   const uint64_t FileSize = Obj.getBufSize();
4338   const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) +
4339                              (uint64_t)Reloc.Symbol * sizeof(Elf_Sym);
4340   if (SymOffset + sizeof(Elf_Sym) > FileSize)
4341     return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(SymOffset) +
4342                                       " goes past the end of the file (0x" +
4343                                       Twine::utohexstr(FileSize) + ")");
4344 
4345   const Elf_Sym *Sym = FirstSym + Reloc.Symbol;
4346   Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable());
4347   if (!ErrOrName)
4348     return WarnAndReturn(Sym, toString(ErrOrName.takeError()));
4349 
4350   return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(*ErrOrName)};
4351 }
4352 } // namespace
4353 
4354 template <class ELFT>
4355 static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj,
4356                                    typename ELFT::DynRange Tags) {
4357   size_t Max = 0;
4358   for (const typename ELFT::Dyn &Dyn : Tags)
4359     Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size());
4360   return Max;
4361 }
4362 
4363 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicTable() {
4364   Elf_Dyn_Range Table = this->dynamic_table();
4365   if (Table.empty())
4366     return;
4367 
4368   OS << "Dynamic section at offset "
4369      << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable.Addr) -
4370                        this->Obj.base(),
4371                    1)
4372      << " contains " << Table.size() << " entries:\n";
4373 
4374   // The type name is surrounded with round brackets, hence add 2.
4375   size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2;
4376   // The "Name/Value" column should be indented from the "Type" column by N
4377   // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
4378   // space (1) = 3.
4379   OS << "  Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type"
4380      << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
4381 
4382   std::string ValueFmt = " %-" + std::to_string(MaxTagSize) + "s ";
4383   for (auto Entry : Table) {
4384     uintX_t Tag = Entry.getTag();
4385     std::string Type =
4386         std::string("(") + this->Obj.getDynamicTagAsString(Tag) + ")";
4387     std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
4388     OS << "  " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10)
4389        << format(ValueFmt.c_str(), Type.c_str()) << Value << "\n";
4390   }
4391 }
4392 
4393 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicRelocations() {
4394   this->printDynamicRelocationsHelper();
4395 }
4396 
4397 template <class ELFT>
4398 void ELFDumper<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) {
4399   printRelRelaReloc(R, getSymbolForReloc(*this, R));
4400 }
4401 
4402 template <class ELFT>
4403 void ELFDumper<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) {
4404   this->forEachRelocationDo(
4405       Sec, opts::RawRelr,
4406       [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
4407           const Elf_Shdr *SymTab) { printReloc(R, Ndx, Sec, SymTab); },
4408       [&](const Elf_Relr &R) { printRelrReloc(R); });
4409 }
4410 
4411 template <class ELFT> void ELFDumper<ELFT>::printDynamicRelocationsHelper() {
4412   const bool IsMips64EL = this->Obj.isMips64EL();
4413   if (this->DynRelaRegion.Size > 0) {
4414     printDynamicRelocHeader(ELF::SHT_RELA, "RELA", this->DynRelaRegion);
4415     for (const Elf_Rela &Rela :
4416          this->DynRelaRegion.template getAsArrayRef<Elf_Rela>())
4417       printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
4418   }
4419 
4420   if (this->DynRelRegion.Size > 0) {
4421     printDynamicRelocHeader(ELF::SHT_REL, "REL", this->DynRelRegion);
4422     for (const Elf_Rel &Rel :
4423          this->DynRelRegion.template getAsArrayRef<Elf_Rel>())
4424       printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4425   }
4426 
4427   if (this->DynRelrRegion.Size > 0) {
4428     printDynamicRelocHeader(ELF::SHT_REL, "RELR", this->DynRelrRegion);
4429     Elf_Relr_Range Relrs =
4430         this->DynRelrRegion.template getAsArrayRef<Elf_Relr>();
4431     for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs))
4432       printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4433   }
4434 
4435   if (this->DynPLTRelRegion.Size) {
4436     if (this->DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) {
4437       printDynamicRelocHeader(ELF::SHT_RELA, "PLT", this->DynPLTRelRegion);
4438       for (const Elf_Rela &Rela :
4439            this->DynPLTRelRegion.template getAsArrayRef<Elf_Rela>())
4440         printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
4441     } else {
4442       printDynamicRelocHeader(ELF::SHT_REL, "PLT", this->DynPLTRelRegion);
4443       for (const Elf_Rel &Rel :
4444            this->DynPLTRelRegion.template getAsArrayRef<Elf_Rel>())
4445         printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4446     }
4447   }
4448 }
4449 
4450 template <class ELFT>
4451 void GNUELFDumper<ELFT>::printGNUVersionSectionProlog(
4452     const typename ELFT::Shdr &Sec, const Twine &Label, unsigned EntriesNum) {
4453   // Don't inline the SecName, because it might report a warning to stderr and
4454   // corrupt the output.
4455   StringRef SecName = this->getPrintableSectionName(Sec);
4456   OS << Label << " section '" << SecName << "' "
4457      << "contains " << EntriesNum << " entries:\n";
4458 
4459   StringRef LinkedSecName = "<corrupt>";
4460   if (Expected<const typename ELFT::Shdr *> LinkedSecOrErr =
4461           this->Obj.getSection(Sec.sh_link))
4462     LinkedSecName = this->getPrintableSectionName(**LinkedSecOrErr);
4463   else
4464     this->reportUniqueWarning("invalid section linked to " +
4465                               this->describe(Sec) + ": " +
4466                               toString(LinkedSecOrErr.takeError()));
4467 
4468   OS << " Addr: " << format_hex_no_prefix(Sec.sh_addr, 16)
4469      << "  Offset: " << format_hex(Sec.sh_offset, 8)
4470      << "  Link: " << Sec.sh_link << " (" << LinkedSecName << ")\n";
4471 }
4472 
4473 template <class ELFT>
4474 void GNUELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
4475   if (!Sec)
4476     return;
4477 
4478   printGNUVersionSectionProlog(*Sec, "Version symbols",
4479                                Sec->sh_size / sizeof(Elf_Versym));
4480   Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
4481       this->getVersionTable(*Sec, /*SymTab=*/nullptr,
4482                             /*StrTab=*/nullptr, /*SymTabSec=*/nullptr);
4483   if (!VerTableOrErr) {
4484     this->reportUniqueWarning(VerTableOrErr.takeError());
4485     return;
4486   }
4487 
4488   SmallVector<Optional<VersionEntry>, 0> *VersionMap = nullptr;
4489   if (Expected<SmallVector<Optional<VersionEntry>, 0> *> MapOrErr =
4490           this->getVersionMap())
4491     VersionMap = *MapOrErr;
4492   else
4493     this->reportUniqueWarning(MapOrErr.takeError());
4494 
4495   ArrayRef<Elf_Versym> VerTable = *VerTableOrErr;
4496   std::vector<StringRef> Versions;
4497   for (size_t I = 0, E = VerTable.size(); I < E; ++I) {
4498     unsigned Ndx = VerTable[I].vs_index;
4499     if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) {
4500       Versions.emplace_back(Ndx == VER_NDX_LOCAL ? "*local*" : "*global*");
4501       continue;
4502     }
4503 
4504     if (!VersionMap) {
4505       Versions.emplace_back("<corrupt>");
4506       continue;
4507     }
4508 
4509     bool IsDefault;
4510     Expected<StringRef> NameOrErr = this->Obj.getSymbolVersionByIndex(
4511         Ndx, IsDefault, *VersionMap, /*IsSymHidden=*/None);
4512     if (!NameOrErr) {
4513       this->reportUniqueWarning("unable to get a version for entry " +
4514                                 Twine(I) + " of " + this->describe(*Sec) +
4515                                 ": " + toString(NameOrErr.takeError()));
4516       Versions.emplace_back("<corrupt>");
4517       continue;
4518     }
4519     Versions.emplace_back(*NameOrErr);
4520   }
4521 
4522   // readelf prints 4 entries per line.
4523   uint64_t Entries = VerTable.size();
4524   for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) {
4525     OS << "  " << format_hex_no_prefix(VersymRow, 3) << ":";
4526     for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) {
4527       unsigned Ndx = VerTable[VersymRow + I].vs_index;
4528       OS << format("%4x%c", Ndx & VERSYM_VERSION,
4529                    Ndx & VERSYM_HIDDEN ? 'h' : ' ');
4530       OS << left_justify("(" + std::string(Versions[VersymRow + I]) + ")", 13);
4531     }
4532     OS << '\n';
4533   }
4534   OS << '\n';
4535 }
4536 
4537 static std::string versionFlagToString(unsigned Flags) {
4538   if (Flags == 0)
4539     return "none";
4540 
4541   std::string Ret;
4542   auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) {
4543     if (!(Flags & Flag))
4544       return;
4545     if (!Ret.empty())
4546       Ret += " | ";
4547     Ret += Name;
4548     Flags &= ~Flag;
4549   };
4550 
4551   AddFlag(VER_FLG_BASE, "BASE");
4552   AddFlag(VER_FLG_WEAK, "WEAK");
4553   AddFlag(VER_FLG_INFO, "INFO");
4554   AddFlag(~0, "<unknown>");
4555   return Ret;
4556 }
4557 
4558 template <class ELFT>
4559 void GNUELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
4560   if (!Sec)
4561     return;
4562 
4563   printGNUVersionSectionProlog(*Sec, "Version definition", Sec->sh_info);
4564 
4565   Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
4566   if (!V) {
4567     this->reportUniqueWarning(V.takeError());
4568     return;
4569   }
4570 
4571   for (const VerDef &Def : *V) {
4572     OS << format("  0x%04x: Rev: %u  Flags: %s  Index: %u  Cnt: %u  Name: %s\n",
4573                  Def.Offset, Def.Version,
4574                  versionFlagToString(Def.Flags).c_str(), Def.Ndx, Def.Cnt,
4575                  Def.Name.data());
4576     unsigned I = 0;
4577     for (const VerdAux &Aux : Def.AuxV)
4578       OS << format("  0x%04x: Parent %u: %s\n", Aux.Offset, ++I,
4579                    Aux.Name.data());
4580   }
4581 
4582   OS << '\n';
4583 }
4584 
4585 template <class ELFT>
4586 void GNUELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
4587   if (!Sec)
4588     return;
4589 
4590   unsigned VerneedNum = Sec->sh_info;
4591   printGNUVersionSectionProlog(*Sec, "Version needs", VerneedNum);
4592 
4593   Expected<std::vector<VerNeed>> V =
4594       this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
4595   if (!V) {
4596     this->reportUniqueWarning(V.takeError());
4597     return;
4598   }
4599 
4600   for (const VerNeed &VN : *V) {
4601     OS << format("  0x%04x: Version: %u  File: %s  Cnt: %u\n", VN.Offset,
4602                  VN.Version, VN.File.data(), VN.Cnt);
4603     for (const VernAux &Aux : VN.AuxV)
4604       OS << format("  0x%04x:   Name: %s  Flags: %s  Version: %u\n", Aux.Offset,
4605                    Aux.Name.data(), versionFlagToString(Aux.Flags).c_str(),
4606                    Aux.Other);
4607   }
4608   OS << '\n';
4609 }
4610 
4611 template <class ELFT>
4612 void GNUELFDumper<ELFT>::printHashHistogram(const Elf_Hash &HashTable) {
4613   size_t NBucket = HashTable.nbucket;
4614   size_t NChain = HashTable.nchain;
4615   ArrayRef<Elf_Word> Buckets = HashTable.buckets();
4616   ArrayRef<Elf_Word> Chains = HashTable.chains();
4617   size_t TotalSyms = 0;
4618   // If hash table is correct, we have at least chains with 0 length
4619   size_t MaxChain = 1;
4620   size_t CumulativeNonZero = 0;
4621 
4622   if (NChain == 0 || NBucket == 0)
4623     return;
4624 
4625   std::vector<size_t> ChainLen(NBucket, 0);
4626   // Go over all buckets and and note chain lengths of each bucket (total
4627   // unique chain lengths).
4628   for (size_t B = 0; B < NBucket; B++) {
4629     std::vector<bool> Visited(NChain);
4630     for (size_t C = Buckets[B]; C < NChain; C = Chains[C]) {
4631       if (C == ELF::STN_UNDEF)
4632         break;
4633       if (Visited[C]) {
4634         this->reportUniqueWarning(".hash section is invalid: bucket " +
4635                                   Twine(C) +
4636                                   ": a cycle was detected in the linked chain");
4637         break;
4638       }
4639       Visited[C] = true;
4640       if (MaxChain <= ++ChainLen[B])
4641         MaxChain++;
4642     }
4643     TotalSyms += ChainLen[B];
4644   }
4645 
4646   if (!TotalSyms)
4647     return;
4648 
4649   std::vector<size_t> Count(MaxChain, 0);
4650   // Count how long is the chain for each bucket
4651   for (size_t B = 0; B < NBucket; B++)
4652     ++Count[ChainLen[B]];
4653   // Print Number of buckets with each chain lengths and their cumulative
4654   // coverage of the symbols
4655   OS << "Histogram for bucket list length (total of " << NBucket
4656      << " buckets)\n"
4657      << " Length  Number     % of total  Coverage\n";
4658   for (size_t I = 0; I < MaxChain; I++) {
4659     CumulativeNonZero += Count[I] * I;
4660     OS << format("%7lu  %-10lu (%5.1f%%)     %5.1f%%\n", I, Count[I],
4661                  (Count[I] * 100.0) / NBucket,
4662                  (CumulativeNonZero * 100.0) / TotalSyms);
4663   }
4664 }
4665 
4666 template <class ELFT>
4667 void GNUELFDumper<ELFT>::printGnuHashHistogram(
4668     const Elf_GnuHash &GnuHashTable) {
4669   Expected<ArrayRef<Elf_Word>> ChainsOrErr =
4670       getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHashTable);
4671   if (!ChainsOrErr) {
4672     this->reportUniqueWarning("unable to print the GNU hash table histogram: " +
4673                               toString(ChainsOrErr.takeError()));
4674     return;
4675   }
4676 
4677   ArrayRef<Elf_Word> Chains = *ChainsOrErr;
4678   size_t Symndx = GnuHashTable.symndx;
4679   size_t TotalSyms = 0;
4680   size_t MaxChain = 1;
4681   size_t CumulativeNonZero = 0;
4682 
4683   size_t NBucket = GnuHashTable.nbuckets;
4684   if (Chains.empty() || NBucket == 0)
4685     return;
4686 
4687   ArrayRef<Elf_Word> Buckets = GnuHashTable.buckets();
4688   std::vector<size_t> ChainLen(NBucket, 0);
4689   for (size_t B = 0; B < NBucket; B++) {
4690     if (!Buckets[B])
4691       continue;
4692     size_t Len = 1;
4693     for (size_t C = Buckets[B] - Symndx;
4694          C < Chains.size() && (Chains[C] & 1) == 0; C++)
4695       if (MaxChain < ++Len)
4696         MaxChain++;
4697     ChainLen[B] = Len;
4698     TotalSyms += Len;
4699   }
4700   MaxChain++;
4701 
4702   if (!TotalSyms)
4703     return;
4704 
4705   std::vector<size_t> Count(MaxChain, 0);
4706   for (size_t B = 0; B < NBucket; B++)
4707     ++Count[ChainLen[B]];
4708   // Print Number of buckets with each chain lengths and their cumulative
4709   // coverage of the symbols
4710   OS << "Histogram for `.gnu.hash' bucket list length (total of " << NBucket
4711      << " buckets)\n"
4712      << " Length  Number     % of total  Coverage\n";
4713   for (size_t I = 0; I < MaxChain; I++) {
4714     CumulativeNonZero += Count[I] * I;
4715     OS << format("%7lu  %-10lu (%5.1f%%)     %5.1f%%\n", I, Count[I],
4716                  (Count[I] * 100.0) / NBucket,
4717                  (CumulativeNonZero * 100.0) / TotalSyms);
4718   }
4719 }
4720 
4721 // Hash histogram shows statistics of how efficient the hash was for the
4722 // dynamic symbol table. The table shows the number of hash buckets for
4723 // different lengths of chains as an absolute number and percentage of the total
4724 // buckets, and the cumulative coverage of symbols for each set of buckets.
4725 template <class ELFT> void GNUELFDumper<ELFT>::printHashHistograms() {
4726   // Print histogram for the .hash section.
4727   if (this->HashTable) {
4728     if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
4729       this->reportUniqueWarning(std::move(E));
4730     else
4731       printHashHistogram(*this->HashTable);
4732   }
4733 
4734   // Print histogram for the .gnu.hash section.
4735   if (this->GnuHashTable) {
4736     if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
4737       this->reportUniqueWarning(std::move(E));
4738     else
4739       printGnuHashHistogram(*this->GnuHashTable);
4740   }
4741 }
4742 
4743 template <class ELFT> void GNUELFDumper<ELFT>::printCGProfile() {
4744   OS << "GNUStyle::printCGProfile not implemented\n";
4745 }
4746 
4747 template <class ELFT> void GNUELFDumper<ELFT>::printBBAddrMaps() {
4748   OS << "GNUStyle::printBBAddrMaps not implemented\n";
4749 }
4750 
4751 static Expected<std::vector<uint64_t>> toULEB128Array(ArrayRef<uint8_t> Data) {
4752   std::vector<uint64_t> Ret;
4753   const uint8_t *Cur = Data.begin();
4754   const uint8_t *End = Data.end();
4755   while (Cur != End) {
4756     unsigned Size;
4757     const char *Err;
4758     Ret.push_back(decodeULEB128(Cur, &Size, End, &Err));
4759     if (Err)
4760       return createError(Err);
4761     Cur += Size;
4762   }
4763   return Ret;
4764 }
4765 
4766 template <class ELFT>
4767 static Expected<std::vector<uint64_t>>
4768 decodeAddrsigSection(const ELFFile<ELFT> &Obj, const typename ELFT::Shdr &Sec) {
4769   Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Sec);
4770   if (!ContentsOrErr)
4771     return ContentsOrErr.takeError();
4772 
4773   if (Expected<std::vector<uint64_t>> SymsOrErr =
4774           toULEB128Array(*ContentsOrErr))
4775     return *SymsOrErr;
4776   else
4777     return createError("unable to decode " + describe(Obj, Sec) + ": " +
4778                        toString(SymsOrErr.takeError()));
4779 }
4780 
4781 template <class ELFT> void GNUELFDumper<ELFT>::printAddrsig() {
4782   if (!this->DotAddrsigSec)
4783     return;
4784 
4785   Expected<std::vector<uint64_t>> SymsOrErr =
4786       decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
4787   if (!SymsOrErr) {
4788     this->reportUniqueWarning(SymsOrErr.takeError());
4789     return;
4790   }
4791 
4792   StringRef Name = this->getPrintableSectionName(*this->DotAddrsigSec);
4793   OS << "\nAddress-significant symbols section '" << Name << "'"
4794      << " contains " << SymsOrErr->size() << " entries:\n";
4795   OS << "   Num: Name\n";
4796 
4797   Field Fields[2] = {0, 8};
4798   size_t SymIndex = 0;
4799   for (uint64_t Sym : *SymsOrErr) {
4800     Fields[0].Str = to_string(format_decimal(++SymIndex, 6)) + ":";
4801     Fields[1].Str = this->getStaticSymbolName(Sym);
4802     for (const Field &Entry : Fields)
4803       printField(Entry);
4804     OS << "\n";
4805   }
4806 }
4807 
4808 template <typename ELFT>
4809 static std::string getGNUProperty(uint32_t Type, uint32_t DataSize,
4810                                   ArrayRef<uint8_t> Data) {
4811   std::string str;
4812   raw_string_ostream OS(str);
4813   uint32_t PrData;
4814   auto DumpBit = [&](uint32_t Flag, StringRef Name) {
4815     if (PrData & Flag) {
4816       PrData &= ~Flag;
4817       OS << Name;
4818       if (PrData)
4819         OS << ", ";
4820     }
4821   };
4822 
4823   switch (Type) {
4824   default:
4825     OS << format("<application-specific type 0x%x>", Type);
4826     return OS.str();
4827   case GNU_PROPERTY_STACK_SIZE: {
4828     OS << "stack size: ";
4829     if (DataSize == sizeof(typename ELFT::uint))
4830       OS << formatv("{0:x}",
4831                     (uint64_t)(*(const typename ELFT::Addr *)Data.data()));
4832     else
4833       OS << format("<corrupt length: 0x%x>", DataSize);
4834     return OS.str();
4835   }
4836   case GNU_PROPERTY_NO_COPY_ON_PROTECTED:
4837     OS << "no copy on protected";
4838     if (DataSize)
4839       OS << format(" <corrupt length: 0x%x>", DataSize);
4840     return OS.str();
4841   case GNU_PROPERTY_AARCH64_FEATURE_1_AND:
4842   case GNU_PROPERTY_X86_FEATURE_1_AND:
4843     OS << ((Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) ? "aarch64 feature: "
4844                                                         : "x86 feature: ");
4845     if (DataSize != 4) {
4846       OS << format("<corrupt length: 0x%x>", DataSize);
4847       return OS.str();
4848     }
4849     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
4850     if (PrData == 0) {
4851       OS << "<None>";
4852       return OS.str();
4853     }
4854     if (Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) {
4855       DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI, "BTI");
4856       DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC, "PAC");
4857     } else {
4858       DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT, "IBT");
4859       DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK, "SHSTK");
4860     }
4861     if (PrData)
4862       OS << format("<unknown flags: 0x%x>", PrData);
4863     return OS.str();
4864   case GNU_PROPERTY_X86_FEATURE_2_NEEDED:
4865   case GNU_PROPERTY_X86_FEATURE_2_USED:
4866     OS << "x86 feature "
4867        << (Type == GNU_PROPERTY_X86_FEATURE_2_NEEDED ? "needed: " : "used: ");
4868     if (DataSize != 4) {
4869       OS << format("<corrupt length: 0x%x>", DataSize);
4870       return OS.str();
4871     }
4872     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
4873     if (PrData == 0) {
4874       OS << "<None>";
4875       return OS.str();
4876     }
4877     DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86, "x86");
4878     DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87, "x87");
4879     DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX, "MMX");
4880     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM, "XMM");
4881     DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM, "YMM");
4882     DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM, "ZMM");
4883     DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR, "FXSR");
4884     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE, "XSAVE");
4885     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT, "XSAVEOPT");
4886     DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC, "XSAVEC");
4887     if (PrData)
4888       OS << format("<unknown flags: 0x%x>", PrData);
4889     return OS.str();
4890   case GNU_PROPERTY_X86_ISA_1_NEEDED:
4891   case GNU_PROPERTY_X86_ISA_1_USED:
4892     OS << "x86 ISA "
4893        << (Type == GNU_PROPERTY_X86_ISA_1_NEEDED ? "needed: " : "used: ");
4894     if (DataSize != 4) {
4895       OS << format("<corrupt length: 0x%x>", DataSize);
4896       return OS.str();
4897     }
4898     PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
4899     if (PrData == 0) {
4900       OS << "<None>";
4901       return OS.str();
4902     }
4903     DumpBit(GNU_PROPERTY_X86_ISA_1_BASELINE, "x86-64-baseline");
4904     DumpBit(GNU_PROPERTY_X86_ISA_1_V2, "x86-64-v2");
4905     DumpBit(GNU_PROPERTY_X86_ISA_1_V3, "x86-64-v3");
4906     DumpBit(GNU_PROPERTY_X86_ISA_1_V4, "x86-64-v4");
4907     if (PrData)
4908       OS << format("<unknown flags: 0x%x>", PrData);
4909     return OS.str();
4910   }
4911 }
4912 
4913 template <typename ELFT>
4914 static SmallVector<std::string, 4> getGNUPropertyList(ArrayRef<uint8_t> Arr) {
4915   using Elf_Word = typename ELFT::Word;
4916 
4917   SmallVector<std::string, 4> Properties;
4918   while (Arr.size() >= 8) {
4919     uint32_t Type = *reinterpret_cast<const Elf_Word *>(Arr.data());
4920     uint32_t DataSize = *reinterpret_cast<const Elf_Word *>(Arr.data() + 4);
4921     Arr = Arr.drop_front(8);
4922 
4923     // Take padding size into account if present.
4924     uint64_t PaddedSize = alignTo(DataSize, sizeof(typename ELFT::uint));
4925     std::string str;
4926     raw_string_ostream OS(str);
4927     if (Arr.size() < PaddedSize) {
4928       OS << format("<corrupt type (0x%x) datasz: 0x%x>", Type, DataSize);
4929       Properties.push_back(OS.str());
4930       break;
4931     }
4932     Properties.push_back(
4933         getGNUProperty<ELFT>(Type, DataSize, Arr.take_front(PaddedSize)));
4934     Arr = Arr.drop_front(PaddedSize);
4935   }
4936 
4937   if (!Arr.empty())
4938     Properties.push_back("<corrupted GNU_PROPERTY_TYPE_0>");
4939 
4940   return Properties;
4941 }
4942 
4943 struct GNUAbiTag {
4944   std::string OSName;
4945   std::string ABI;
4946   bool IsValid;
4947 };
4948 
4949 template <typename ELFT> static GNUAbiTag getGNUAbiTag(ArrayRef<uint8_t> Desc) {
4950   typedef typename ELFT::Word Elf_Word;
4951 
4952   ArrayRef<Elf_Word> Words(reinterpret_cast<const Elf_Word *>(Desc.begin()),
4953                            reinterpret_cast<const Elf_Word *>(Desc.end()));
4954 
4955   if (Words.size() < 4)
4956     return {"", "", /*IsValid=*/false};
4957 
4958   static const char *OSNames[] = {
4959       "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable", "NaCl",
4960   };
4961   StringRef OSName = "Unknown";
4962   if (Words[0] < array_lengthof(OSNames))
4963     OSName = OSNames[Words[0]];
4964   uint32_t Major = Words[1], Minor = Words[2], Patch = Words[3];
4965   std::string str;
4966   raw_string_ostream ABI(str);
4967   ABI << Major << "." << Minor << "." << Patch;
4968   return {std::string(OSName), ABI.str(), /*IsValid=*/true};
4969 }
4970 
4971 static std::string getGNUBuildId(ArrayRef<uint8_t> Desc) {
4972   std::string str;
4973   raw_string_ostream OS(str);
4974   for (uint8_t B : Desc)
4975     OS << format_hex_no_prefix(B, 2);
4976   return OS.str();
4977 }
4978 
4979 static StringRef getDescAsStringRef(ArrayRef<uint8_t> Desc) {
4980   return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
4981 }
4982 
4983 template <typename ELFT>
4984 static bool printGNUNote(raw_ostream &OS, uint32_t NoteType,
4985                          ArrayRef<uint8_t> Desc) {
4986   // Return true if we were able to pretty-print the note, false otherwise.
4987   switch (NoteType) {
4988   default:
4989     return false;
4990   case ELF::NT_GNU_ABI_TAG: {
4991     const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
4992     if (!AbiTag.IsValid)
4993       OS << "    <corrupt GNU_ABI_TAG>";
4994     else
4995       OS << "    OS: " << AbiTag.OSName << ", ABI: " << AbiTag.ABI;
4996     break;
4997   }
4998   case ELF::NT_GNU_BUILD_ID: {
4999     OS << "    Build ID: " << getGNUBuildId(Desc);
5000     break;
5001   }
5002   case ELF::NT_GNU_GOLD_VERSION:
5003     OS << "    Version: " << getDescAsStringRef(Desc);
5004     break;
5005   case ELF::NT_GNU_PROPERTY_TYPE_0:
5006     OS << "    Properties:";
5007     for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
5008       OS << "    " << Property << "\n";
5009     break;
5010   }
5011   OS << '\n';
5012   return true;
5013 }
5014 
5015 template <typename ELFT>
5016 static bool printLLVMOMPOFFLOADNote(raw_ostream &OS, uint32_t NoteType,
5017                                     ArrayRef<uint8_t> Desc) {
5018   switch (NoteType) {
5019   default:
5020     return false;
5021   case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
5022     OS << "    Version: " << getDescAsStringRef(Desc);
5023     break;
5024   case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
5025     OS << "    Producer: " << getDescAsStringRef(Desc);
5026     break;
5027   case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
5028     OS << "    Producer version: " << getDescAsStringRef(Desc);
5029     break;
5030   }
5031   OS << '\n';
5032   return true;
5033 }
5034 
5035 const EnumEntry<unsigned> FreeBSDFeatureCtlFlags[] = {
5036     {"ASLR_DISABLE", NT_FREEBSD_FCTL_ASLR_DISABLE},
5037     {"PROTMAX_DISABLE", NT_FREEBSD_FCTL_PROTMAX_DISABLE},
5038     {"STKGAP_DISABLE", NT_FREEBSD_FCTL_STKGAP_DISABLE},
5039     {"WXNEEDED", NT_FREEBSD_FCTL_WXNEEDED},
5040     {"LA48", NT_FREEBSD_FCTL_LA48},
5041     {"ASG_DISABLE", NT_FREEBSD_FCTL_ASG_DISABLE},
5042 };
5043 
5044 struct FreeBSDNote {
5045   std::string Type;
5046   std::string Value;
5047 };
5048 
5049 template <typename ELFT>
5050 static Optional<FreeBSDNote>
5051 getFreeBSDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc, bool IsCore) {
5052   if (IsCore)
5053     return None; // No pretty-printing yet.
5054   switch (NoteType) {
5055   case ELF::NT_FREEBSD_ABI_TAG:
5056     if (Desc.size() != 4)
5057       return None;
5058     return FreeBSDNote{
5059         "ABI tag",
5060         utostr(support::endian::read32<ELFT::TargetEndianness>(Desc.data()))};
5061   case ELF::NT_FREEBSD_ARCH_TAG:
5062     return FreeBSDNote{"Arch tag", toStringRef(Desc).str()};
5063   case ELF::NT_FREEBSD_FEATURE_CTL: {
5064     if (Desc.size() != 4)
5065       return None;
5066     unsigned Value =
5067         support::endian::read32<ELFT::TargetEndianness>(Desc.data());
5068     std::string FlagsStr;
5069     raw_string_ostream OS(FlagsStr);
5070     printFlags(Value, makeArrayRef(FreeBSDFeatureCtlFlags), OS);
5071     if (OS.str().empty())
5072       OS << "0x" << utohexstr(Value);
5073     else
5074       OS << "(0x" << utohexstr(Value) << ")";
5075     return FreeBSDNote{"Feature flags", OS.str()};
5076   }
5077   default:
5078     return None;
5079   }
5080 }
5081 
5082 struct AMDNote {
5083   std::string Type;
5084   std::string Value;
5085 };
5086 
5087 template <typename ELFT>
5088 static AMDNote getAMDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
5089   switch (NoteType) {
5090   default:
5091     return {"", ""};
5092   case ELF::NT_AMD_HSA_CODE_OBJECT_VERSION: {
5093     struct CodeObjectVersion {
5094       uint32_t MajorVersion;
5095       uint32_t MinorVersion;
5096     };
5097     if (Desc.size() != sizeof(CodeObjectVersion))
5098       return {"AMD HSA Code Object Version",
5099               "Invalid AMD HSA Code Object Version"};
5100     std::string VersionString;
5101     raw_string_ostream StrOS(VersionString);
5102     auto Version = reinterpret_cast<const CodeObjectVersion *>(Desc.data());
5103     StrOS << "[Major: " << Version->MajorVersion
5104           << ", Minor: " << Version->MinorVersion << "]";
5105     return {"AMD HSA Code Object Version", VersionString};
5106   }
5107   case ELF::NT_AMD_HSA_HSAIL: {
5108     struct HSAILProperties {
5109       uint32_t HSAILMajorVersion;
5110       uint32_t HSAILMinorVersion;
5111       uint8_t Profile;
5112       uint8_t MachineModel;
5113       uint8_t DefaultFloatRound;
5114     };
5115     if (Desc.size() != sizeof(HSAILProperties))
5116       return {"AMD HSA HSAIL Properties", "Invalid AMD HSA HSAIL Properties"};
5117     auto Properties = reinterpret_cast<const HSAILProperties *>(Desc.data());
5118     std::string HSAILPropetiesString;
5119     raw_string_ostream StrOS(HSAILPropetiesString);
5120     StrOS << "[HSAIL Major: " << Properties->HSAILMajorVersion
5121           << ", HSAIL Minor: " << Properties->HSAILMinorVersion
5122           << ", Profile: " << uint32_t(Properties->Profile)
5123           << ", Machine Model: " << uint32_t(Properties->MachineModel)
5124           << ", Default Float Round: "
5125           << uint32_t(Properties->DefaultFloatRound) << "]";
5126     return {"AMD HSA HSAIL Properties", HSAILPropetiesString};
5127   }
5128   case ELF::NT_AMD_HSA_ISA_VERSION: {
5129     struct IsaVersion {
5130       uint16_t VendorNameSize;
5131       uint16_t ArchitectureNameSize;
5132       uint32_t Major;
5133       uint32_t Minor;
5134       uint32_t Stepping;
5135     };
5136     if (Desc.size() < sizeof(IsaVersion))
5137       return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"};
5138     auto Isa = reinterpret_cast<const IsaVersion *>(Desc.data());
5139     if (Desc.size() < sizeof(IsaVersion) +
5140                           Isa->VendorNameSize + Isa->ArchitectureNameSize ||
5141         Isa->VendorNameSize == 0 || Isa->ArchitectureNameSize == 0)
5142       return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"};
5143     std::string IsaString;
5144     raw_string_ostream StrOS(IsaString);
5145     StrOS << "[Vendor: "
5146           << StringRef((const char*)Desc.data() + sizeof(IsaVersion), Isa->VendorNameSize - 1)
5147           << ", Architecture: "
5148           << StringRef((const char*)Desc.data() + sizeof(IsaVersion) + Isa->VendorNameSize,
5149                        Isa->ArchitectureNameSize - 1)
5150           << ", Major: " << Isa->Major << ", Minor: " << Isa->Minor
5151           << ", Stepping: " << Isa->Stepping << "]";
5152     return {"AMD HSA ISA Version", IsaString};
5153   }
5154   case ELF::NT_AMD_HSA_METADATA: {
5155     if (Desc.size() == 0)
5156       return {"AMD HSA Metadata", ""};
5157     return {
5158         "AMD HSA Metadata",
5159         std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size() - 1)};
5160   }
5161   case ELF::NT_AMD_HSA_ISA_NAME: {
5162     if (Desc.size() == 0)
5163       return {"AMD HSA ISA Name", ""};
5164     return {
5165         "AMD HSA ISA Name",
5166         std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
5167   }
5168   case ELF::NT_AMD_PAL_METADATA: {
5169     struct PALMetadata {
5170       uint32_t Key;
5171       uint32_t Value;
5172     };
5173     if (Desc.size() % sizeof(PALMetadata) != 0)
5174       return {"AMD PAL Metadata", "Invalid AMD PAL Metadata"};
5175     auto Isa = reinterpret_cast<const PALMetadata *>(Desc.data());
5176     std::string MetadataString;
5177     raw_string_ostream StrOS(MetadataString);
5178     for (size_t I = 0, E = Desc.size() / sizeof(PALMetadata); I < E; ++I) {
5179       StrOS << "[" << Isa[I].Key << ": " << Isa[I].Value << "]";
5180     }
5181     return {"AMD PAL Metadata", MetadataString};
5182   }
5183   }
5184 }
5185 
5186 struct AMDGPUNote {
5187   std::string Type;
5188   std::string Value;
5189 };
5190 
5191 template <typename ELFT>
5192 static AMDGPUNote getAMDGPUNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
5193   switch (NoteType) {
5194   default:
5195     return {"", ""};
5196   case ELF::NT_AMDGPU_METADATA: {
5197     StringRef MsgPackString =
5198         StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
5199     msgpack::Document MsgPackDoc;
5200     if (!MsgPackDoc.readFromBlob(MsgPackString, /*Multi=*/false))
5201       return {"", ""};
5202 
5203     AMDGPU::HSAMD::V3::MetadataVerifier Verifier(true);
5204     std::string MetadataString;
5205     if (!Verifier.verify(MsgPackDoc.getRoot()))
5206       MetadataString = "Invalid AMDGPU Metadata\n";
5207 
5208     raw_string_ostream StrOS(MetadataString);
5209     if (MsgPackDoc.getRoot().isScalar()) {
5210       // TODO: passing a scalar root to toYAML() asserts:
5211       // (PolymorphicTraits<T>::getKind(Val) != NodeKind::Scalar &&
5212       //    "plain scalar documents are not supported")
5213       // To avoid this crash we print the raw data instead.
5214       return {"", ""};
5215     }
5216     MsgPackDoc.toYAML(StrOS);
5217     return {"AMDGPU Metadata", StrOS.str()};
5218   }
5219   }
5220 }
5221 
5222 struct CoreFileMapping {
5223   uint64_t Start, End, Offset;
5224   StringRef Filename;
5225 };
5226 
5227 struct CoreNote {
5228   uint64_t PageSize;
5229   std::vector<CoreFileMapping> Mappings;
5230 };
5231 
5232 static Expected<CoreNote> readCoreNote(DataExtractor Desc) {
5233   // Expected format of the NT_FILE note description:
5234   // 1. # of file mappings (call it N)
5235   // 2. Page size
5236   // 3. N (start, end, offset) triples
5237   // 4. N packed filenames (null delimited)
5238   // Each field is an Elf_Addr, except for filenames which are char* strings.
5239 
5240   CoreNote Ret;
5241   const int Bytes = Desc.getAddressSize();
5242 
5243   if (!Desc.isValidOffsetForAddress(2))
5244     return createError("the note of size 0x" + Twine::utohexstr(Desc.size()) +
5245                        " is too short, expected at least 0x" +
5246                        Twine::utohexstr(Bytes * 2));
5247   if (Desc.getData().back() != 0)
5248     return createError("the note is not NUL terminated");
5249 
5250   uint64_t DescOffset = 0;
5251   uint64_t FileCount = Desc.getAddress(&DescOffset);
5252   Ret.PageSize = Desc.getAddress(&DescOffset);
5253 
5254   if (!Desc.isValidOffsetForAddress(3 * FileCount * Bytes))
5255     return createError("unable to read file mappings (found " +
5256                        Twine(FileCount) + "): the note of size 0x" +
5257                        Twine::utohexstr(Desc.size()) + " is too short");
5258 
5259   uint64_t FilenamesOffset = 0;
5260   DataExtractor Filenames(
5261       Desc.getData().drop_front(DescOffset + 3 * FileCount * Bytes),
5262       Desc.isLittleEndian(), Desc.getAddressSize());
5263 
5264   Ret.Mappings.resize(FileCount);
5265   size_t I = 0;
5266   for (CoreFileMapping &Mapping : Ret.Mappings) {
5267     ++I;
5268     if (!Filenames.isValidOffsetForDataOfSize(FilenamesOffset, 1))
5269       return createError(
5270           "unable to read the file name for the mapping with index " +
5271           Twine(I) + ": the note of size 0x" + Twine::utohexstr(Desc.size()) +
5272           " is truncated");
5273     Mapping.Start = Desc.getAddress(&DescOffset);
5274     Mapping.End = Desc.getAddress(&DescOffset);
5275     Mapping.Offset = Desc.getAddress(&DescOffset);
5276     Mapping.Filename = Filenames.getCStrRef(&FilenamesOffset);
5277   }
5278 
5279   return Ret;
5280 }
5281 
5282 template <typename ELFT>
5283 static void printCoreNote(raw_ostream &OS, const CoreNote &Note) {
5284   // Length of "0x<address>" string.
5285   const int FieldWidth = ELFT::Is64Bits ? 18 : 10;
5286 
5287   OS << "    Page size: " << format_decimal(Note.PageSize, 0) << '\n';
5288   OS << "    " << right_justify("Start", FieldWidth) << "  "
5289      << right_justify("End", FieldWidth) << "  "
5290      << right_justify("Page Offset", FieldWidth) << '\n';
5291   for (const CoreFileMapping &Mapping : Note.Mappings) {
5292     OS << "    " << format_hex(Mapping.Start, FieldWidth) << "  "
5293        << format_hex(Mapping.End, FieldWidth) << "  "
5294        << format_hex(Mapping.Offset, FieldWidth) << "\n        "
5295        << Mapping.Filename << '\n';
5296   }
5297 }
5298 
5299 const NoteType GenericNoteTypes[] = {
5300     {ELF::NT_VERSION, "NT_VERSION (version)"},
5301     {ELF::NT_ARCH, "NT_ARCH (architecture)"},
5302     {ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN, "OPEN"},
5303     {ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC, "func"},
5304 };
5305 
5306 const NoteType GNUNoteTypes[] = {
5307     {ELF::NT_GNU_ABI_TAG, "NT_GNU_ABI_TAG (ABI version tag)"},
5308     {ELF::NT_GNU_HWCAP, "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"},
5309     {ELF::NT_GNU_BUILD_ID, "NT_GNU_BUILD_ID (unique build ID bitstring)"},
5310     {ELF::NT_GNU_GOLD_VERSION, "NT_GNU_GOLD_VERSION (gold version)"},
5311     {ELF::NT_GNU_PROPERTY_TYPE_0, "NT_GNU_PROPERTY_TYPE_0 (property note)"},
5312 };
5313 
5314 const NoteType FreeBSDCoreNoteTypes[] = {
5315     {ELF::NT_FREEBSD_THRMISC, "NT_THRMISC (thrmisc structure)"},
5316     {ELF::NT_FREEBSD_PROCSTAT_PROC, "NT_PROCSTAT_PROC (proc data)"},
5317     {ELF::NT_FREEBSD_PROCSTAT_FILES, "NT_PROCSTAT_FILES (files data)"},
5318     {ELF::NT_FREEBSD_PROCSTAT_VMMAP, "NT_PROCSTAT_VMMAP (vmmap data)"},
5319     {ELF::NT_FREEBSD_PROCSTAT_GROUPS, "NT_PROCSTAT_GROUPS (groups data)"},
5320     {ELF::NT_FREEBSD_PROCSTAT_UMASK, "NT_PROCSTAT_UMASK (umask data)"},
5321     {ELF::NT_FREEBSD_PROCSTAT_RLIMIT, "NT_PROCSTAT_RLIMIT (rlimit data)"},
5322     {ELF::NT_FREEBSD_PROCSTAT_OSREL, "NT_PROCSTAT_OSREL (osreldate data)"},
5323     {ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS,
5324      "NT_PROCSTAT_PSSTRINGS (ps_strings data)"},
5325     {ELF::NT_FREEBSD_PROCSTAT_AUXV, "NT_PROCSTAT_AUXV (auxv data)"},
5326 };
5327 
5328 const NoteType FreeBSDNoteTypes[] = {
5329     {ELF::NT_FREEBSD_ABI_TAG, "NT_FREEBSD_ABI_TAG (ABI version tag)"},
5330     {ELF::NT_FREEBSD_NOINIT_TAG, "NT_FREEBSD_NOINIT_TAG (no .init tag)"},
5331     {ELF::NT_FREEBSD_ARCH_TAG, "NT_FREEBSD_ARCH_TAG (architecture tag)"},
5332     {ELF::NT_FREEBSD_FEATURE_CTL,
5333      "NT_FREEBSD_FEATURE_CTL (FreeBSD feature control)"},
5334 };
5335 
5336 const NoteType OpenBSDCoreNoteTypes[] = {
5337     {ELF::NT_OPENBSD_PROCINFO, "NT_OPENBSD_PROCINFO (procinfo structure)"},
5338     {ELF::NT_OPENBSD_AUXV, "NT_OPENBSD_AUXV (ELF auxiliary vector data)"},
5339     {ELF::NT_OPENBSD_REGS, "NT_OPENBSD_REGS (regular registers)"},
5340     {ELF::NT_OPENBSD_FPREGS, "NT_OPENBSD_FPREGS (floating point registers)"},
5341     {ELF::NT_OPENBSD_WCOOKIE, "NT_OPENBSD_WCOOKIE (window cookie)"},
5342 };
5343 
5344 const NoteType AMDNoteTypes[] = {
5345     {ELF::NT_AMD_HSA_CODE_OBJECT_VERSION,
5346      "NT_AMD_HSA_CODE_OBJECT_VERSION (AMD HSA Code Object Version)"},
5347     {ELF::NT_AMD_HSA_HSAIL, "NT_AMD_HSA_HSAIL (AMD HSA HSAIL Properties)"},
5348     {ELF::NT_AMD_HSA_ISA_VERSION, "NT_AMD_HSA_ISA_VERSION (AMD HSA ISA Version)"},
5349     {ELF::NT_AMD_HSA_METADATA, "NT_AMD_HSA_METADATA (AMD HSA Metadata)"},
5350     {ELF::NT_AMD_HSA_ISA_NAME, "NT_AMD_HSA_ISA_NAME (AMD HSA ISA Name)"},
5351     {ELF::NT_AMD_PAL_METADATA, "NT_AMD_PAL_METADATA (AMD PAL Metadata)"},
5352 };
5353 
5354 const NoteType AMDGPUNoteTypes[] = {
5355     {ELF::NT_AMDGPU_METADATA, "NT_AMDGPU_METADATA (AMDGPU Metadata)"},
5356 };
5357 
5358 const NoteType LLVMOMPOFFLOADNoteTypes[] = {
5359     {ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION,
5360      "NT_LLVM_OPENMP_OFFLOAD_VERSION (image format version)"},
5361     {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER,
5362      "NT_LLVM_OPENMP_OFFLOAD_PRODUCER (producing toolchain)"},
5363     {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION,
5364      "NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION (producing toolchain version)"},
5365 };
5366 
5367 const NoteType CoreNoteTypes[] = {
5368     {ELF::NT_PRSTATUS, "NT_PRSTATUS (prstatus structure)"},
5369     {ELF::NT_FPREGSET, "NT_FPREGSET (floating point registers)"},
5370     {ELF::NT_PRPSINFO, "NT_PRPSINFO (prpsinfo structure)"},
5371     {ELF::NT_TASKSTRUCT, "NT_TASKSTRUCT (task structure)"},
5372     {ELF::NT_AUXV, "NT_AUXV (auxiliary vector)"},
5373     {ELF::NT_PSTATUS, "NT_PSTATUS (pstatus structure)"},
5374     {ELF::NT_FPREGS, "NT_FPREGS (floating point registers)"},
5375     {ELF::NT_PSINFO, "NT_PSINFO (psinfo structure)"},
5376     {ELF::NT_LWPSTATUS, "NT_LWPSTATUS (lwpstatus_t structure)"},
5377     {ELF::NT_LWPSINFO, "NT_LWPSINFO (lwpsinfo_t structure)"},
5378     {ELF::NT_WIN32PSTATUS, "NT_WIN32PSTATUS (win32_pstatus structure)"},
5379 
5380     {ELF::NT_PPC_VMX, "NT_PPC_VMX (ppc Altivec registers)"},
5381     {ELF::NT_PPC_VSX, "NT_PPC_VSX (ppc VSX registers)"},
5382     {ELF::NT_PPC_TAR, "NT_PPC_TAR (ppc TAR register)"},
5383     {ELF::NT_PPC_PPR, "NT_PPC_PPR (ppc PPR register)"},
5384     {ELF::NT_PPC_DSCR, "NT_PPC_DSCR (ppc DSCR register)"},
5385     {ELF::NT_PPC_EBB, "NT_PPC_EBB (ppc EBB registers)"},
5386     {ELF::NT_PPC_PMU, "NT_PPC_PMU (ppc PMU registers)"},
5387     {ELF::NT_PPC_TM_CGPR, "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"},
5388     {ELF::NT_PPC_TM_CFPR,
5389      "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"},
5390     {ELF::NT_PPC_TM_CVMX,
5391      "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"},
5392     {ELF::NT_PPC_TM_CVSX, "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"},
5393     {ELF::NT_PPC_TM_SPR, "NT_PPC_TM_SPR (ppc TM special purpose registers)"},
5394     {ELF::NT_PPC_TM_CTAR, "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"},
5395     {ELF::NT_PPC_TM_CPPR, "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"},
5396     {ELF::NT_PPC_TM_CDSCR, "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"},
5397 
5398     {ELF::NT_386_TLS, "NT_386_TLS (x86 TLS information)"},
5399     {ELF::NT_386_IOPERM, "NT_386_IOPERM (x86 I/O permissions)"},
5400     {ELF::NT_X86_XSTATE, "NT_X86_XSTATE (x86 XSAVE extended state)"},
5401 
5402     {ELF::NT_S390_HIGH_GPRS, "NT_S390_HIGH_GPRS (s390 upper register halves)"},
5403     {ELF::NT_S390_TIMER, "NT_S390_TIMER (s390 timer register)"},
5404     {ELF::NT_S390_TODCMP, "NT_S390_TODCMP (s390 TOD comparator register)"},
5405     {ELF::NT_S390_TODPREG, "NT_S390_TODPREG (s390 TOD programmable register)"},
5406     {ELF::NT_S390_CTRS, "NT_S390_CTRS (s390 control registers)"},
5407     {ELF::NT_S390_PREFIX, "NT_S390_PREFIX (s390 prefix register)"},
5408     {ELF::NT_S390_LAST_BREAK,
5409      "NT_S390_LAST_BREAK (s390 last breaking event address)"},
5410     {ELF::NT_S390_SYSTEM_CALL,
5411      "NT_S390_SYSTEM_CALL (s390 system call restart data)"},
5412     {ELF::NT_S390_TDB, "NT_S390_TDB (s390 transaction diagnostic block)"},
5413     {ELF::NT_S390_VXRS_LOW,
5414      "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"},
5415     {ELF::NT_S390_VXRS_HIGH, "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"},
5416     {ELF::NT_S390_GS_CB, "NT_S390_GS_CB (s390 guarded-storage registers)"},
5417     {ELF::NT_S390_GS_BC,
5418      "NT_S390_GS_BC (s390 guarded-storage broadcast control)"},
5419 
5420     {ELF::NT_ARM_VFP, "NT_ARM_VFP (arm VFP registers)"},
5421     {ELF::NT_ARM_TLS, "NT_ARM_TLS (AArch TLS registers)"},
5422     {ELF::NT_ARM_HW_BREAK,
5423      "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"},
5424     {ELF::NT_ARM_HW_WATCH,
5425      "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"},
5426 
5427     {ELF::NT_FILE, "NT_FILE (mapped files)"},
5428     {ELF::NT_PRXFPREG, "NT_PRXFPREG (user_xfpregs structure)"},
5429     {ELF::NT_SIGINFO, "NT_SIGINFO (siginfo_t data)"},
5430 };
5431 
5432 template <class ELFT>
5433 StringRef getNoteTypeName(const typename ELFT::Note &Note, unsigned ELFType) {
5434   uint32_t Type = Note.getType();
5435   auto FindNote = [&](ArrayRef<NoteType> V) -> StringRef {
5436     for (const NoteType &N : V)
5437       if (N.ID == Type)
5438         return N.Name;
5439     return "";
5440   };
5441 
5442   StringRef Name = Note.getName();
5443   if (Name == "GNU")
5444     return FindNote(GNUNoteTypes);
5445   if (Name == "FreeBSD") {
5446     if (ELFType == ELF::ET_CORE) {
5447       // FreeBSD also places the generic core notes in the FreeBSD namespace.
5448       StringRef Result = FindNote(FreeBSDCoreNoteTypes);
5449       if (!Result.empty())
5450         return Result;
5451       return FindNote(CoreNoteTypes);
5452     } else {
5453       return FindNote(FreeBSDNoteTypes);
5454     }
5455   }
5456   if (Name.startswith("OpenBSD") && ELFType == ELF::ET_CORE) {
5457     // OpenBSD also places the generic core notes in the OpenBSD namespace.
5458     StringRef Result = FindNote(OpenBSDCoreNoteTypes);
5459     if (!Result.empty())
5460       return Result;
5461     return FindNote(CoreNoteTypes);
5462   }
5463   if (Name == "AMD")
5464     return FindNote(AMDNoteTypes);
5465   if (Name == "AMDGPU")
5466     return FindNote(AMDGPUNoteTypes);
5467   if (Name == "LLVMOMPOFFLOAD")
5468     return FindNote(LLVMOMPOFFLOADNoteTypes);
5469 
5470   if (ELFType == ELF::ET_CORE)
5471     return FindNote(CoreNoteTypes);
5472   return FindNote(GenericNoteTypes);
5473 }
5474 
5475 template <class ELFT>
5476 static void printNotesHelper(
5477     const ELFDumper<ELFT> &Dumper,
5478     llvm::function_ref<void(Optional<StringRef>, typename ELFT::Off,
5479                             typename ELFT::Addr)>
5480         StartNotesFn,
5481     llvm::function_ref<Error(const typename ELFT::Note &, bool)> ProcessNoteFn,
5482     llvm::function_ref<void()> FinishNotesFn) {
5483   const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
5484   bool IsCoreFile = Obj.getHeader().e_type == ELF::ET_CORE;
5485 
5486   ArrayRef<typename ELFT::Shdr> Sections = cantFail(Obj.sections());
5487   if (!IsCoreFile && !Sections.empty()) {
5488     for (const typename ELFT::Shdr &S : Sections) {
5489       if (S.sh_type != SHT_NOTE)
5490         continue;
5491       StartNotesFn(expectedToOptional(Obj.getSectionName(S)), S.sh_offset,
5492                    S.sh_size);
5493       Error Err = Error::success();
5494       size_t I = 0;
5495       for (const typename ELFT::Note Note : Obj.notes(S, Err)) {
5496         if (Error E = ProcessNoteFn(Note, IsCoreFile))
5497           Dumper.reportUniqueWarning(
5498               "unable to read note with index " + Twine(I) + " from the " +
5499               describe(Obj, S) + ": " + toString(std::move(E)));
5500         ++I;
5501       }
5502       if (Err)
5503         Dumper.reportUniqueWarning("unable to read notes from the " +
5504                                    describe(Obj, S) + ": " +
5505                                    toString(std::move(Err)));
5506       FinishNotesFn();
5507     }
5508     return;
5509   }
5510 
5511   Expected<ArrayRef<typename ELFT::Phdr>> PhdrsOrErr = Obj.program_headers();
5512   if (!PhdrsOrErr) {
5513     Dumper.reportUniqueWarning(
5514         "unable to read program headers to locate the PT_NOTE segment: " +
5515         toString(PhdrsOrErr.takeError()));
5516     return;
5517   }
5518 
5519   for (size_t I = 0, E = (*PhdrsOrErr).size(); I != E; ++I) {
5520     const typename ELFT::Phdr &P = (*PhdrsOrErr)[I];
5521     if (P.p_type != PT_NOTE)
5522       continue;
5523     StartNotesFn(/*SecName=*/None, P.p_offset, P.p_filesz);
5524     Error Err = Error::success();
5525     size_t Index = 0;
5526     for (const typename ELFT::Note Note : Obj.notes(P, Err)) {
5527       if (Error E = ProcessNoteFn(Note, IsCoreFile))
5528         Dumper.reportUniqueWarning("unable to read note with index " +
5529                                    Twine(Index) +
5530                                    " from the PT_NOTE segment with index " +
5531                                    Twine(I) + ": " + toString(std::move(E)));
5532       ++Index;
5533     }
5534     if (Err)
5535       Dumper.reportUniqueWarning(
5536           "unable to read notes from the PT_NOTE segment with index " +
5537           Twine(I) + ": " + toString(std::move(Err)));
5538     FinishNotesFn();
5539   }
5540 }
5541 
5542 template <class ELFT> void GNUELFDumper<ELFT>::printNotes() {
5543   bool IsFirstHeader = true;
5544   auto PrintHeader = [&](Optional<StringRef> SecName,
5545                          const typename ELFT::Off Offset,
5546                          const typename ELFT::Addr Size) {
5547     // Print a newline between notes sections to match GNU readelf.
5548     if (!IsFirstHeader) {
5549       OS << '\n';
5550     } else {
5551       IsFirstHeader = false;
5552     }
5553 
5554     OS << "Displaying notes found ";
5555 
5556     if (SecName)
5557       OS << "in: " << *SecName << "\n";
5558     else
5559       OS << "at file offset " << format_hex(Offset, 10) << " with length "
5560          << format_hex(Size, 10) << ":\n";
5561 
5562     OS << "  Owner                Data size \tDescription\n";
5563   };
5564 
5565   auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
5566     StringRef Name = Note.getName();
5567     ArrayRef<uint8_t> Descriptor = Note.getDesc();
5568     Elf_Word Type = Note.getType();
5569 
5570     // Print the note owner/type.
5571     OS << "  " << left_justify(Name, 20) << ' '
5572        << format_hex(Descriptor.size(), 10) << '\t';
5573 
5574     StringRef NoteType =
5575         getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
5576     if (!NoteType.empty())
5577       OS << NoteType << '\n';
5578     else
5579       OS << "Unknown note type: (" << format_hex(Type, 10) << ")\n";
5580 
5581     // Print the description, or fallback to printing raw bytes for unknown
5582     // owners/if we fail to pretty-print the contents.
5583     if (Name == "GNU") {
5584       if (printGNUNote<ELFT>(OS, Type, Descriptor))
5585         return Error::success();
5586     } else if (Name == "FreeBSD") {
5587       if (Optional<FreeBSDNote> N =
5588               getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
5589         OS << "    " << N->Type << ": " << N->Value << '\n';
5590         return Error::success();
5591       }
5592     } else if (Name == "AMD") {
5593       const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
5594       if (!N.Type.empty()) {
5595         OS << "    " << N.Type << ":\n        " << N.Value << '\n';
5596         return Error::success();
5597       }
5598     } else if (Name == "AMDGPU") {
5599       const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
5600       if (!N.Type.empty()) {
5601         OS << "    " << N.Type << ":\n        " << N.Value << '\n';
5602         return Error::success();
5603       }
5604     } else if (Name == "LLVMOMPOFFLOAD") {
5605       if (printLLVMOMPOFFLOADNote<ELFT>(OS, Type, Descriptor))
5606         return Error::success();
5607     } else if (Name == "CORE") {
5608       if (Type == ELF::NT_FILE) {
5609         DataExtractor DescExtractor(Descriptor,
5610                                     ELFT::TargetEndianness == support::little,
5611                                     sizeof(Elf_Addr));
5612         if (Expected<CoreNote> NoteOrErr = readCoreNote(DescExtractor)) {
5613           printCoreNote<ELFT>(OS, *NoteOrErr);
5614           return Error::success();
5615         } else {
5616           return NoteOrErr.takeError();
5617         }
5618       }
5619     }
5620     if (!Descriptor.empty()) {
5621       OS << "   description data:";
5622       for (uint8_t B : Descriptor)
5623         OS << " " << format("%02x", B);
5624       OS << '\n';
5625     }
5626     return Error::success();
5627   };
5628 
5629   printNotesHelper(*this, PrintHeader, ProcessNote, []() {});
5630 }
5631 
5632 template <class ELFT> void GNUELFDumper<ELFT>::printELFLinkerOptions() {
5633   OS << "printELFLinkerOptions not implemented!\n";
5634 }
5635 
5636 template <class ELFT>
5637 void ELFDumper<ELFT>::printDependentLibsHelper(
5638     function_ref<void(const Elf_Shdr &)> OnSectionStart,
5639     function_ref<void(StringRef, uint64_t)> OnLibEntry) {
5640   auto Warn = [this](unsigned SecNdx, StringRef Msg) {
5641     this->reportUniqueWarning("SHT_LLVM_DEPENDENT_LIBRARIES section at index " +
5642                               Twine(SecNdx) + " is broken: " + Msg);
5643   };
5644 
5645   unsigned I = -1;
5646   for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
5647     ++I;
5648     if (Shdr.sh_type != ELF::SHT_LLVM_DEPENDENT_LIBRARIES)
5649       continue;
5650 
5651     OnSectionStart(Shdr);
5652 
5653     Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Shdr);
5654     if (!ContentsOrErr) {
5655       Warn(I, toString(ContentsOrErr.takeError()));
5656       continue;
5657     }
5658 
5659     ArrayRef<uint8_t> Contents = *ContentsOrErr;
5660     if (!Contents.empty() && Contents.back() != 0) {
5661       Warn(I, "the content is not null-terminated");
5662       continue;
5663     }
5664 
5665     for (const uint8_t *I = Contents.begin(), *E = Contents.end(); I < E;) {
5666       StringRef Lib((const char *)I);
5667       OnLibEntry(Lib, I - Contents.begin());
5668       I += Lib.size() + 1;
5669     }
5670   }
5671 }
5672 
5673 template <class ELFT>
5674 void ELFDumper<ELFT>::forEachRelocationDo(
5675     const Elf_Shdr &Sec, bool RawRelr,
5676     llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
5677                             const Elf_Shdr &, const Elf_Shdr *)>
5678         RelRelaFn,
5679     llvm::function_ref<void(const Elf_Relr &)> RelrFn) {
5680   auto Warn = [&](Error &&E,
5681                   const Twine &Prefix = "unable to read relocations from") {
5682     this->reportUniqueWarning(Prefix + " " + describe(Sec) + ": " +
5683                               toString(std::move(E)));
5684   };
5685 
5686   // SHT_RELR/SHT_ANDROID_RELR sections do not have an associated symbol table.
5687   // For them we should not treat the value of the sh_link field as an index of
5688   // a symbol table.
5689   const Elf_Shdr *SymTab;
5690   if (Sec.sh_type != ELF::SHT_RELR && Sec.sh_type != ELF::SHT_ANDROID_RELR) {
5691     Expected<const Elf_Shdr *> SymTabOrErr = Obj.getSection(Sec.sh_link);
5692     if (!SymTabOrErr) {
5693       Warn(SymTabOrErr.takeError(), "unable to locate a symbol table for");
5694       return;
5695     }
5696     SymTab = *SymTabOrErr;
5697   }
5698 
5699   unsigned RelNdx = 0;
5700   const bool IsMips64EL = this->Obj.isMips64EL();
5701   switch (Sec.sh_type) {
5702   case ELF::SHT_REL:
5703     if (Expected<Elf_Rel_Range> RangeOrErr = Obj.rels(Sec)) {
5704       for (const Elf_Rel &R : *RangeOrErr)
5705         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5706     } else {
5707       Warn(RangeOrErr.takeError());
5708     }
5709     break;
5710   case ELF::SHT_RELA:
5711     if (Expected<Elf_Rela_Range> RangeOrErr = Obj.relas(Sec)) {
5712       for (const Elf_Rela &R : *RangeOrErr)
5713         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5714     } else {
5715       Warn(RangeOrErr.takeError());
5716     }
5717     break;
5718   case ELF::SHT_RELR:
5719   case ELF::SHT_ANDROID_RELR: {
5720     Expected<Elf_Relr_Range> RangeOrErr = Obj.relrs(Sec);
5721     if (!RangeOrErr) {
5722       Warn(RangeOrErr.takeError());
5723       break;
5724     }
5725     if (RawRelr) {
5726       for (const Elf_Relr &R : *RangeOrErr)
5727         RelrFn(R);
5728       break;
5729     }
5730 
5731     for (const Elf_Rel &R : Obj.decode_relrs(*RangeOrErr))
5732       RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec,
5733                 /*SymTab=*/nullptr);
5734     break;
5735   }
5736   case ELF::SHT_ANDROID_REL:
5737   case ELF::SHT_ANDROID_RELA:
5738     if (Expected<std::vector<Elf_Rela>> RelasOrErr = Obj.android_relas(Sec)) {
5739       for (const Elf_Rela &R : *RelasOrErr)
5740         RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
5741     } else {
5742       Warn(RelasOrErr.takeError());
5743     }
5744     break;
5745   }
5746 }
5747 
5748 template <class ELFT>
5749 StringRef ELFDumper<ELFT>::getPrintableSectionName(const Elf_Shdr &Sec) const {
5750   StringRef Name = "<?>";
5751   if (Expected<StringRef> SecNameOrErr =
5752           Obj.getSectionName(Sec, this->WarningHandler))
5753     Name = *SecNameOrErr;
5754   else
5755     this->reportUniqueWarning("unable to get the name of " + describe(Sec) +
5756                               ": " + toString(SecNameOrErr.takeError()));
5757   return Name;
5758 }
5759 
5760 template <class ELFT> void GNUELFDumper<ELFT>::printDependentLibs() {
5761   bool SectionStarted = false;
5762   struct NameOffset {
5763     StringRef Name;
5764     uint64_t Offset;
5765   };
5766   std::vector<NameOffset> SecEntries;
5767   NameOffset Current;
5768   auto PrintSection = [&]() {
5769     OS << "Dependent libraries section " << Current.Name << " at offset "
5770        << format_hex(Current.Offset, 1) << " contains " << SecEntries.size()
5771        << " entries:\n";
5772     for (NameOffset Entry : SecEntries)
5773       OS << "  [" << format("%6" PRIx64, Entry.Offset) << "]  " << Entry.Name
5774          << "\n";
5775     OS << "\n";
5776     SecEntries.clear();
5777   };
5778 
5779   auto OnSectionStart = [&](const Elf_Shdr &Shdr) {
5780     if (SectionStarted)
5781       PrintSection();
5782     SectionStarted = true;
5783     Current.Offset = Shdr.sh_offset;
5784     Current.Name = this->getPrintableSectionName(Shdr);
5785   };
5786   auto OnLibEntry = [&](StringRef Lib, uint64_t Offset) {
5787     SecEntries.push_back(NameOffset{Lib, Offset});
5788   };
5789 
5790   this->printDependentLibsHelper(OnSectionStart, OnLibEntry);
5791   if (SectionStarted)
5792     PrintSection();
5793 }
5794 
5795 template <class ELFT>
5796 SmallVector<uint32_t> ELFDumper<ELFT>::getSymbolIndexesForFunctionAddress(
5797     uint64_t SymValue, Optional<const Elf_Shdr *> FunctionSec) {
5798   SmallVector<uint32_t> SymbolIndexes;
5799   if (!this->AddressToIndexMap.hasValue()) {
5800     // Populate the address to index map upon the first invocation of this
5801     // function.
5802     this->AddressToIndexMap.emplace();
5803     if (this->DotSymtabSec) {
5804       if (Expected<Elf_Sym_Range> SymsOrError =
5805               Obj.symbols(this->DotSymtabSec)) {
5806         uint32_t Index = (uint32_t)-1;
5807         for (const Elf_Sym &Sym : *SymsOrError) {
5808           ++Index;
5809 
5810           if (Sym.st_shndx == ELF::SHN_UNDEF || Sym.getType() != ELF::STT_FUNC)
5811             continue;
5812 
5813           Expected<uint64_t> SymAddrOrErr =
5814               ObjF.toSymbolRef(this->DotSymtabSec, Index).getAddress();
5815           if (!SymAddrOrErr) {
5816             std::string Name = this->getStaticSymbolName(Index);
5817             reportUniqueWarning("unable to get address of symbol '" + Name +
5818                                 "': " + toString(SymAddrOrErr.takeError()));
5819             return SymbolIndexes;
5820           }
5821 
5822           (*this->AddressToIndexMap)[*SymAddrOrErr].push_back(Index);
5823         }
5824       } else {
5825         reportUniqueWarning("unable to read the symbol table: " +
5826                             toString(SymsOrError.takeError()));
5827       }
5828     }
5829   }
5830 
5831   auto Symbols = this->AddressToIndexMap->find(SymValue);
5832   if (Symbols == this->AddressToIndexMap->end())
5833     return SymbolIndexes;
5834 
5835   for (uint32_t Index : Symbols->second) {
5836     // Check if the symbol is in the right section. FunctionSec == None
5837     // means "any section".
5838     if (FunctionSec) {
5839       const Elf_Sym &Sym = *cantFail(Obj.getSymbol(this->DotSymtabSec, Index));
5840       if (Expected<const Elf_Shdr *> SecOrErr =
5841               Obj.getSection(Sym, this->DotSymtabSec,
5842                              this->getShndxTable(this->DotSymtabSec))) {
5843         if (*FunctionSec != *SecOrErr)
5844           continue;
5845       } else {
5846         std::string Name = this->getStaticSymbolName(Index);
5847         // Note: it is impossible to trigger this error currently, it is
5848         // untested.
5849         reportUniqueWarning("unable to get section of symbol '" + Name +
5850                             "': " + toString(SecOrErr.takeError()));
5851         return SymbolIndexes;
5852       }
5853     }
5854 
5855     SymbolIndexes.push_back(Index);
5856   }
5857 
5858   return SymbolIndexes;
5859 }
5860 
5861 template <class ELFT>
5862 bool ELFDumper<ELFT>::printFunctionStackSize(
5863     uint64_t SymValue, Optional<const Elf_Shdr *> FunctionSec,
5864     const Elf_Shdr &StackSizeSec, DataExtractor Data, uint64_t *Offset) {
5865   SmallVector<uint32_t> FuncSymIndexes =
5866       this->getSymbolIndexesForFunctionAddress(SymValue, FunctionSec);
5867   if (FuncSymIndexes.empty())
5868     reportUniqueWarning(
5869         "could not identify function symbol for stack size entry in " +
5870         describe(StackSizeSec));
5871 
5872   // Extract the size. The expectation is that Offset is pointing to the right
5873   // place, i.e. past the function address.
5874   Error Err = Error::success();
5875   uint64_t StackSize = Data.getULEB128(Offset, &Err);
5876   if (Err) {
5877     reportUniqueWarning("could not extract a valid stack size from " +
5878                         describe(StackSizeSec) + ": " +
5879                         toString(std::move(Err)));
5880     return false;
5881   }
5882 
5883   if (FuncSymIndexes.empty()) {
5884     printStackSizeEntry(StackSize, {"?"});
5885   } else {
5886     SmallVector<std::string> FuncSymNames;
5887     for (uint32_t Index : FuncSymIndexes)
5888       FuncSymNames.push_back(this->getStaticSymbolName(Index));
5889     printStackSizeEntry(StackSize, FuncSymNames);
5890   }
5891 
5892   return true;
5893 }
5894 
5895 template <class ELFT>
5896 void GNUELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
5897                                              ArrayRef<std::string> FuncNames) {
5898   OS.PadToColumn(2);
5899   OS << format_decimal(Size, 11);
5900   OS.PadToColumn(18);
5901 
5902   OS << join(FuncNames.begin(), FuncNames.end(), ", ") << "\n";
5903 }
5904 
5905 template <class ELFT>
5906 void ELFDumper<ELFT>::printStackSize(const Relocation<ELFT> &R,
5907                                      const Elf_Shdr &RelocSec, unsigned Ndx,
5908                                      const Elf_Shdr *SymTab,
5909                                      const Elf_Shdr *FunctionSec,
5910                                      const Elf_Shdr &StackSizeSec,
5911                                      const RelocationResolver &Resolver,
5912                                      DataExtractor Data) {
5913   // This function ignores potentially erroneous input, unless it is directly
5914   // related to stack size reporting.
5915   const Elf_Sym *Sym = nullptr;
5916   Expected<RelSymbol<ELFT>> TargetOrErr = this->getRelocationTarget(R, SymTab);
5917   if (!TargetOrErr)
5918     reportUniqueWarning("unable to get the target of relocation with index " +
5919                         Twine(Ndx) + " in " + describe(RelocSec) + ": " +
5920                         toString(TargetOrErr.takeError()));
5921   else
5922     Sym = TargetOrErr->Sym;
5923 
5924   uint64_t RelocSymValue = 0;
5925   if (Sym) {
5926     Expected<const Elf_Shdr *> SectionOrErr =
5927         this->Obj.getSection(*Sym, SymTab, this->getShndxTable(SymTab));
5928     if (!SectionOrErr) {
5929       reportUniqueWarning(
5930           "cannot identify the section for relocation symbol '" +
5931           (*TargetOrErr).Name + "': " + toString(SectionOrErr.takeError()));
5932     } else if (*SectionOrErr != FunctionSec) {
5933       reportUniqueWarning("relocation symbol '" + (*TargetOrErr).Name +
5934                           "' is not in the expected section");
5935       // Pretend that the symbol is in the correct section and report its
5936       // stack size anyway.
5937       FunctionSec = *SectionOrErr;
5938     }
5939 
5940     RelocSymValue = Sym->st_value;
5941   }
5942 
5943   uint64_t Offset = R.Offset;
5944   if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
5945     reportUniqueWarning("found invalid relocation offset (0x" +
5946                         Twine::utohexstr(Offset) + ") into " +
5947                         describe(StackSizeSec) +
5948                         " while trying to extract a stack size entry");
5949     return;
5950   }
5951 
5952   uint64_t SymValue =
5953       Resolver(R.Type, Offset, RelocSymValue, Data.getAddress(&Offset),
5954                R.Addend.getValueOr(0));
5955   this->printFunctionStackSize(SymValue, FunctionSec, StackSizeSec, Data,
5956                                &Offset);
5957 }
5958 
5959 template <class ELFT>
5960 void ELFDumper<ELFT>::printNonRelocatableStackSizes(
5961     std::function<void()> PrintHeader) {
5962   // This function ignores potentially erroneous input, unless it is directly
5963   // related to stack size reporting.
5964   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
5965     if (this->getPrintableSectionName(Sec) != ".stack_sizes")
5966       continue;
5967     PrintHeader();
5968     ArrayRef<uint8_t> Contents =
5969         unwrapOrError(this->FileName, Obj.getSectionContents(Sec));
5970     DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
5971     uint64_t Offset = 0;
5972     while (Offset < Contents.size()) {
5973       // The function address is followed by a ULEB representing the stack
5974       // size. Check for an extra byte before we try to process the entry.
5975       if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
5976         reportUniqueWarning(
5977             describe(Sec) +
5978             " ended while trying to extract a stack size entry");
5979         break;
5980       }
5981       uint64_t SymValue = Data.getAddress(&Offset);
5982       if (!printFunctionStackSize(SymValue, /*FunctionSec=*/None, Sec, Data,
5983                                   &Offset))
5984         break;
5985     }
5986   }
5987 }
5988 
5989 template <class ELFT>
5990 void ELFDumper<ELFT>::getSectionAndRelocations(
5991     std::function<bool(const Elf_Shdr &)> IsMatch,
5992     llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> &SecToRelocMap) {
5993   for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
5994     if (IsMatch(Sec))
5995       if (SecToRelocMap.insert(std::make_pair(&Sec, (const Elf_Shdr *)nullptr))
5996               .second)
5997         continue;
5998 
5999     if (Sec.sh_type != ELF::SHT_RELA && Sec.sh_type != ELF::SHT_REL)
6000       continue;
6001 
6002     Expected<const Elf_Shdr *> RelSecOrErr = Obj.getSection(Sec.sh_info);
6003     if (!RelSecOrErr) {
6004       reportUniqueWarning(describe(Sec) +
6005                           ": failed to get a relocated section: " +
6006                           toString(RelSecOrErr.takeError()));
6007       continue;
6008     }
6009     const Elf_Shdr *ContentsSec = *RelSecOrErr;
6010     if (IsMatch(*ContentsSec))
6011       SecToRelocMap[ContentsSec] = &Sec;
6012   }
6013 }
6014 
6015 template <class ELFT>
6016 void ELFDumper<ELFT>::printRelocatableStackSizes(
6017     std::function<void()> PrintHeader) {
6018   // Build a map between stack size sections and their corresponding relocation
6019   // sections.
6020   llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> StackSizeRelocMap;
6021   auto IsMatch = [&](const Elf_Shdr &Sec) -> bool {
6022     StringRef SectionName;
6023     if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec))
6024       SectionName = *NameOrErr;
6025     else
6026       consumeError(NameOrErr.takeError());
6027 
6028     return SectionName == ".stack_sizes";
6029   };
6030   getSectionAndRelocations(IsMatch, StackSizeRelocMap);
6031 
6032   for (const auto &StackSizeMapEntry : StackSizeRelocMap) {
6033     PrintHeader();
6034     const Elf_Shdr *StackSizesELFSec = StackSizeMapEntry.first;
6035     const Elf_Shdr *RelocSec = StackSizeMapEntry.second;
6036 
6037     // Warn about stack size sections without a relocation section.
6038     if (!RelocSec) {
6039       reportWarning(createError(".stack_sizes (" + describe(*StackSizesELFSec) +
6040                                 ") does not have a corresponding "
6041                                 "relocation section"),
6042                     FileName);
6043       continue;
6044     }
6045 
6046     // A .stack_sizes section header's sh_link field is supposed to point
6047     // to the section that contains the functions whose stack sizes are
6048     // described in it.
6049     const Elf_Shdr *FunctionSec = unwrapOrError(
6050         this->FileName, Obj.getSection(StackSizesELFSec->sh_link));
6051 
6052     SupportsRelocation IsSupportedFn;
6053     RelocationResolver Resolver;
6054     std::tie(IsSupportedFn, Resolver) = getRelocationResolver(this->ObjF);
6055     ArrayRef<uint8_t> Contents =
6056         unwrapOrError(this->FileName, Obj.getSectionContents(*StackSizesELFSec));
6057     DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
6058 
6059     forEachRelocationDo(
6060         *RelocSec, /*RawRelr=*/false,
6061         [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
6062             const Elf_Shdr *SymTab) {
6063           if (!IsSupportedFn || !IsSupportedFn(R.Type)) {
6064             reportUniqueWarning(
6065                 describe(*RelocSec) +
6066                 " contains an unsupported relocation with index " + Twine(Ndx) +
6067                 ": " + Obj.getRelocationTypeName(R.Type));
6068             return;
6069           }
6070 
6071           this->printStackSize(R, *RelocSec, Ndx, SymTab, FunctionSec,
6072                                *StackSizesELFSec, Resolver, Data);
6073         },
6074         [](const Elf_Relr &) {
6075           llvm_unreachable("can't get here, because we only support "
6076                            "SHT_REL/SHT_RELA sections");
6077         });
6078   }
6079 }
6080 
6081 template <class ELFT>
6082 void GNUELFDumper<ELFT>::printStackSizes() {
6083   bool HeaderHasBeenPrinted = false;
6084   auto PrintHeader = [&]() {
6085     if (HeaderHasBeenPrinted)
6086       return;
6087     OS << "\nStack Sizes:\n";
6088     OS.PadToColumn(9);
6089     OS << "Size";
6090     OS.PadToColumn(18);
6091     OS << "Functions\n";
6092     HeaderHasBeenPrinted = true;
6093   };
6094 
6095   // For non-relocatable objects, look directly for sections whose name starts
6096   // with .stack_sizes and process the contents.
6097   if (this->Obj.getHeader().e_type == ELF::ET_REL)
6098     this->printRelocatableStackSizes(PrintHeader);
6099   else
6100     this->printNonRelocatableStackSizes(PrintHeader);
6101 }
6102 
6103 template <class ELFT>
6104 void GNUELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
6105   size_t Bias = ELFT::Is64Bits ? 8 : 0;
6106   auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
6107     OS.PadToColumn(2);
6108     OS << format_hex_no_prefix(Parser.getGotAddress(E), 8 + Bias);
6109     OS.PadToColumn(11 + Bias);
6110     OS << format_decimal(Parser.getGotOffset(E), 6) << "(gp)";
6111     OS.PadToColumn(22 + Bias);
6112     OS << format_hex_no_prefix(*E, 8 + Bias);
6113     OS.PadToColumn(31 + 2 * Bias);
6114     OS << Purpose << "\n";
6115   };
6116 
6117   OS << (Parser.IsStatic ? "Static GOT:\n" : "Primary GOT:\n");
6118   OS << " Canonical gp value: "
6119      << format_hex_no_prefix(Parser.getGp(), 8 + Bias) << "\n\n";
6120 
6121   OS << " Reserved entries:\n";
6122   if (ELFT::Is64Bits)
6123     OS << "           Address     Access          Initial Purpose\n";
6124   else
6125     OS << "   Address     Access  Initial Purpose\n";
6126   PrintEntry(Parser.getGotLazyResolver(), "Lazy resolver");
6127   if (Parser.getGotModulePointer())
6128     PrintEntry(Parser.getGotModulePointer(), "Module pointer (GNU extension)");
6129 
6130   if (!Parser.getLocalEntries().empty()) {
6131     OS << "\n";
6132     OS << " Local entries:\n";
6133     if (ELFT::Is64Bits)
6134       OS << "           Address     Access          Initial\n";
6135     else
6136       OS << "   Address     Access  Initial\n";
6137     for (auto &E : Parser.getLocalEntries())
6138       PrintEntry(&E, "");
6139   }
6140 
6141   if (Parser.IsStatic)
6142     return;
6143 
6144   if (!Parser.getGlobalEntries().empty()) {
6145     OS << "\n";
6146     OS << " Global entries:\n";
6147     if (ELFT::Is64Bits)
6148       OS << "           Address     Access          Initial         Sym.Val."
6149          << " Type    Ndx Name\n";
6150     else
6151       OS << "   Address     Access  Initial Sym.Val. Type    Ndx Name\n";
6152 
6153     DataRegion<Elf_Word> ShndxTable(
6154         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6155     for (auto &E : Parser.getGlobalEntries()) {
6156       const Elf_Sym &Sym = *Parser.getGotSym(&E);
6157       const Elf_Sym &FirstSym = this->dynamic_symbols()[0];
6158       std::string SymName = this->getFullSymbolName(
6159           Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
6160 
6161       OS.PadToColumn(2);
6162       OS << to_string(format_hex_no_prefix(Parser.getGotAddress(&E), 8 + Bias));
6163       OS.PadToColumn(11 + Bias);
6164       OS << to_string(format_decimal(Parser.getGotOffset(&E), 6)) + "(gp)";
6165       OS.PadToColumn(22 + Bias);
6166       OS << to_string(format_hex_no_prefix(E, 8 + Bias));
6167       OS.PadToColumn(31 + 2 * Bias);
6168       OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
6169       OS.PadToColumn(40 + 3 * Bias);
6170       OS << printEnum(Sym.getType(), makeArrayRef(ElfSymbolTypes));
6171       OS.PadToColumn(48 + 3 * Bias);
6172       OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
6173                                 ShndxTable);
6174       OS.PadToColumn(52 + 3 * Bias);
6175       OS << SymName << "\n";
6176     }
6177   }
6178 
6179   if (!Parser.getOtherEntries().empty())
6180     OS << "\n Number of TLS and multi-GOT entries "
6181        << Parser.getOtherEntries().size() << "\n";
6182 }
6183 
6184 template <class ELFT>
6185 void GNUELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
6186   size_t Bias = ELFT::Is64Bits ? 8 : 0;
6187   auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
6188     OS.PadToColumn(2);
6189     OS << format_hex_no_prefix(Parser.getPltAddress(E), 8 + Bias);
6190     OS.PadToColumn(11 + Bias);
6191     OS << format_hex_no_prefix(*E, 8 + Bias);
6192     OS.PadToColumn(20 + 2 * Bias);
6193     OS << Purpose << "\n";
6194   };
6195 
6196   OS << "PLT GOT:\n\n";
6197 
6198   OS << " Reserved entries:\n";
6199   OS << "   Address  Initial Purpose\n";
6200   PrintEntry(Parser.getPltLazyResolver(), "PLT lazy resolver");
6201   if (Parser.getPltModulePointer())
6202     PrintEntry(Parser.getPltModulePointer(), "Module pointer");
6203 
6204   if (!Parser.getPltEntries().empty()) {
6205     OS << "\n";
6206     OS << " Entries:\n";
6207     OS << "   Address  Initial Sym.Val. Type    Ndx Name\n";
6208     DataRegion<Elf_Word> ShndxTable(
6209         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6210     for (auto &E : Parser.getPltEntries()) {
6211       const Elf_Sym &Sym = *Parser.getPltSym(&E);
6212       const Elf_Sym &FirstSym = *cantFail(
6213           this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
6214       std::string SymName = this->getFullSymbolName(
6215           Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
6216 
6217       OS.PadToColumn(2);
6218       OS << to_string(format_hex_no_prefix(Parser.getPltAddress(&E), 8 + Bias));
6219       OS.PadToColumn(11 + Bias);
6220       OS << to_string(format_hex_no_prefix(E, 8 + Bias));
6221       OS.PadToColumn(20 + 2 * Bias);
6222       OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
6223       OS.PadToColumn(29 + 3 * Bias);
6224       OS << printEnum(Sym.getType(), makeArrayRef(ElfSymbolTypes));
6225       OS.PadToColumn(37 + 3 * Bias);
6226       OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
6227                                 ShndxTable);
6228       OS.PadToColumn(41 + 3 * Bias);
6229       OS << SymName << "\n";
6230     }
6231   }
6232 }
6233 
6234 template <class ELFT>
6235 Expected<const Elf_Mips_ABIFlags<ELFT> *>
6236 getMipsAbiFlagsSection(const ELFDumper<ELFT> &Dumper) {
6237   const typename ELFT::Shdr *Sec = Dumper.findSectionByName(".MIPS.abiflags");
6238   if (Sec == nullptr)
6239     return nullptr;
6240 
6241   constexpr StringRef ErrPrefix = "unable to read the .MIPS.abiflags section: ";
6242   Expected<ArrayRef<uint8_t>> DataOrErr =
6243       Dumper.getElfObject().getELFFile().getSectionContents(*Sec);
6244   if (!DataOrErr)
6245     return createError(ErrPrefix + toString(DataOrErr.takeError()));
6246 
6247   if (DataOrErr->size() != sizeof(Elf_Mips_ABIFlags<ELFT>))
6248     return createError(ErrPrefix + "it has a wrong size (" +
6249         Twine(DataOrErr->size()) + ")");
6250   return reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(DataOrErr->data());
6251 }
6252 
6253 template <class ELFT> void GNUELFDumper<ELFT>::printMipsABIFlags() {
6254   const Elf_Mips_ABIFlags<ELFT> *Flags = nullptr;
6255   if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
6256           getMipsAbiFlagsSection(*this))
6257     Flags = *SecOrErr;
6258   else
6259     this->reportUniqueWarning(SecOrErr.takeError());
6260   if (!Flags)
6261     return;
6262 
6263   OS << "MIPS ABI Flags Version: " << Flags->version << "\n\n";
6264   OS << "ISA: MIPS" << int(Flags->isa_level);
6265   if (Flags->isa_rev > 1)
6266     OS << "r" << int(Flags->isa_rev);
6267   OS << "\n";
6268   OS << "GPR size: " << getMipsRegisterSize(Flags->gpr_size) << "\n";
6269   OS << "CPR1 size: " << getMipsRegisterSize(Flags->cpr1_size) << "\n";
6270   OS << "CPR2 size: " << getMipsRegisterSize(Flags->cpr2_size) << "\n";
6271   OS << "FP ABI: " << printEnum(Flags->fp_abi, makeArrayRef(ElfMipsFpABIType))
6272      << "\n";
6273   OS << "ISA Extension: "
6274      << printEnum(Flags->isa_ext, makeArrayRef(ElfMipsISAExtType)) << "\n";
6275   if (Flags->ases == 0)
6276     OS << "ASEs: None\n";
6277   else
6278     // FIXME: Print each flag on a separate line.
6279     OS << "ASEs: " << printFlags(Flags->ases, makeArrayRef(ElfMipsASEFlags))
6280        << "\n";
6281   OS << "FLAGS 1: " << format_hex_no_prefix(Flags->flags1, 8, false) << "\n";
6282   OS << "FLAGS 2: " << format_hex_no_prefix(Flags->flags2, 8, false) << "\n";
6283   OS << "\n";
6284 }
6285 
6286 template <class ELFT> void LLVMELFDumper<ELFT>::printFileHeaders() {
6287   const Elf_Ehdr &E = this->Obj.getHeader();
6288   {
6289     DictScope D(W, "ElfHeader");
6290     {
6291       DictScope D(W, "Ident");
6292       W.printBinary("Magic", makeArrayRef(E.e_ident).slice(ELF::EI_MAG0, 4));
6293       W.printEnum("Class", E.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass));
6294       W.printEnum("DataEncoding", E.e_ident[ELF::EI_DATA],
6295                   makeArrayRef(ElfDataEncoding));
6296       W.printNumber("FileVersion", E.e_ident[ELF::EI_VERSION]);
6297 
6298       auto OSABI = makeArrayRef(ElfOSABI);
6299       if (E.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH &&
6300           E.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) {
6301         switch (E.e_machine) {
6302         case ELF::EM_AMDGPU:
6303           OSABI = makeArrayRef(AMDGPUElfOSABI);
6304           break;
6305         case ELF::EM_ARM:
6306           OSABI = makeArrayRef(ARMElfOSABI);
6307           break;
6308         case ELF::EM_TI_C6000:
6309           OSABI = makeArrayRef(C6000ElfOSABI);
6310           break;
6311         }
6312       }
6313       W.printEnum("OS/ABI", E.e_ident[ELF::EI_OSABI], OSABI);
6314       W.printNumber("ABIVersion", E.e_ident[ELF::EI_ABIVERSION]);
6315       W.printBinary("Unused", makeArrayRef(E.e_ident).slice(ELF::EI_PAD));
6316     }
6317 
6318     std::string TypeStr;
6319     if (const EnumEntry<unsigned> *Ent = getObjectFileEnumEntry(E.e_type)) {
6320       TypeStr = Ent->Name.str();
6321     } else {
6322       if (E.e_type >= ET_LOPROC)
6323         TypeStr = "Processor Specific";
6324       else if (E.e_type >= ET_LOOS)
6325         TypeStr = "OS Specific";
6326       else
6327         TypeStr = "Unknown";
6328     }
6329     W.printString("Type", TypeStr + " (0x" + to_hexString(E.e_type) + ")");
6330 
6331     W.printEnum("Machine", E.e_machine, makeArrayRef(ElfMachineType));
6332     W.printNumber("Version", E.e_version);
6333     W.printHex("Entry", E.e_entry);
6334     W.printHex("ProgramHeaderOffset", E.e_phoff);
6335     W.printHex("SectionHeaderOffset", E.e_shoff);
6336     if (E.e_machine == EM_MIPS)
6337       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderMipsFlags),
6338                    unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
6339                    unsigned(ELF::EF_MIPS_MACH));
6340     else if (E.e_machine == EM_AMDGPU) {
6341       switch (E.e_ident[ELF::EI_ABIVERSION]) {
6342       default:
6343         W.printHex("Flags", E.e_flags);
6344         break;
6345       case 0:
6346         // ELFOSABI_AMDGPU_PAL, ELFOSABI_AMDGPU_MESA3D support *_V3 flags.
6347         LLVM_FALLTHROUGH;
6348       case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
6349         W.printFlags("Flags", E.e_flags,
6350                      makeArrayRef(ElfHeaderAMDGPUFlagsABIVersion3),
6351                      unsigned(ELF::EF_AMDGPU_MACH));
6352         break;
6353       case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
6354         W.printFlags("Flags", E.e_flags,
6355                      makeArrayRef(ElfHeaderAMDGPUFlagsABIVersion4),
6356                      unsigned(ELF::EF_AMDGPU_MACH),
6357                      unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
6358                      unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
6359         break;
6360       }
6361     } else if (E.e_machine == EM_RISCV)
6362       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderRISCVFlags));
6363     else if (E.e_machine == EM_AVR)
6364       W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderAVRFlags),
6365                    unsigned(ELF::EF_AVR_ARCH_MASK));
6366     else
6367       W.printFlags("Flags", E.e_flags);
6368     W.printNumber("HeaderSize", E.e_ehsize);
6369     W.printNumber("ProgramHeaderEntrySize", E.e_phentsize);
6370     W.printNumber("ProgramHeaderCount", E.e_phnum);
6371     W.printNumber("SectionHeaderEntrySize", E.e_shentsize);
6372     W.printString("SectionHeaderCount",
6373                   getSectionHeadersNumString(this->Obj, this->FileName));
6374     W.printString("StringTableSectionIndex",
6375                   getSectionHeaderTableIndexString(this->Obj, this->FileName));
6376   }
6377 }
6378 
6379 template <class ELFT> void LLVMELFDumper<ELFT>::printGroupSections() {
6380   DictScope Lists(W, "Groups");
6381   std::vector<GroupSection> V = this->getGroups();
6382   DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
6383   for (const GroupSection &G : V) {
6384     DictScope D(W, "Group");
6385     W.printNumber("Name", G.Name, G.ShName);
6386     W.printNumber("Index", G.Index);
6387     W.printNumber("Link", G.Link);
6388     W.printNumber("Info", G.Info);
6389     W.printHex("Type", getGroupType(G.Type), G.Type);
6390     W.startLine() << "Signature: " << G.Signature << "\n";
6391 
6392     ListScope L(W, "Section(s) in group");
6393     for (const GroupMember &GM : G.Members) {
6394       const GroupSection *MainGroup = Map[GM.Index];
6395       if (MainGroup != &G)
6396         this->reportUniqueWarning(
6397             "section with index " + Twine(GM.Index) +
6398             ", included in the group section with index " +
6399             Twine(MainGroup->Index) +
6400             ", was also found in the group section with index " +
6401             Twine(G.Index));
6402       W.startLine() << GM.Name << " (" << GM.Index << ")\n";
6403     }
6404   }
6405 
6406   if (V.empty())
6407     W.startLine() << "There are no group sections in the file.\n";
6408 }
6409 
6410 template <class ELFT> void LLVMELFDumper<ELFT>::printRelocations() {
6411   ListScope D(W, "Relocations");
6412 
6413   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6414     if (!isRelocationSec<ELFT>(Sec))
6415       continue;
6416 
6417     StringRef Name = this->getPrintableSectionName(Sec);
6418     unsigned SecNdx = &Sec - &cantFail(this->Obj.sections()).front();
6419     W.startLine() << "Section (" << SecNdx << ") " << Name << " {\n";
6420     W.indent();
6421     this->printRelocationsHelper(Sec);
6422     W.unindent();
6423     W.startLine() << "}\n";
6424   }
6425 }
6426 
6427 template <class ELFT>
6428 void LLVMELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
6429   W.startLine() << W.hex(R) << "\n";
6430 }
6431 
6432 template <class ELFT>
6433 void LLVMELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
6434                                             const RelSymbol<ELFT> &RelSym) {
6435   StringRef SymbolName = RelSym.Name;
6436   SmallString<32> RelocName;
6437   this->Obj.getRelocationTypeName(R.Type, RelocName);
6438 
6439   if (opts::ExpandRelocs) {
6440     DictScope Group(W, "Relocation");
6441     W.printHex("Offset", R.Offset);
6442     W.printNumber("Type", RelocName, R.Type);
6443     W.printNumber("Symbol", !SymbolName.empty() ? SymbolName : "-", R.Symbol);
6444     if (R.Addend)
6445       W.printHex("Addend", (uintX_t)*R.Addend);
6446   } else {
6447     raw_ostream &OS = W.startLine();
6448     OS << W.hex(R.Offset) << " " << RelocName << " "
6449        << (!SymbolName.empty() ? SymbolName : "-");
6450     if (R.Addend)
6451       OS << " " << W.hex((uintX_t)*R.Addend);
6452     OS << "\n";
6453   }
6454 }
6455 
6456 template <class ELFT> void LLVMELFDumper<ELFT>::printSectionHeaders() {
6457   ListScope SectionsD(W, "Sections");
6458 
6459   int SectionIndex = -1;
6460   std::vector<EnumEntry<unsigned>> FlagsList =
6461       getSectionFlagsForTarget(this->Obj.getHeader().e_machine);
6462   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6463     DictScope SectionD(W, "Section");
6464     W.printNumber("Index", ++SectionIndex);
6465     W.printNumber("Name", this->getPrintableSectionName(Sec), Sec.sh_name);
6466     W.printHex("Type",
6467                object::getELFSectionTypeName(this->Obj.getHeader().e_machine,
6468                                              Sec.sh_type),
6469                Sec.sh_type);
6470     W.printFlags("Flags", Sec.sh_flags, makeArrayRef(FlagsList));
6471     W.printHex("Address", Sec.sh_addr);
6472     W.printHex("Offset", Sec.sh_offset);
6473     W.printNumber("Size", Sec.sh_size);
6474     W.printNumber("Link", Sec.sh_link);
6475     W.printNumber("Info", Sec.sh_info);
6476     W.printNumber("AddressAlignment", Sec.sh_addralign);
6477     W.printNumber("EntrySize", Sec.sh_entsize);
6478 
6479     if (opts::SectionRelocations) {
6480       ListScope D(W, "Relocations");
6481       this->printRelocationsHelper(Sec);
6482     }
6483 
6484     if (opts::SectionSymbols) {
6485       ListScope D(W, "Symbols");
6486       if (this->DotSymtabSec) {
6487         StringRef StrTable = unwrapOrError(
6488             this->FileName,
6489             this->Obj.getStringTableForSymtab(*this->DotSymtabSec));
6490         ArrayRef<Elf_Word> ShndxTable = this->getShndxTable(this->DotSymtabSec);
6491 
6492         typename ELFT::SymRange Symbols = unwrapOrError(
6493             this->FileName, this->Obj.symbols(this->DotSymtabSec));
6494         for (const Elf_Sym &Sym : Symbols) {
6495           const Elf_Shdr *SymSec = unwrapOrError(
6496               this->FileName,
6497               this->Obj.getSection(Sym, this->DotSymtabSec, ShndxTable));
6498           if (SymSec == &Sec)
6499             printSymbol(Sym, &Sym - &Symbols[0], ShndxTable, StrTable, false,
6500                         false);
6501         }
6502       }
6503     }
6504 
6505     if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) {
6506       ArrayRef<uint8_t> Data =
6507           unwrapOrError(this->FileName, this->Obj.getSectionContents(Sec));
6508       W.printBinaryBlock(
6509           "SectionData",
6510           StringRef(reinterpret_cast<const char *>(Data.data()), Data.size()));
6511     }
6512   }
6513 }
6514 
6515 template <class ELFT>
6516 void LLVMELFDumper<ELFT>::printSymbolSection(
6517     const Elf_Sym &Symbol, unsigned SymIndex,
6518     DataRegion<Elf_Word> ShndxTable) const {
6519   auto GetSectionSpecialType = [&]() -> Optional<StringRef> {
6520     if (Symbol.isUndefined())
6521       return StringRef("Undefined");
6522     if (Symbol.isProcessorSpecific())
6523       return StringRef("Processor Specific");
6524     if (Symbol.isOSSpecific())
6525       return StringRef("Operating System Specific");
6526     if (Symbol.isAbsolute())
6527       return StringRef("Absolute");
6528     if (Symbol.isCommon())
6529       return StringRef("Common");
6530     if (Symbol.isReserved() && Symbol.st_shndx != SHN_XINDEX)
6531       return StringRef("Reserved");
6532     return None;
6533   };
6534 
6535   if (Optional<StringRef> Type = GetSectionSpecialType()) {
6536     W.printHex("Section", *Type, Symbol.st_shndx);
6537     return;
6538   }
6539 
6540   Expected<unsigned> SectionIndex =
6541       this->getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
6542   if (!SectionIndex) {
6543     assert(Symbol.st_shndx == SHN_XINDEX &&
6544            "getSymbolSectionIndex should only fail due to an invalid "
6545            "SHT_SYMTAB_SHNDX table/reference");
6546     this->reportUniqueWarning(SectionIndex.takeError());
6547     W.printHex("Section", "Reserved", SHN_XINDEX);
6548     return;
6549   }
6550 
6551   Expected<StringRef> SectionName =
6552       this->getSymbolSectionName(Symbol, *SectionIndex);
6553   if (!SectionName) {
6554     // Don't report an invalid section name if the section headers are missing.
6555     // In such situations, all sections will be "invalid".
6556     if (!this->ObjF.sections().empty())
6557       this->reportUniqueWarning(SectionName.takeError());
6558     else
6559       consumeError(SectionName.takeError());
6560     W.printHex("Section", "<?>", *SectionIndex);
6561   } else {
6562     W.printHex("Section", *SectionName, *SectionIndex);
6563   }
6564 }
6565 
6566 template <class ELFT>
6567 void LLVMELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
6568                                       DataRegion<Elf_Word> ShndxTable,
6569                                       Optional<StringRef> StrTable,
6570                                       bool IsDynamic,
6571                                       bool /*NonVisibilityBitsUsed*/) const {
6572   std::string FullSymbolName = this->getFullSymbolName(
6573       Symbol, SymIndex, ShndxTable, StrTable, IsDynamic);
6574   unsigned char SymbolType = Symbol.getType();
6575 
6576   DictScope D(W, "Symbol");
6577   W.printNumber("Name", FullSymbolName, Symbol.st_name);
6578   W.printHex("Value", Symbol.st_value);
6579   W.printNumber("Size", Symbol.st_size);
6580   W.printEnum("Binding", Symbol.getBinding(), makeArrayRef(ElfSymbolBindings));
6581   if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
6582       SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
6583     W.printEnum("Type", SymbolType, makeArrayRef(AMDGPUSymbolTypes));
6584   else
6585     W.printEnum("Type", SymbolType, makeArrayRef(ElfSymbolTypes));
6586   if (Symbol.st_other == 0)
6587     // Usually st_other flag is zero. Do not pollute the output
6588     // by flags enumeration in that case.
6589     W.printNumber("Other", 0);
6590   else {
6591     std::vector<EnumEntry<unsigned>> SymOtherFlags(std::begin(ElfSymOtherFlags),
6592                                                    std::end(ElfSymOtherFlags));
6593     if (this->Obj.getHeader().e_machine == EM_MIPS) {
6594       // Someones in their infinite wisdom decided to make STO_MIPS_MIPS16
6595       // flag overlapped with other ST_MIPS_xxx flags. So consider both
6596       // cases separately.
6597       if ((Symbol.st_other & STO_MIPS_MIPS16) == STO_MIPS_MIPS16)
6598         SymOtherFlags.insert(SymOtherFlags.end(),
6599                              std::begin(ElfMips16SymOtherFlags),
6600                              std::end(ElfMips16SymOtherFlags));
6601       else
6602         SymOtherFlags.insert(SymOtherFlags.end(),
6603                              std::begin(ElfMipsSymOtherFlags),
6604                              std::end(ElfMipsSymOtherFlags));
6605     } else if (this->Obj.getHeader().e_machine == EM_AARCH64) {
6606       SymOtherFlags.insert(SymOtherFlags.end(),
6607                            std::begin(ElfAArch64SymOtherFlags),
6608                            std::end(ElfAArch64SymOtherFlags));
6609     } else if (this->Obj.getHeader().e_machine == EM_RISCV) {
6610       SymOtherFlags.insert(SymOtherFlags.end(),
6611                            std::begin(ElfRISCVSymOtherFlags),
6612                            std::end(ElfRISCVSymOtherFlags));
6613     }
6614     W.printFlags("Other", Symbol.st_other, makeArrayRef(SymOtherFlags), 0x3u);
6615   }
6616   printSymbolSection(Symbol, SymIndex, ShndxTable);
6617 }
6618 
6619 template <class ELFT>
6620 void LLVMELFDumper<ELFT>::printSymbols(bool PrintSymbols,
6621                                        bool PrintDynamicSymbols) {
6622   if (PrintSymbols) {
6623     ListScope Group(W, "Symbols");
6624     this->printSymbolsHelper(false);
6625   }
6626   if (PrintDynamicSymbols) {
6627     ListScope Group(W, "DynamicSymbols");
6628     this->printSymbolsHelper(true);
6629   }
6630 }
6631 
6632 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicTable() {
6633   Elf_Dyn_Range Table = this->dynamic_table();
6634   if (Table.empty())
6635     return;
6636 
6637   W.startLine() << "DynamicSection [ (" << Table.size() << " entries)\n";
6638 
6639   size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table);
6640   // The "Name/Value" column should be indented from the "Type" column by N
6641   // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
6642   // space (1) = -3.
6643   W.startLine() << "  Tag" << std::string(ELFT::Is64Bits ? 16 : 8, ' ')
6644                 << "Type" << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
6645 
6646   std::string ValueFmt = "%-" + std::to_string(MaxTagSize) + "s ";
6647   for (auto Entry : Table) {
6648     uintX_t Tag = Entry.getTag();
6649     std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
6650     W.startLine() << "  " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10, true)
6651                   << " "
6652                   << format(ValueFmt.c_str(),
6653                             this->Obj.getDynamicTagAsString(Tag).c_str())
6654                   << Value << "\n";
6655   }
6656   W.startLine() << "]\n";
6657 }
6658 
6659 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicRelocations() {
6660   W.startLine() << "Dynamic Relocations {\n";
6661   W.indent();
6662   this->printDynamicRelocationsHelper();
6663   W.unindent();
6664   W.startLine() << "}\n";
6665 }
6666 
6667 template <class ELFT>
6668 void LLVMELFDumper<ELFT>::printProgramHeaders(
6669     bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
6670   if (PrintProgramHeaders)
6671     printProgramHeaders();
6672   if (PrintSectionMapping == cl::BOU_TRUE)
6673     printSectionMapping();
6674 }
6675 
6676 template <class ELFT> void LLVMELFDumper<ELFT>::printProgramHeaders() {
6677   ListScope L(W, "ProgramHeaders");
6678 
6679   Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
6680   if (!PhdrsOrErr) {
6681     this->reportUniqueWarning("unable to dump program headers: " +
6682                               toString(PhdrsOrErr.takeError()));
6683     return;
6684   }
6685 
6686   for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
6687     DictScope P(W, "ProgramHeader");
6688     StringRef Type =
6689         segmentTypeToString(this->Obj.getHeader().e_machine, Phdr.p_type);
6690 
6691     W.printHex("Type", Type.empty() ? "Unknown" : Type, Phdr.p_type);
6692     W.printHex("Offset", Phdr.p_offset);
6693     W.printHex("VirtualAddress", Phdr.p_vaddr);
6694     W.printHex("PhysicalAddress", Phdr.p_paddr);
6695     W.printNumber("FileSize", Phdr.p_filesz);
6696     W.printNumber("MemSize", Phdr.p_memsz);
6697     W.printFlags("Flags", Phdr.p_flags, makeArrayRef(ElfSegmentFlags));
6698     W.printNumber("Alignment", Phdr.p_align);
6699   }
6700 }
6701 
6702 template <class ELFT>
6703 void LLVMELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
6704   ListScope SS(W, "VersionSymbols");
6705   if (!Sec)
6706     return;
6707 
6708   StringRef StrTable;
6709   ArrayRef<Elf_Sym> Syms;
6710   const Elf_Shdr *SymTabSec;
6711   Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
6712       this->getVersionTable(*Sec, &Syms, &StrTable, &SymTabSec);
6713   if (!VerTableOrErr) {
6714     this->reportUniqueWarning(VerTableOrErr.takeError());
6715     return;
6716   }
6717 
6718   if (StrTable.empty() || Syms.empty() || Syms.size() != VerTableOrErr->size())
6719     return;
6720 
6721   ArrayRef<Elf_Word> ShNdxTable = this->getShndxTable(SymTabSec);
6722   for (size_t I = 0, E = Syms.size(); I < E; ++I) {
6723     DictScope S(W, "Symbol");
6724     W.printNumber("Version", (*VerTableOrErr)[I].vs_index & VERSYM_VERSION);
6725     W.printString("Name",
6726                   this->getFullSymbolName(Syms[I], I, ShNdxTable, StrTable,
6727                                           /*IsDynamic=*/true));
6728   }
6729 }
6730 
6731 const EnumEntry<unsigned> SymVersionFlags[] = {
6732     {"Base", "BASE", VER_FLG_BASE},
6733     {"Weak", "WEAK", VER_FLG_WEAK},
6734     {"Info", "INFO", VER_FLG_INFO}};
6735 
6736 template <class ELFT>
6737 void LLVMELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
6738   ListScope SD(W, "VersionDefinitions");
6739   if (!Sec)
6740     return;
6741 
6742   Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
6743   if (!V) {
6744     this->reportUniqueWarning(V.takeError());
6745     return;
6746   }
6747 
6748   for (const VerDef &D : *V) {
6749     DictScope Def(W, "Definition");
6750     W.printNumber("Version", D.Version);
6751     W.printFlags("Flags", D.Flags, makeArrayRef(SymVersionFlags));
6752     W.printNumber("Index", D.Ndx);
6753     W.printNumber("Hash", D.Hash);
6754     W.printString("Name", D.Name.c_str());
6755     W.printList(
6756         "Predecessors", D.AuxV,
6757         [](raw_ostream &OS, const VerdAux &Aux) { OS << Aux.Name.c_str(); });
6758   }
6759 }
6760 
6761 template <class ELFT>
6762 void LLVMELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
6763   ListScope SD(W, "VersionRequirements");
6764   if (!Sec)
6765     return;
6766 
6767   Expected<std::vector<VerNeed>> V =
6768       this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
6769   if (!V) {
6770     this->reportUniqueWarning(V.takeError());
6771     return;
6772   }
6773 
6774   for (const VerNeed &VN : *V) {
6775     DictScope Entry(W, "Dependency");
6776     W.printNumber("Version", VN.Version);
6777     W.printNumber("Count", VN.Cnt);
6778     W.printString("FileName", VN.File.c_str());
6779 
6780     ListScope L(W, "Entries");
6781     for (const VernAux &Aux : VN.AuxV) {
6782       DictScope Entry(W, "Entry");
6783       W.printNumber("Hash", Aux.Hash);
6784       W.printFlags("Flags", Aux.Flags, makeArrayRef(SymVersionFlags));
6785       W.printNumber("Index", Aux.Other);
6786       W.printString("Name", Aux.Name.c_str());
6787     }
6788   }
6789 }
6790 
6791 template <class ELFT> void LLVMELFDumper<ELFT>::printHashHistograms() {
6792   W.startLine() << "Hash Histogram not implemented!\n";
6793 }
6794 
6795 // Returns true if rel/rela section exists, and populates SymbolIndices.
6796 // Otherwise returns false.
6797 template <class ELFT>
6798 static bool getSymbolIndices(const typename ELFT::Shdr *CGRelSection,
6799                              const ELFFile<ELFT> &Obj,
6800                              const LLVMELFDumper<ELFT> *Dumper,
6801                              SmallVector<uint32_t, 128> &SymbolIndices) {
6802   if (!CGRelSection) {
6803     Dumper->reportUniqueWarning(
6804         "relocation section for a call graph section doesn't exist");
6805     return false;
6806   }
6807 
6808   if (CGRelSection->sh_type == SHT_REL) {
6809     typename ELFT::RelRange CGProfileRel;
6810     Expected<typename ELFT::RelRange> CGProfileRelOrError =
6811         Obj.rels(*CGRelSection);
6812     if (!CGProfileRelOrError) {
6813       Dumper->reportUniqueWarning("unable to load relocations for "
6814                                   "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
6815                                   toString(CGProfileRelOrError.takeError()));
6816       return false;
6817     }
6818 
6819     CGProfileRel = *CGProfileRelOrError;
6820     for (const typename ELFT::Rel &Rel : CGProfileRel)
6821       SymbolIndices.push_back(Rel.getSymbol(Obj.isMips64EL()));
6822   } else {
6823     // MC unconditionally produces SHT_REL, but GNU strip/objcopy may convert
6824     // the format to SHT_RELA
6825     // (https://sourceware.org/bugzilla/show_bug.cgi?id=28035)
6826     typename ELFT::RelaRange CGProfileRela;
6827     Expected<typename ELFT::RelaRange> CGProfileRelaOrError =
6828         Obj.relas(*CGRelSection);
6829     if (!CGProfileRelaOrError) {
6830       Dumper->reportUniqueWarning("unable to load relocations for "
6831                                   "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
6832                                   toString(CGProfileRelaOrError.takeError()));
6833       return false;
6834     }
6835 
6836     CGProfileRela = *CGProfileRelaOrError;
6837     for (const typename ELFT::Rela &Rela : CGProfileRela)
6838       SymbolIndices.push_back(Rela.getSymbol(Obj.isMips64EL()));
6839   }
6840 
6841   return true;
6842 }
6843 
6844 template <class ELFT> void LLVMELFDumper<ELFT>::printCGProfile() {
6845   llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> SecToRelocMap;
6846 
6847   auto IsMatch = [](const Elf_Shdr &Sec) -> bool {
6848     return Sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE;
6849   };
6850   this->getSectionAndRelocations(IsMatch, SecToRelocMap);
6851 
6852   for (const auto &CGMapEntry : SecToRelocMap) {
6853     const Elf_Shdr *CGSection = CGMapEntry.first;
6854     const Elf_Shdr *CGRelSection = CGMapEntry.second;
6855 
6856     Expected<ArrayRef<Elf_CGProfile>> CGProfileOrErr =
6857         this->Obj.template getSectionContentsAsArray<Elf_CGProfile>(*CGSection);
6858     if (!CGProfileOrErr) {
6859       this->reportUniqueWarning(
6860           "unable to load the SHT_LLVM_CALL_GRAPH_PROFILE section: " +
6861           toString(CGProfileOrErr.takeError()));
6862       return;
6863     }
6864 
6865     SmallVector<uint32_t, 128> SymbolIndices;
6866     bool UseReloc =
6867         getSymbolIndices<ELFT>(CGRelSection, this->Obj, this, SymbolIndices);
6868     if (UseReloc && SymbolIndices.size() != CGProfileOrErr->size() * 2) {
6869       this->reportUniqueWarning(
6870           "number of from/to pairs does not match number of frequencies");
6871       UseReloc = false;
6872     }
6873 
6874     ListScope L(W, "CGProfile");
6875     for (uint32_t I = 0, Size = CGProfileOrErr->size(); I != Size; ++I) {
6876       const Elf_CGProfile &CGPE = (*CGProfileOrErr)[I];
6877       DictScope D(W, "CGProfileEntry");
6878       if (UseReloc) {
6879         uint32_t From = SymbolIndices[I * 2];
6880         uint32_t To = SymbolIndices[I * 2 + 1];
6881         W.printNumber("From", this->getStaticSymbolName(From), From);
6882         W.printNumber("To", this->getStaticSymbolName(To), To);
6883       }
6884       W.printNumber("Weight", CGPE.cgp_weight);
6885     }
6886   }
6887 }
6888 
6889 template <class ELFT> void LLVMELFDumper<ELFT>::printBBAddrMaps() {
6890   bool IsRelocatable = this->Obj.getHeader().e_type == ELF::ET_REL;
6891   for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6892     if (Sec.sh_type != SHT_LLVM_BB_ADDR_MAP)
6893       continue;
6894     Optional<const Elf_Shdr *> FunctionSec = None;
6895     if (IsRelocatable)
6896       FunctionSec =
6897           unwrapOrError(this->FileName, this->Obj.getSection(Sec.sh_link));
6898     ListScope L(W, "BBAddrMap");
6899     Expected<std::vector<BBAddrMap>> BBAddrMapOrErr =
6900         this->Obj.decodeBBAddrMap(Sec);
6901     if (!BBAddrMapOrErr) {
6902       this->reportUniqueWarning("unable to dump " + this->describe(Sec) + ": " +
6903                                 toString(BBAddrMapOrErr.takeError()));
6904       continue;
6905     }
6906     for (const BBAddrMap &AM : *BBAddrMapOrErr) {
6907       DictScope D(W, "Function");
6908       W.printHex("At", AM.Addr);
6909       SmallVector<uint32_t> FuncSymIndex =
6910           this->getSymbolIndexesForFunctionAddress(AM.Addr, FunctionSec);
6911       std::string FuncName = "<?>";
6912       if (FuncSymIndex.empty())
6913         this->reportUniqueWarning(
6914             "could not identify function symbol for address (0x" +
6915             Twine::utohexstr(AM.Addr) + ") in " + this->describe(Sec));
6916       else
6917         FuncName = this->getStaticSymbolName(FuncSymIndex.front());
6918       W.printString("Name", FuncName);
6919 
6920       ListScope L(W, "BB entries");
6921       for (const BBAddrMap::BBEntry &BBE : AM.BBEntries) {
6922         DictScope L(W);
6923         W.printHex("Offset", BBE.Offset);
6924         W.printHex("Size", BBE.Size);
6925         W.printBoolean("HasReturn", BBE.HasReturn);
6926         W.printBoolean("HasTailCall", BBE.HasTailCall);
6927         W.printBoolean("IsEHPad", BBE.IsEHPad);
6928         W.printBoolean("CanFallThrough", BBE.CanFallThrough);
6929       }
6930     }
6931   }
6932 }
6933 
6934 template <class ELFT> void LLVMELFDumper<ELFT>::printAddrsig() {
6935   ListScope L(W, "Addrsig");
6936   if (!this->DotAddrsigSec)
6937     return;
6938 
6939   Expected<std::vector<uint64_t>> SymsOrErr =
6940       decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
6941   if (!SymsOrErr) {
6942     this->reportUniqueWarning(SymsOrErr.takeError());
6943     return;
6944   }
6945 
6946   for (uint64_t Sym : *SymsOrErr)
6947     W.printNumber("Sym", this->getStaticSymbolName(Sym), Sym);
6948 }
6949 
6950 template <typename ELFT>
6951 static bool printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
6952                                   ScopedPrinter &W) {
6953   // Return true if we were able to pretty-print the note, false otherwise.
6954   switch (NoteType) {
6955   default:
6956     return false;
6957   case ELF::NT_GNU_ABI_TAG: {
6958     const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
6959     if (!AbiTag.IsValid) {
6960       W.printString("ABI", "<corrupt GNU_ABI_TAG>");
6961       return false;
6962     } else {
6963       W.printString("OS", AbiTag.OSName);
6964       W.printString("ABI", AbiTag.ABI);
6965     }
6966     break;
6967   }
6968   case ELF::NT_GNU_BUILD_ID: {
6969     W.printString("Build ID", getGNUBuildId(Desc));
6970     break;
6971   }
6972   case ELF::NT_GNU_GOLD_VERSION:
6973     W.printString("Version", getDescAsStringRef(Desc));
6974     break;
6975   case ELF::NT_GNU_PROPERTY_TYPE_0:
6976     ListScope D(W, "Property");
6977     for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
6978       W.printString(Property);
6979     break;
6980   }
6981   return true;
6982 }
6983 
6984 template <typename ELFT>
6985 static bool printLLVMOMPOFFLOADNoteLLVMStyle(uint32_t NoteType,
6986                                              ArrayRef<uint8_t> Desc,
6987                                              ScopedPrinter &W) {
6988   switch (NoteType) {
6989   default:
6990     return false;
6991   case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
6992     W.printString("Version", getDescAsStringRef(Desc));
6993     break;
6994   case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
6995     W.printString("Producer", getDescAsStringRef(Desc));
6996     break;
6997   case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
6998     W.printString("Producer version", getDescAsStringRef(Desc));
6999     break;
7000   }
7001   return true;
7002 }
7003 
7004 static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) {
7005   W.printNumber("Page Size", Note.PageSize);
7006   for (const CoreFileMapping &Mapping : Note.Mappings) {
7007     ListScope D(W, "Mapping");
7008     W.printHex("Start", Mapping.Start);
7009     W.printHex("End", Mapping.End);
7010     W.printHex("Offset", Mapping.Offset);
7011     W.printString("Filename", Mapping.Filename);
7012   }
7013 }
7014 
7015 template <class ELFT> void LLVMELFDumper<ELFT>::printNotes() {
7016   ListScope L(W, "Notes");
7017 
7018   std::unique_ptr<DictScope> NoteScope;
7019   auto StartNotes = [&](Optional<StringRef> SecName,
7020                         const typename ELFT::Off Offset,
7021                         const typename ELFT::Addr Size) {
7022     NoteScope = std::make_unique<DictScope>(W, "NoteSection");
7023     W.printString("Name", SecName ? *SecName : "<?>");
7024     W.printHex("Offset", Offset);
7025     W.printHex("Size", Size);
7026   };
7027 
7028   auto EndNotes = [&] { NoteScope.reset(); };
7029 
7030   auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
7031     DictScope D2(W, "Note");
7032     StringRef Name = Note.getName();
7033     ArrayRef<uint8_t> Descriptor = Note.getDesc();
7034     Elf_Word Type = Note.getType();
7035 
7036     // Print the note owner/type.
7037     W.printString("Owner", Name);
7038     W.printHex("Data size", Descriptor.size());
7039 
7040     StringRef NoteType =
7041         getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
7042     if (!NoteType.empty())
7043       W.printString("Type", NoteType);
7044     else
7045       W.printString("Type",
7046                     "Unknown (" + to_string(format_hex(Type, 10)) + ")");
7047 
7048     // Print the description, or fallback to printing raw bytes for unknown
7049     // owners/if we fail to pretty-print the contents.
7050     if (Name == "GNU") {
7051       if (printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W))
7052         return Error::success();
7053     } else if (Name == "FreeBSD") {
7054       if (Optional<FreeBSDNote> N =
7055               getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
7056         W.printString(N->Type, N->Value);
7057         return Error::success();
7058       }
7059     } else if (Name == "AMD") {
7060       const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
7061       if (!N.Type.empty()) {
7062         W.printString(N.Type, N.Value);
7063         return Error::success();
7064       }
7065     } else if (Name == "AMDGPU") {
7066       const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
7067       if (!N.Type.empty()) {
7068         W.printString(N.Type, N.Value);
7069         return Error::success();
7070       }
7071     } else if (Name == "LLVMOMPOFFLOAD") {
7072       if (printLLVMOMPOFFLOADNoteLLVMStyle<ELFT>(Type, Descriptor, W))
7073         return Error::success();
7074     } else if (Name == "CORE") {
7075       if (Type == ELF::NT_FILE) {
7076         DataExtractor DescExtractor(Descriptor,
7077                                     ELFT::TargetEndianness == support::little,
7078                                     sizeof(Elf_Addr));
7079         if (Expected<CoreNote> N = readCoreNote(DescExtractor)) {
7080           printCoreNoteLLVMStyle(*N, W);
7081           return Error::success();
7082         } else {
7083           return N.takeError();
7084         }
7085       }
7086     }
7087     if (!Descriptor.empty()) {
7088       W.printBinaryBlock("Description data", Descriptor);
7089     }
7090     return Error::success();
7091   };
7092 
7093   printNotesHelper(*this, StartNotes, ProcessNote, EndNotes);
7094 }
7095 
7096 template <class ELFT> void LLVMELFDumper<ELFT>::printELFLinkerOptions() {
7097   ListScope L(W, "LinkerOptions");
7098 
7099   unsigned I = -1;
7100   for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) {
7101     ++I;
7102     if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS)
7103       continue;
7104 
7105     Expected<ArrayRef<uint8_t>> ContentsOrErr =
7106         this->Obj.getSectionContents(Shdr);
7107     if (!ContentsOrErr) {
7108       this->reportUniqueWarning("unable to read the content of the "
7109                                 "SHT_LLVM_LINKER_OPTIONS section: " +
7110                                 toString(ContentsOrErr.takeError()));
7111       continue;
7112     }
7113     if (ContentsOrErr->empty())
7114       continue;
7115 
7116     if (ContentsOrErr->back() != 0) {
7117       this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " +
7118                                 Twine(I) +
7119                                 " is broken: the "
7120                                 "content is not null-terminated");
7121       continue;
7122     }
7123 
7124     SmallVector<StringRef, 16> Strings;
7125     toStringRef(ContentsOrErr->drop_back()).split(Strings, '\0');
7126     if (Strings.size() % 2 != 0) {
7127       this->reportUniqueWarning(
7128           "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) +
7129           " is broken: an incomplete "
7130           "key-value pair was found. The last possible key was: \"" +
7131           Strings.back() + "\"");
7132       continue;
7133     }
7134 
7135     for (size_t I = 0; I < Strings.size(); I += 2)
7136       W.printString(Strings[I], Strings[I + 1]);
7137   }
7138 }
7139 
7140 template <class ELFT> void LLVMELFDumper<ELFT>::printDependentLibs() {
7141   ListScope L(W, "DependentLibs");
7142   this->printDependentLibsHelper(
7143       [](const Elf_Shdr &) {},
7144       [this](StringRef Lib, uint64_t) { W.printString(Lib); });
7145 }
7146 
7147 template <class ELFT> void LLVMELFDumper<ELFT>::printStackSizes() {
7148   ListScope L(W, "StackSizes");
7149   if (this->Obj.getHeader().e_type == ELF::ET_REL)
7150     this->printRelocatableStackSizes([]() {});
7151   else
7152     this->printNonRelocatableStackSizes([]() {});
7153 }
7154 
7155 template <class ELFT>
7156 void LLVMELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
7157                                               ArrayRef<std::string> FuncNames) {
7158   DictScope D(W, "Entry");
7159   W.printList("Functions", FuncNames);
7160   W.printHex("Size", Size);
7161 }
7162 
7163 template <class ELFT>
7164 void LLVMELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
7165   auto PrintEntry = [&](const Elf_Addr *E) {
7166     W.printHex("Address", Parser.getGotAddress(E));
7167     W.printNumber("Access", Parser.getGotOffset(E));
7168     W.printHex("Initial", *E);
7169   };
7170 
7171   DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT");
7172 
7173   W.printHex("Canonical gp value", Parser.getGp());
7174   {
7175     ListScope RS(W, "Reserved entries");
7176     {
7177       DictScope D(W, "Entry");
7178       PrintEntry(Parser.getGotLazyResolver());
7179       W.printString("Purpose", StringRef("Lazy resolver"));
7180     }
7181 
7182     if (Parser.getGotModulePointer()) {
7183       DictScope D(W, "Entry");
7184       PrintEntry(Parser.getGotModulePointer());
7185       W.printString("Purpose", StringRef("Module pointer (GNU extension)"));
7186     }
7187   }
7188   {
7189     ListScope LS(W, "Local entries");
7190     for (auto &E : Parser.getLocalEntries()) {
7191       DictScope D(W, "Entry");
7192       PrintEntry(&E);
7193     }
7194   }
7195 
7196   if (Parser.IsStatic)
7197     return;
7198 
7199   {
7200     ListScope GS(W, "Global entries");
7201     for (auto &E : Parser.getGlobalEntries()) {
7202       DictScope D(W, "Entry");
7203 
7204       PrintEntry(&E);
7205 
7206       const Elf_Sym &Sym = *Parser.getGotSym(&E);
7207       W.printHex("Value", Sym.st_value);
7208       W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes));
7209 
7210       const unsigned SymIndex = &Sym - this->dynamic_symbols().begin();
7211       DataRegion<Elf_Word> ShndxTable(
7212           (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
7213       printSymbolSection(Sym, SymIndex, ShndxTable);
7214 
7215       std::string SymName = this->getFullSymbolName(
7216           Sym, SymIndex, ShndxTable, this->DynamicStringTable, true);
7217       W.printNumber("Name", SymName, Sym.st_name);
7218     }
7219   }
7220 
7221   W.printNumber("Number of TLS and multi-GOT entries",
7222                 uint64_t(Parser.getOtherEntries().size()));
7223 }
7224 
7225 template <class ELFT>
7226 void LLVMELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
7227   auto PrintEntry = [&](const Elf_Addr *E) {
7228     W.printHex("Address", Parser.getPltAddress(E));
7229     W.printHex("Initial", *E);
7230   };
7231 
7232   DictScope GS(W, "PLT GOT");
7233 
7234   {
7235     ListScope RS(W, "Reserved entries");
7236     {
7237       DictScope D(W, "Entry");
7238       PrintEntry(Parser.getPltLazyResolver());
7239       W.printString("Purpose", StringRef("PLT lazy resolver"));
7240     }
7241 
7242     if (auto E = Parser.getPltModulePointer()) {
7243       DictScope D(W, "Entry");
7244       PrintEntry(E);
7245       W.printString("Purpose", StringRef("Module pointer"));
7246     }
7247   }
7248   {
7249     ListScope LS(W, "Entries");
7250     DataRegion<Elf_Word> ShndxTable(
7251         (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
7252     for (auto &E : Parser.getPltEntries()) {
7253       DictScope D(W, "Entry");
7254       PrintEntry(&E);
7255 
7256       const Elf_Sym &Sym = *Parser.getPltSym(&E);
7257       W.printHex("Value", Sym.st_value);
7258       W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes));
7259       printSymbolSection(Sym, &Sym - this->dynamic_symbols().begin(),
7260                          ShndxTable);
7261 
7262       const Elf_Sym *FirstSym = cantFail(
7263           this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
7264       std::string SymName = this->getFullSymbolName(
7265           Sym, &Sym - FirstSym, ShndxTable, Parser.getPltStrTable(), true);
7266       W.printNumber("Name", SymName, Sym.st_name);
7267     }
7268   }
7269 }
7270 
7271 template <class ELFT> void LLVMELFDumper<ELFT>::printMipsABIFlags() {
7272   const Elf_Mips_ABIFlags<ELFT> *Flags;
7273   if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
7274           getMipsAbiFlagsSection(*this)) {
7275     Flags = *SecOrErr;
7276     if (!Flags) {
7277       W.startLine() << "There is no .MIPS.abiflags section in the file.\n";
7278       return;
7279     }
7280   } else {
7281     this->reportUniqueWarning(SecOrErr.takeError());
7282     return;
7283   }
7284 
7285   raw_ostream &OS = W.getOStream();
7286   DictScope GS(W, "MIPS ABI Flags");
7287 
7288   W.printNumber("Version", Flags->version);
7289   W.startLine() << "ISA: ";
7290   if (Flags->isa_rev <= 1)
7291     OS << format("MIPS%u", Flags->isa_level);
7292   else
7293     OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev);
7294   OS << "\n";
7295   W.printEnum("ISA Extension", Flags->isa_ext, makeArrayRef(ElfMipsISAExtType));
7296   W.printFlags("ASEs", Flags->ases, makeArrayRef(ElfMipsASEFlags));
7297   W.printEnum("FP ABI", Flags->fp_abi, makeArrayRef(ElfMipsFpABIType));
7298   W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size));
7299   W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size));
7300   W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size));
7301   W.printFlags("Flags 1", Flags->flags1, makeArrayRef(ElfMipsFlags1));
7302   W.printHex("Flags 2", Flags->flags2);
7303 }
7304