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