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