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