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