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