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