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