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