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