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