Fix test failures introduced by PR #113697 (#116941)
[llvm-project.git] / llvm / tools / llvm-readobj / ELFDumper.cpp
blobbb8ec41d87454cb460aebd5efe40b7ee150036fb
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 "ObjDumper.h"
17 #include "StackMapPrinter.h"
18 #include "llvm-readobj.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/MapVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/BinaryFormat/AMDGPUMetadataVerifier.h"
31 #include "llvm/BinaryFormat/ELF.h"
32 #include "llvm/BinaryFormat/MsgPackDocument.h"
33 #include "llvm/Demangle/Demangle.h"
34 #include "llvm/Object/Archive.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/HexagonAttributeParser.h"
53 #include "llvm/Support/LEB128.h"
54 #include "llvm/Support/MSP430AttributeParser.h"
55 #include "llvm/Support/MSP430Attributes.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/MipsABIFlags.h"
58 #include "llvm/Support/RISCVAttributeParser.h"
59 #include "llvm/Support/RISCVAttributes.h"
60 #include "llvm/Support/ScopedPrinter.h"
61 #include "llvm/Support/SystemZ/zOSSupport.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include <algorithm>
64 #include <array>
65 #include <cinttypes>
66 #include <cstddef>
67 #include <cstdint>
68 #include <cstdlib>
69 #include <iterator>
70 #include <memory>
71 #include <optional>
72 #include <string>
73 #include <system_error>
74 #include <vector>
76 using namespace llvm;
77 using namespace llvm::object;
78 using namespace llvm::support;
79 using namespace ELF;
81 #define LLVM_READOBJ_ENUM_CASE(ns, enum) \
82 case ns::enum: \
83 return #enum;
85 #define ENUM_ENT(enum, altName) \
86 { #enum, altName, ELF::enum }
88 #define ENUM_ENT_1(enum) \
89 { #enum, #enum, ELF::enum }
91 namespace {
93 template <class ELFT> struct RelSymbol {
94 RelSymbol(const typename ELFT::Sym *S, StringRef N)
95 : Sym(S), Name(N.str()) {}
96 const typename ELFT::Sym *Sym;
97 std::string Name;
100 /// Represents a contiguous uniform range in the file. We cannot just create a
101 /// range directly because when creating one of these from the .dynamic table
102 /// the size, entity size and virtual address are different entries in arbitrary
103 /// order (DT_REL, DT_RELSZ, DT_RELENT for example).
104 struct DynRegionInfo {
105 DynRegionInfo(const Binary &Owner, const ObjDumper &D)
106 : Obj(&Owner), Dumper(&D) {}
107 DynRegionInfo(const Binary &Owner, const ObjDumper &D, const uint8_t *A,
108 uint64_t S, uint64_t ES)
109 : Addr(A), Size(S), EntSize(ES), Obj(&Owner), Dumper(&D) {}
111 /// Address in current address space.
112 const uint8_t *Addr = nullptr;
113 /// Size in bytes of the region.
114 uint64_t Size = 0;
115 /// Size of each entity in the region.
116 uint64_t EntSize = 0;
118 /// Owner object. Used for error reporting.
119 const Binary *Obj;
120 /// Dumper used for error reporting.
121 const ObjDumper *Dumper;
122 /// Error prefix. Used for error reporting to provide more information.
123 std::string Context;
124 /// Region size name. Used for error reporting.
125 StringRef SizePrintName = "size";
126 /// Entry size name. Used for error reporting. If this field is empty, errors
127 /// will not mention the entry size.
128 StringRef EntSizePrintName = "entry size";
130 template <typename Type> ArrayRef<Type> getAsArrayRef() const {
131 const Type *Start = reinterpret_cast<const Type *>(Addr);
132 if (!Start)
133 return {Start, Start};
135 const uint64_t Offset =
136 Addr - (const uint8_t *)Obj->getMemoryBufferRef().getBufferStart();
137 const uint64_t ObjSize = Obj->getMemoryBufferRef().getBufferSize();
139 if (Size > ObjSize - Offset) {
140 Dumper->reportUniqueWarning(
141 "unable to read data at 0x" + Twine::utohexstr(Offset) +
142 " of size 0x" + Twine::utohexstr(Size) + " (" + SizePrintName +
143 "): it goes past the end of the file of size 0x" +
144 Twine::utohexstr(ObjSize));
145 return {Start, Start};
148 if (EntSize == sizeof(Type) && (Size % EntSize == 0))
149 return {Start, Start + (Size / EntSize)};
151 std::string Msg;
152 if (!Context.empty())
153 Msg += Context + " has ";
155 Msg += ("invalid " + SizePrintName + " (0x" + Twine::utohexstr(Size) + ")")
156 .str();
157 if (!EntSizePrintName.empty())
158 Msg +=
159 (" or " + EntSizePrintName + " (0x" + Twine::utohexstr(EntSize) + ")")
160 .str();
162 Dumper->reportUniqueWarning(Msg);
163 return {Start, Start};
167 struct GroupMember {
168 StringRef Name;
169 uint64_t Index;
172 struct GroupSection {
173 StringRef Name;
174 std::string Signature;
175 uint64_t ShName;
176 uint64_t Index;
177 uint32_t Link;
178 uint32_t Info;
179 uint32_t Type;
180 std::vector<GroupMember> Members;
183 namespace {
185 struct NoteType {
186 uint32_t ID;
187 StringRef Name;
190 } // namespace
192 template <class ELFT> class Relocation {
193 public:
194 Relocation(const typename ELFT::Rel &R, bool IsMips64EL)
195 : Type(R.getType(IsMips64EL)), Symbol(R.getSymbol(IsMips64EL)),
196 Offset(R.r_offset), Info(R.r_info) {}
198 Relocation(const typename ELFT::Rela &R, bool IsMips64EL)
199 : Relocation((const typename ELFT::Rel &)R, IsMips64EL) {
200 Addend = R.r_addend;
203 uint32_t Type;
204 uint32_t Symbol;
205 typename ELFT::uint Offset;
206 typename ELFT::uint Info;
207 std::optional<int64_t> Addend;
210 template <class ELFT> class MipsGOTParser;
212 template <typename ELFT> class ELFDumper : public ObjDumper {
213 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
215 public:
216 ELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer);
218 void printUnwindInfo() override;
219 void printNeededLibraries() override;
220 void printHashTable() override;
221 void printGnuHashTable() override;
222 void printLoadName() override;
223 void printVersionInfo() override;
224 void printArchSpecificInfo() override;
225 void printStackMap() const override;
226 void printMemtag() override;
227 ArrayRef<uint8_t> getMemtagGlobalsSectionContents(uint64_t ExpectedAddr);
229 // Hash histogram shows statistics of how efficient the hash was for the
230 // dynamic symbol table. The table shows the number of hash buckets for
231 // different lengths of chains as an absolute number and percentage of the
232 // total buckets, and the cumulative coverage of symbols for each set of
233 // buckets.
234 void printHashHistograms() override;
236 const object::ELFObjectFile<ELFT> &getElfObject() const { return ObjF; };
238 std::string describe(const Elf_Shdr &Sec) const;
240 unsigned getHashTableEntSize() const {
241 // EM_S390 and ELF::EM_ALPHA platforms use 8-bytes entries in SHT_HASH
242 // sections. This violates the ELF specification.
243 if (Obj.getHeader().e_machine == ELF::EM_S390 ||
244 Obj.getHeader().e_machine == ELF::EM_ALPHA)
245 return 8;
246 return 4;
249 std::vector<EnumEntry<unsigned>>
250 getOtherFlagsFromSymbol(const Elf_Ehdr &Header, const Elf_Sym &Symbol) const;
252 Elf_Dyn_Range dynamic_table() const {
253 // A valid .dynamic section contains an array of entries terminated
254 // with a DT_NULL entry. However, sometimes the section content may
255 // continue past the DT_NULL entry, so to dump the section correctly,
256 // we first find the end of the entries by iterating over them.
257 Elf_Dyn_Range Table = DynamicTable.template getAsArrayRef<Elf_Dyn>();
259 size_t Size = 0;
260 while (Size < Table.size())
261 if (Table[Size++].getTag() == DT_NULL)
262 break;
264 return Table.slice(0, Size);
267 Elf_Sym_Range dynamic_symbols() const {
268 if (!DynSymRegion)
269 return Elf_Sym_Range();
270 return DynSymRegion->template getAsArrayRef<Elf_Sym>();
273 const Elf_Shdr *findSectionByName(StringRef Name) const;
275 StringRef getDynamicStringTable() const { return DynamicStringTable; }
277 protected:
278 virtual void printVersionSymbolSection(const Elf_Shdr *Sec) = 0;
279 virtual void printVersionDefinitionSection(const Elf_Shdr *Sec) = 0;
280 virtual void printVersionDependencySection(const Elf_Shdr *Sec) = 0;
282 void
283 printDependentLibsHelper(function_ref<void(const Elf_Shdr &)> OnSectionStart,
284 function_ref<void(StringRef, uint64_t)> OnLibEntry);
286 virtual void printRelRelaReloc(const Relocation<ELFT> &R,
287 const RelSymbol<ELFT> &RelSym) = 0;
288 virtual void printDynamicRelocHeader(unsigned Type, StringRef Name,
289 const DynRegionInfo &Reg) {}
290 void printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
291 const Elf_Shdr &Sec, const Elf_Shdr *SymTab);
292 void printDynamicReloc(const Relocation<ELFT> &R);
293 void printDynamicRelocationsHelper();
294 void printRelocationsHelper(const Elf_Shdr &Sec);
295 void forEachRelocationDo(
296 const Elf_Shdr &Sec,
297 llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
298 const Elf_Shdr &, const Elf_Shdr *)>
299 RelRelaFn);
301 virtual void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
302 bool NonVisibilityBitsUsed,
303 bool ExtraSymInfo) const {};
304 virtual void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
305 DataRegion<Elf_Word> ShndxTable,
306 std::optional<StringRef> StrTable, bool IsDynamic,
307 bool NonVisibilityBitsUsed,
308 bool ExtraSymInfo) const = 0;
310 virtual void printMipsABIFlags() = 0;
311 virtual void printMipsGOT(const MipsGOTParser<ELFT> &Parser) = 0;
312 virtual void printMipsPLT(const MipsGOTParser<ELFT> &Parser) = 0;
314 virtual void printMemtag(
315 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
316 const ArrayRef<uint8_t> AndroidNoteDesc,
317 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) = 0;
319 virtual void printHashHistogram(const Elf_Hash &HashTable) const;
320 virtual void printGnuHashHistogram(const Elf_GnuHash &GnuHashTable) const;
321 virtual void printHashHistogramStats(size_t NBucket, size_t MaxChain,
322 size_t TotalSyms, ArrayRef<size_t> Count,
323 bool IsGnu) const = 0;
325 Expected<ArrayRef<Elf_Versym>>
326 getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
327 StringRef *StrTab, const Elf_Shdr **SymTabSec) const;
328 StringRef getPrintableSectionName(const Elf_Shdr &Sec) const;
330 std::vector<GroupSection> getGroups();
332 // Returns the function symbol index for the given address. Matches the
333 // symbol's section with FunctionSec when specified.
334 // Returns std::nullopt if no function symbol can be found for the address or
335 // in case it is not defined in the specified section.
336 SmallVector<uint32_t> getSymbolIndexesForFunctionAddress(
337 uint64_t SymValue, std::optional<const Elf_Shdr *> FunctionSec);
338 bool printFunctionStackSize(uint64_t SymValue,
339 std::optional<const Elf_Shdr *> FunctionSec,
340 const Elf_Shdr &StackSizeSec, DataExtractor Data,
341 uint64_t *Offset);
342 void printStackSize(const Relocation<ELFT> &R, const Elf_Shdr &RelocSec,
343 unsigned Ndx, const Elf_Shdr *SymTab,
344 const Elf_Shdr *FunctionSec, const Elf_Shdr &StackSizeSec,
345 const RelocationResolver &Resolver, DataExtractor Data);
346 virtual void printStackSizeEntry(uint64_t Size,
347 ArrayRef<std::string> FuncNames) = 0;
349 void printRelocatableStackSizes(std::function<void()> PrintHeader);
350 void printNonRelocatableStackSizes(std::function<void()> PrintHeader);
352 const object::ELFObjectFile<ELFT> &ObjF;
353 const ELFFile<ELFT> &Obj;
354 StringRef FileName;
356 Expected<DynRegionInfo> createDRI(uint64_t Offset, uint64_t Size,
357 uint64_t EntSize) {
358 if (Offset + Size < Offset || Offset + Size > Obj.getBufSize())
359 return createError("offset (0x" + Twine::utohexstr(Offset) +
360 ") + size (0x" + Twine::utohexstr(Size) +
361 ") is greater than the file size (0x" +
362 Twine::utohexstr(Obj.getBufSize()) + ")");
363 return DynRegionInfo(ObjF, *this, Obj.base() + Offset, Size, EntSize);
366 void printAttributes(unsigned, std::unique_ptr<ELFAttributeParser>,
367 llvm::endianness);
368 void printMipsReginfo();
369 void printMipsOptions();
371 std::pair<const Elf_Phdr *, const Elf_Shdr *> findDynamic();
372 void loadDynamicTable();
373 void parseDynamicTable();
375 Expected<StringRef> getSymbolVersion(const Elf_Sym &Sym,
376 bool &IsDefault) const;
377 Expected<SmallVector<std::optional<VersionEntry>, 0> *> getVersionMap() const;
379 DynRegionInfo DynRelRegion;
380 DynRegionInfo DynRelaRegion;
381 DynRegionInfo DynCrelRegion;
382 DynRegionInfo DynRelrRegion;
383 DynRegionInfo DynPLTRelRegion;
384 std::optional<DynRegionInfo> DynSymRegion;
385 DynRegionInfo DynSymTabShndxRegion;
386 DynRegionInfo DynamicTable;
387 StringRef DynamicStringTable;
388 const Elf_Hash *HashTable = nullptr;
389 const Elf_GnuHash *GnuHashTable = nullptr;
390 const Elf_Shdr *DotSymtabSec = nullptr;
391 const Elf_Shdr *DotDynsymSec = nullptr;
392 const Elf_Shdr *DotAddrsigSec = nullptr;
393 DenseMap<const Elf_Shdr *, ArrayRef<Elf_Word>> ShndxTables;
394 std::optional<uint64_t> SONameOffset;
395 std::optional<DenseMap<uint64_t, std::vector<uint32_t>>> AddressToIndexMap;
397 const Elf_Shdr *SymbolVersionSection = nullptr; // .gnu.version
398 const Elf_Shdr *SymbolVersionNeedSection = nullptr; // .gnu.version_r
399 const Elf_Shdr *SymbolVersionDefSection = nullptr; // .gnu.version_d
401 std::string getFullSymbolName(const Elf_Sym &Symbol, unsigned SymIndex,
402 DataRegion<Elf_Word> ShndxTable,
403 std::optional<StringRef> StrTable,
404 bool IsDynamic) const;
405 Expected<unsigned>
406 getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
407 DataRegion<Elf_Word> ShndxTable) const;
408 Expected<StringRef> getSymbolSectionName(const Elf_Sym &Symbol,
409 unsigned SectionIndex) const;
410 std::string getStaticSymbolName(uint32_t Index) const;
411 StringRef getDynamicString(uint64_t Value) const;
413 std::pair<Elf_Sym_Range, std::optional<StringRef>> getSymtabAndStrtab() const;
414 void printSymbolsHelper(bool IsDynamic, bool ExtraSymInfo) const;
415 std::string getDynamicEntry(uint64_t Type, uint64_t Value) const;
417 Expected<RelSymbol<ELFT>> getRelocationTarget(const Relocation<ELFT> &R,
418 const Elf_Shdr *SymTab) const;
420 ArrayRef<Elf_Word> getShndxTable(const Elf_Shdr *Symtab) const;
422 private:
423 mutable SmallVector<std::optional<VersionEntry>, 0> VersionMap;
426 template <class ELFT>
427 std::string ELFDumper<ELFT>::describe(const Elf_Shdr &Sec) const {
428 return ::describe(Obj, Sec);
431 namespace {
433 template <class ELFT> struct SymtabLink {
434 typename ELFT::SymRange Symbols;
435 StringRef StringTable;
436 const typename ELFT::Shdr *SymTab;
439 // Returns the linked symbol table, symbols and associated string table for a
440 // given section.
441 template <class ELFT>
442 Expected<SymtabLink<ELFT>> getLinkAsSymtab(const ELFFile<ELFT> &Obj,
443 const typename ELFT::Shdr &Sec,
444 unsigned ExpectedType) {
445 Expected<const typename ELFT::Shdr *> SymtabOrErr =
446 Obj.getSection(Sec.sh_link);
447 if (!SymtabOrErr)
448 return createError("invalid section linked to " + describe(Obj, Sec) +
449 ": " + toString(SymtabOrErr.takeError()));
451 if ((*SymtabOrErr)->sh_type != ExpectedType)
452 return createError(
453 "invalid section linked to " + describe(Obj, Sec) + ": expected " +
454 object::getELFSectionTypeName(Obj.getHeader().e_machine, ExpectedType) +
455 ", but got " +
456 object::getELFSectionTypeName(Obj.getHeader().e_machine,
457 (*SymtabOrErr)->sh_type));
459 Expected<StringRef> StrTabOrErr = Obj.getLinkAsStrtab(**SymtabOrErr);
460 if (!StrTabOrErr)
461 return createError(
462 "can't get a string table for the symbol table linked to " +
463 describe(Obj, Sec) + ": " + toString(StrTabOrErr.takeError()));
465 Expected<typename ELFT::SymRange> SymsOrErr = Obj.symbols(*SymtabOrErr);
466 if (!SymsOrErr)
467 return createError("unable to read symbols from the " + describe(Obj, Sec) +
468 ": " + toString(SymsOrErr.takeError()));
470 return SymtabLink<ELFT>{*SymsOrErr, *StrTabOrErr, *SymtabOrErr};
473 } // namespace
475 template <class ELFT>
476 Expected<ArrayRef<typename ELFT::Versym>>
477 ELFDumper<ELFT>::getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
478 StringRef *StrTab,
479 const Elf_Shdr **SymTabSec) const {
480 assert((!SymTab && !StrTab && !SymTabSec) || (SymTab && StrTab && SymTabSec));
481 if (reinterpret_cast<uintptr_t>(Obj.base() + Sec.sh_offset) %
482 sizeof(uint16_t) !=
484 return createError("the " + describe(Sec) + " is misaligned");
486 Expected<ArrayRef<Elf_Versym>> VersionsOrErr =
487 Obj.template getSectionContentsAsArray<Elf_Versym>(Sec);
488 if (!VersionsOrErr)
489 return createError("cannot read content of " + describe(Sec) + ": " +
490 toString(VersionsOrErr.takeError()));
492 Expected<SymtabLink<ELFT>> SymTabOrErr =
493 getLinkAsSymtab(Obj, Sec, SHT_DYNSYM);
494 if (!SymTabOrErr) {
495 reportUniqueWarning(SymTabOrErr.takeError());
496 return *VersionsOrErr;
499 if (SymTabOrErr->Symbols.size() != VersionsOrErr->size())
500 reportUniqueWarning(describe(Sec) + ": the number of entries (" +
501 Twine(VersionsOrErr->size()) +
502 ") does not match the number of symbols (" +
503 Twine(SymTabOrErr->Symbols.size()) +
504 ") in the symbol table with index " +
505 Twine(Sec.sh_link));
507 if (SymTab) {
508 *SymTab = SymTabOrErr->Symbols;
509 *StrTab = SymTabOrErr->StringTable;
510 *SymTabSec = SymTabOrErr->SymTab;
512 return *VersionsOrErr;
515 template <class ELFT>
516 std::pair<typename ELFDumper<ELFT>::Elf_Sym_Range, std::optional<StringRef>>
517 ELFDumper<ELFT>::getSymtabAndStrtab() const {
518 assert(DotSymtabSec);
519 Elf_Sym_Range Syms(nullptr, nullptr);
520 std::optional<StringRef> StrTable;
521 if (Expected<StringRef> StrTableOrErr =
522 Obj.getStringTableForSymtab(*DotSymtabSec))
523 StrTable = *StrTableOrErr;
524 else
525 reportUniqueWarning(
526 "unable to get the string table for the SHT_SYMTAB section: " +
527 toString(StrTableOrErr.takeError()));
529 if (Expected<Elf_Sym_Range> SymsOrErr = Obj.symbols(DotSymtabSec))
530 Syms = *SymsOrErr;
531 else
532 reportUniqueWarning("unable to read symbols from the SHT_SYMTAB section: " +
533 toString(SymsOrErr.takeError()));
534 return {Syms, StrTable};
537 template <class ELFT>
538 void ELFDumper<ELFT>::printSymbolsHelper(bool IsDynamic,
539 bool ExtraSymInfo) const {
540 std::optional<StringRef> StrTable;
541 size_t Entries = 0;
542 Elf_Sym_Range Syms(nullptr, nullptr);
543 const Elf_Shdr *SymtabSec = IsDynamic ? DotDynsymSec : DotSymtabSec;
545 if (IsDynamic) {
546 StrTable = DynamicStringTable;
547 Syms = dynamic_symbols();
548 Entries = Syms.size();
549 } else if (DotSymtabSec) {
550 std::tie(Syms, StrTable) = getSymtabAndStrtab();
551 Entries = DotSymtabSec->getEntityCount();
553 if (Syms.empty())
554 return;
556 // The st_other field has 2 logical parts. The first two bits hold the symbol
557 // visibility (STV_*) and the remainder hold other platform-specific values.
558 bool NonVisibilityBitsUsed =
559 llvm::any_of(Syms, [](const Elf_Sym &S) { return S.st_other & ~0x3; });
561 DataRegion<Elf_Word> ShndxTable =
562 IsDynamic ? DataRegion<Elf_Word>(
563 (const Elf_Word *)this->DynSymTabShndxRegion.Addr,
564 this->getElfObject().getELFFile().end())
565 : DataRegion<Elf_Word>(this->getShndxTable(SymtabSec));
567 printSymtabMessage(SymtabSec, Entries, NonVisibilityBitsUsed, ExtraSymInfo);
568 for (const Elf_Sym &Sym : Syms)
569 printSymbol(Sym, &Sym - Syms.begin(), ShndxTable, StrTable, IsDynamic,
570 NonVisibilityBitsUsed, ExtraSymInfo);
573 template <typename ELFT> class GNUELFDumper : public ELFDumper<ELFT> {
574 formatted_raw_ostream &OS;
576 public:
577 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
579 GNUELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
580 : ELFDumper<ELFT>(ObjF, Writer),
581 OS(static_cast<formatted_raw_ostream &>(Writer.getOStream())) {
582 assert(&this->W.getOStream() == &llvm::fouts());
585 void printFileSummary(StringRef FileStr, ObjectFile &Obj,
586 ArrayRef<std::string> InputFilenames,
587 const Archive *A) override;
588 void printFileHeaders() override;
589 void printGroupSections() override;
590 void printRelocations() override;
591 void printSectionHeaders() override;
592 void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols,
593 bool ExtraSymInfo) override;
594 void printHashSymbols() override;
595 void printSectionDetails() override;
596 void printDependentLibs() override;
597 void printDynamicTable() override;
598 void printDynamicRelocations() override;
599 void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
600 bool NonVisibilityBitsUsed,
601 bool ExtraSymInfo) const override;
602 void printProgramHeaders(bool PrintProgramHeaders,
603 cl::boolOrDefault PrintSectionMapping) override;
604 void printVersionSymbolSection(const Elf_Shdr *Sec) override;
605 void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
606 void printVersionDependencySection(const Elf_Shdr *Sec) override;
607 void printCGProfile() override;
608 void printBBAddrMaps(bool PrettyPGOAnalysis) override;
609 void printAddrsig() override;
610 void printNotes() override;
611 void printELFLinkerOptions() override;
612 void printStackSizes() override;
613 void printMemtag(
614 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
615 const ArrayRef<uint8_t> AndroidNoteDesc,
616 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) override;
617 void printHashHistogramStats(size_t NBucket, size_t MaxChain,
618 size_t TotalSyms, ArrayRef<size_t> Count,
619 bool IsGnu) const override;
621 private:
622 void printHashTableSymbols(const Elf_Hash &HashTable);
623 void printGnuHashTableSymbols(const Elf_GnuHash &GnuHashTable);
625 struct Field {
626 std::string Str;
627 unsigned Column;
629 Field(StringRef S, unsigned Col) : Str(std::string(S)), Column(Col) {}
630 Field(unsigned Col) : Column(Col) {}
633 template <typename T, typename TEnum>
634 std::string printFlags(T Value, ArrayRef<EnumEntry<TEnum>> EnumValues,
635 TEnum EnumMask1 = {}, TEnum EnumMask2 = {},
636 TEnum EnumMask3 = {}) const {
637 std::string Str;
638 for (const EnumEntry<TEnum> &Flag : EnumValues) {
639 if (Flag.Value == 0)
640 continue;
642 TEnum EnumMask{};
643 if (Flag.Value & EnumMask1)
644 EnumMask = EnumMask1;
645 else if (Flag.Value & EnumMask2)
646 EnumMask = EnumMask2;
647 else if (Flag.Value & EnumMask3)
648 EnumMask = EnumMask3;
649 bool IsEnum = (Flag.Value & EnumMask) != 0;
650 if ((!IsEnum && (Value & Flag.Value) == Flag.Value) ||
651 (IsEnum && (Value & EnumMask) == Flag.Value)) {
652 if (!Str.empty())
653 Str += ", ";
654 Str += Flag.AltName;
657 return Str;
660 formatted_raw_ostream &printField(struct Field F) const {
661 if (F.Column != 0)
662 OS.PadToColumn(F.Column);
663 OS << F.Str;
664 OS.flush();
665 return OS;
667 void printHashedSymbol(const Elf_Sym *Sym, unsigned SymIndex,
668 DataRegion<Elf_Word> ShndxTable, StringRef StrTable,
669 uint32_t Bucket);
670 void printRelr(const Elf_Shdr &Sec);
671 void printRelRelaReloc(const Relocation<ELFT> &R,
672 const RelSymbol<ELFT> &RelSym) override;
673 void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
674 DataRegion<Elf_Word> ShndxTable,
675 std::optional<StringRef> StrTable, bool IsDynamic,
676 bool NonVisibilityBitsUsed,
677 bool ExtraSymInfo) const override;
678 void printDynamicRelocHeader(unsigned Type, StringRef Name,
679 const DynRegionInfo &Reg) override;
681 std::string getSymbolSectionNdx(const Elf_Sym &Symbol, unsigned SymIndex,
682 DataRegion<Elf_Word> ShndxTable,
683 bool ExtraSymInfo = false) const;
684 void printProgramHeaders() override;
685 void printSectionMapping() override;
686 void printGNUVersionSectionProlog(const typename ELFT::Shdr &Sec,
687 const Twine &Label, unsigned EntriesNum);
689 void printStackSizeEntry(uint64_t Size,
690 ArrayRef<std::string> FuncNames) override;
692 void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
693 void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
694 void printMipsABIFlags() override;
697 template <typename ELFT> class LLVMELFDumper : public ELFDumper<ELFT> {
698 public:
699 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
701 LLVMELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
702 : ELFDumper<ELFT>(ObjF, Writer), W(Writer) {}
704 void printFileHeaders() override;
705 void printGroupSections() override;
706 void printRelocations() override;
707 void printSectionHeaders() override;
708 void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols,
709 bool ExtraSymInfo) override;
710 void printDependentLibs() override;
711 void printDynamicTable() override;
712 void printDynamicRelocations() override;
713 void printProgramHeaders(bool PrintProgramHeaders,
714 cl::boolOrDefault PrintSectionMapping) override;
715 void printVersionSymbolSection(const Elf_Shdr *Sec) override;
716 void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
717 void printVersionDependencySection(const Elf_Shdr *Sec) override;
718 void printCGProfile() override;
719 void printBBAddrMaps(bool PrettyPGOAnalysis) override;
720 void printAddrsig() override;
721 void printNotes() override;
722 void printELFLinkerOptions() override;
723 void printStackSizes() override;
724 void printMemtag(
725 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
726 const ArrayRef<uint8_t> AndroidNoteDesc,
727 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) override;
728 void printSymbolSection(const Elf_Sym &Symbol, unsigned SymIndex,
729 DataRegion<Elf_Word> ShndxTable) const;
730 void printHashHistogramStats(size_t NBucket, size_t MaxChain,
731 size_t TotalSyms, ArrayRef<size_t> Count,
732 bool IsGnu) const override;
734 private:
735 void printRelRelaReloc(const Relocation<ELFT> &R,
736 const RelSymbol<ELFT> &RelSym) override;
738 void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
739 DataRegion<Elf_Word> ShndxTable,
740 std::optional<StringRef> StrTable, bool IsDynamic,
741 bool /*NonVisibilityBitsUsed*/,
742 bool /*ExtraSymInfo*/) const override;
743 void printProgramHeaders() override;
744 void printSectionMapping() override {}
745 void printStackSizeEntry(uint64_t Size,
746 ArrayRef<std::string> FuncNames) override;
748 void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
749 void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
750 void printMipsABIFlags() override;
751 virtual void printZeroSymbolOtherField(const Elf_Sym &Symbol) const;
753 protected:
754 virtual std::string getGroupSectionHeaderName() const;
755 void printSymbolOtherField(const Elf_Sym &Symbol) const;
756 virtual void printExpandedRelRelaReloc(const Relocation<ELFT> &R,
757 StringRef SymbolName,
758 StringRef RelocName);
759 virtual void printDefaultRelRelaReloc(const Relocation<ELFT> &R,
760 StringRef SymbolName,
761 StringRef RelocName);
762 virtual void printRelocationSectionInfo(const Elf_Shdr &Sec, StringRef Name,
763 const unsigned SecNdx);
764 virtual void printSectionGroupMembers(StringRef Name, uint64_t Idx) const;
765 virtual void printEmptyGroupMessage() const;
767 ScopedPrinter &W;
770 // JSONELFDumper shares most of the same implementation as LLVMELFDumper except
771 // it uses a JSONScopedPrinter.
772 template <typename ELFT> class JSONELFDumper : public LLVMELFDumper<ELFT> {
773 public:
774 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
776 JSONELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
777 : LLVMELFDumper<ELFT>(ObjF, Writer) {}
779 std::string getGroupSectionHeaderName() const override;
781 void printFileSummary(StringRef FileStr, ObjectFile &Obj,
782 ArrayRef<std::string> InputFilenames,
783 const Archive *A) override;
784 virtual void printZeroSymbolOtherField(const Elf_Sym &Symbol) const override;
786 void printDefaultRelRelaReloc(const Relocation<ELFT> &R,
787 StringRef SymbolName,
788 StringRef RelocName) override;
790 void printRelocationSectionInfo(const Elf_Shdr &Sec, StringRef Name,
791 const unsigned SecNdx) override;
793 void printSectionGroupMembers(StringRef Name, uint64_t Idx) const override;
795 void printEmptyGroupMessage() const override;
797 void printDynamicTable() override;
799 private:
800 void printAuxillaryDynamicTableEntryInfo(const Elf_Dyn &Entry);
802 std::unique_ptr<DictScope> FileScope;
805 } // end anonymous namespace
807 namespace llvm {
809 template <class ELFT>
810 static std::unique_ptr<ObjDumper>
811 createELFDumper(const ELFObjectFile<ELFT> &Obj, ScopedPrinter &Writer) {
812 if (opts::Output == opts::GNU)
813 return std::make_unique<GNUELFDumper<ELFT>>(Obj, Writer);
814 else if (opts::Output == opts::JSON)
815 return std::make_unique<JSONELFDumper<ELFT>>(Obj, Writer);
816 return std::make_unique<LLVMELFDumper<ELFT>>(Obj, Writer);
819 std::unique_ptr<ObjDumper> createELFDumper(const object::ELFObjectFileBase &Obj,
820 ScopedPrinter &Writer) {
821 // Little-endian 32-bit
822 if (const ELF32LEObjectFile *ELFObj = dyn_cast<ELF32LEObjectFile>(&Obj))
823 return createELFDumper(*ELFObj, Writer);
825 // Big-endian 32-bit
826 if (const ELF32BEObjectFile *ELFObj = dyn_cast<ELF32BEObjectFile>(&Obj))
827 return createELFDumper(*ELFObj, Writer);
829 // Little-endian 64-bit
830 if (const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(&Obj))
831 return createELFDumper(*ELFObj, Writer);
833 // Big-endian 64-bit
834 return createELFDumper(*cast<ELF64BEObjectFile>(&Obj), Writer);
837 } // end namespace llvm
839 template <class ELFT>
840 Expected<SmallVector<std::optional<VersionEntry>, 0> *>
841 ELFDumper<ELFT>::getVersionMap() const {
842 // If the VersionMap has already been loaded or if there is no dynamic symtab
843 // or version table, there is nothing to do.
844 if (!VersionMap.empty() || !DynSymRegion || !SymbolVersionSection)
845 return &VersionMap;
847 Expected<SmallVector<std::optional<VersionEntry>, 0>> MapOrErr =
848 Obj.loadVersionMap(SymbolVersionNeedSection, SymbolVersionDefSection);
849 if (MapOrErr)
850 VersionMap = *MapOrErr;
851 else
852 return MapOrErr.takeError();
854 return &VersionMap;
857 template <typename ELFT>
858 Expected<StringRef> ELFDumper<ELFT>::getSymbolVersion(const Elf_Sym &Sym,
859 bool &IsDefault) const {
860 // This is a dynamic symbol. Look in the GNU symbol version table.
861 if (!SymbolVersionSection) {
862 // No version table.
863 IsDefault = false;
864 return "";
867 assert(DynSymRegion && "DynSymRegion has not been initialised");
868 // Determine the position in the symbol table of this entry.
869 size_t EntryIndex = (reinterpret_cast<uintptr_t>(&Sym) -
870 reinterpret_cast<uintptr_t>(DynSymRegion->Addr)) /
871 sizeof(Elf_Sym);
873 // Get the corresponding version index entry.
874 Expected<const Elf_Versym *> EntryOrErr =
875 Obj.template getEntry<Elf_Versym>(*SymbolVersionSection, EntryIndex);
876 if (!EntryOrErr)
877 return EntryOrErr.takeError();
879 unsigned Version = (*EntryOrErr)->vs_index;
880 if (Version == VER_NDX_LOCAL || Version == VER_NDX_GLOBAL) {
881 IsDefault = false;
882 return "";
885 Expected<SmallVector<std::optional<VersionEntry>, 0> *> MapOrErr =
886 getVersionMap();
887 if (!MapOrErr)
888 return MapOrErr.takeError();
890 return Obj.getSymbolVersionByIndex(Version, IsDefault, **MapOrErr,
891 Sym.st_shndx == ELF::SHN_UNDEF);
894 template <typename ELFT>
895 Expected<RelSymbol<ELFT>>
896 ELFDumper<ELFT>::getRelocationTarget(const Relocation<ELFT> &R,
897 const Elf_Shdr *SymTab) const {
898 if (R.Symbol == 0)
899 return RelSymbol<ELFT>(nullptr, "");
901 Expected<const Elf_Sym *> SymOrErr =
902 Obj.template getEntry<Elf_Sym>(*SymTab, R.Symbol);
903 if (!SymOrErr)
904 return createError("unable to read an entry with index " + Twine(R.Symbol) +
905 " from " + describe(*SymTab) + ": " +
906 toString(SymOrErr.takeError()));
907 const Elf_Sym *Sym = *SymOrErr;
908 if (!Sym)
909 return RelSymbol<ELFT>(nullptr, "");
911 Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(*SymTab);
912 if (!StrTableOrErr)
913 return StrTableOrErr.takeError();
915 const Elf_Sym *FirstSym =
916 cantFail(Obj.template getEntry<Elf_Sym>(*SymTab, 0));
917 std::string SymbolName =
918 getFullSymbolName(*Sym, Sym - FirstSym, getShndxTable(SymTab),
919 *StrTableOrErr, SymTab->sh_type == SHT_DYNSYM);
920 return RelSymbol<ELFT>(Sym, SymbolName);
923 template <typename ELFT>
924 ArrayRef<typename ELFT::Word>
925 ELFDumper<ELFT>::getShndxTable(const Elf_Shdr *Symtab) const {
926 if (Symtab) {
927 auto It = ShndxTables.find(Symtab);
928 if (It != ShndxTables.end())
929 return It->second;
931 return {};
934 static std::string maybeDemangle(StringRef Name) {
935 return opts::Demangle ? demangle(Name) : Name.str();
938 template <typename ELFT>
939 std::string ELFDumper<ELFT>::getStaticSymbolName(uint32_t Index) const {
940 auto Warn = [&](Error E) -> std::string {
941 reportUniqueWarning("unable to read the name of symbol with index " +
942 Twine(Index) + ": " + toString(std::move(E)));
943 return "<?>";
946 Expected<const typename ELFT::Sym *> SymOrErr =
947 Obj.getSymbol(DotSymtabSec, Index);
948 if (!SymOrErr)
949 return Warn(SymOrErr.takeError());
951 Expected<StringRef> StrTabOrErr = Obj.getStringTableForSymtab(*DotSymtabSec);
952 if (!StrTabOrErr)
953 return Warn(StrTabOrErr.takeError());
955 Expected<StringRef> NameOrErr = (*SymOrErr)->getName(*StrTabOrErr);
956 if (!NameOrErr)
957 return Warn(NameOrErr.takeError());
958 return maybeDemangle(*NameOrErr);
961 template <typename ELFT>
962 std::string ELFDumper<ELFT>::getFullSymbolName(
963 const Elf_Sym &Symbol, unsigned SymIndex, DataRegion<Elf_Word> ShndxTable,
964 std::optional<StringRef> StrTable, bool IsDynamic) const {
965 if (!StrTable)
966 return "<?>";
968 std::string SymbolName;
969 if (Expected<StringRef> NameOrErr = Symbol.getName(*StrTable)) {
970 SymbolName = maybeDemangle(*NameOrErr);
971 } else {
972 reportUniqueWarning(NameOrErr.takeError());
973 return "<?>";
976 if (SymbolName.empty() && Symbol.getType() == ELF::STT_SECTION) {
977 Expected<unsigned> SectionIndex =
978 getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
979 if (!SectionIndex) {
980 reportUniqueWarning(SectionIndex.takeError());
981 return "<?>";
983 Expected<StringRef> NameOrErr = getSymbolSectionName(Symbol, *SectionIndex);
984 if (!NameOrErr) {
985 reportUniqueWarning(NameOrErr.takeError());
986 return ("<section " + Twine(*SectionIndex) + ">").str();
988 return std::string(*NameOrErr);
991 if (!IsDynamic)
992 return SymbolName;
994 bool IsDefault;
995 Expected<StringRef> VersionOrErr = getSymbolVersion(Symbol, IsDefault);
996 if (!VersionOrErr) {
997 reportUniqueWarning(VersionOrErr.takeError());
998 return SymbolName + "@<corrupt>";
1001 if (!VersionOrErr->empty()) {
1002 SymbolName += (IsDefault ? "@@" : "@");
1003 SymbolName += *VersionOrErr;
1005 return SymbolName;
1008 template <typename ELFT>
1009 Expected<unsigned>
1010 ELFDumper<ELFT>::getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
1011 DataRegion<Elf_Word> ShndxTable) const {
1012 unsigned Ndx = Symbol.st_shndx;
1013 if (Ndx == SHN_XINDEX)
1014 return object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex,
1015 ShndxTable);
1016 if (Ndx != SHN_UNDEF && Ndx < SHN_LORESERVE)
1017 return Ndx;
1019 auto CreateErr = [&](const Twine &Name,
1020 std::optional<unsigned> Offset = std::nullopt) {
1021 std::string Desc;
1022 if (Offset)
1023 Desc = (Name + "+0x" + Twine::utohexstr(*Offset)).str();
1024 else
1025 Desc = Name.str();
1026 return createError(
1027 "unable to get section index for symbol with st_shndx = 0x" +
1028 Twine::utohexstr(Ndx) + " (" + Desc + ")");
1031 if (Ndx >= ELF::SHN_LOPROC && Ndx <= ELF::SHN_HIPROC)
1032 return CreateErr("SHN_LOPROC", Ndx - ELF::SHN_LOPROC);
1033 if (Ndx >= ELF::SHN_LOOS && Ndx <= ELF::SHN_HIOS)
1034 return CreateErr("SHN_LOOS", Ndx - ELF::SHN_LOOS);
1035 if (Ndx == ELF::SHN_UNDEF)
1036 return CreateErr("SHN_UNDEF");
1037 if (Ndx == ELF::SHN_ABS)
1038 return CreateErr("SHN_ABS");
1039 if (Ndx == ELF::SHN_COMMON)
1040 return CreateErr("SHN_COMMON");
1041 return CreateErr("SHN_LORESERVE", Ndx - SHN_LORESERVE);
1044 template <typename ELFT>
1045 Expected<StringRef>
1046 ELFDumper<ELFT>::getSymbolSectionName(const Elf_Sym &Symbol,
1047 unsigned SectionIndex) const {
1048 Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(SectionIndex);
1049 if (!SecOrErr)
1050 return SecOrErr.takeError();
1051 return Obj.getSectionName(**SecOrErr);
1054 template <class ELFO>
1055 static const typename ELFO::Elf_Shdr *
1056 findNotEmptySectionByAddress(const ELFO &Obj, StringRef FileName,
1057 uint64_t Addr) {
1058 for (const typename ELFO::Elf_Shdr &Shdr : cantFail(Obj.sections()))
1059 if (Shdr.sh_addr == Addr && Shdr.sh_size > 0)
1060 return &Shdr;
1061 return nullptr;
1064 const EnumEntry<unsigned> ElfClass[] = {
1065 {"None", "none", ELF::ELFCLASSNONE},
1066 {"32-bit", "ELF32", ELF::ELFCLASS32},
1067 {"64-bit", "ELF64", ELF::ELFCLASS64},
1070 const EnumEntry<unsigned> ElfDataEncoding[] = {
1071 {"None", "none", ELF::ELFDATANONE},
1072 {"LittleEndian", "2's complement, little endian", ELF::ELFDATA2LSB},
1073 {"BigEndian", "2's complement, big endian", ELF::ELFDATA2MSB},
1076 const EnumEntry<unsigned> ElfObjectFileType[] = {
1077 {"None", "NONE (none)", ELF::ET_NONE},
1078 {"Relocatable", "REL (Relocatable file)", ELF::ET_REL},
1079 {"Executable", "EXEC (Executable file)", ELF::ET_EXEC},
1080 {"SharedObject", "DYN (Shared object file)", ELF::ET_DYN},
1081 {"Core", "CORE (Core file)", ELF::ET_CORE},
1084 const EnumEntry<unsigned> ElfOSABI[] = {
1085 {"SystemV", "UNIX - System V", ELF::ELFOSABI_NONE},
1086 {"HPUX", "UNIX - HP-UX", ELF::ELFOSABI_HPUX},
1087 {"NetBSD", "UNIX - NetBSD", ELF::ELFOSABI_NETBSD},
1088 {"GNU/Linux", "UNIX - GNU", ELF::ELFOSABI_LINUX},
1089 {"GNU/Hurd", "GNU/Hurd", ELF::ELFOSABI_HURD},
1090 {"Solaris", "UNIX - Solaris", ELF::ELFOSABI_SOLARIS},
1091 {"AIX", "UNIX - AIX", ELF::ELFOSABI_AIX},
1092 {"IRIX", "UNIX - IRIX", ELF::ELFOSABI_IRIX},
1093 {"FreeBSD", "UNIX - FreeBSD", ELF::ELFOSABI_FREEBSD},
1094 {"TRU64", "UNIX - TRU64", ELF::ELFOSABI_TRU64},
1095 {"Modesto", "Novell - Modesto", ELF::ELFOSABI_MODESTO},
1096 {"OpenBSD", "UNIX - OpenBSD", ELF::ELFOSABI_OPENBSD},
1097 {"OpenVMS", "VMS - OpenVMS", ELF::ELFOSABI_OPENVMS},
1098 {"NSK", "HP - Non-Stop Kernel", ELF::ELFOSABI_NSK},
1099 {"AROS", "AROS", ELF::ELFOSABI_AROS},
1100 {"FenixOS", "FenixOS", ELF::ELFOSABI_FENIXOS},
1101 {"CloudABI", "CloudABI", ELF::ELFOSABI_CLOUDABI},
1102 {"CUDA", "NVIDIA - CUDA", ELF::ELFOSABI_CUDA},
1103 {"Standalone", "Standalone App", ELF::ELFOSABI_STANDALONE}
1106 const EnumEntry<unsigned> AMDGPUElfOSABI[] = {
1107 {"AMDGPU_HSA", "AMDGPU - HSA", ELF::ELFOSABI_AMDGPU_HSA},
1108 {"AMDGPU_PAL", "AMDGPU - PAL", ELF::ELFOSABI_AMDGPU_PAL},
1109 {"AMDGPU_MESA3D", "AMDGPU - MESA3D", ELF::ELFOSABI_AMDGPU_MESA3D}
1112 const EnumEntry<unsigned> ARMElfOSABI[] = {
1113 {"ARM", "ARM", ELF::ELFOSABI_ARM},
1114 {"ARM FDPIC", "ARM FDPIC", ELF::ELFOSABI_ARM_FDPIC},
1117 const EnumEntry<unsigned> C6000ElfOSABI[] = {
1118 {"C6000_ELFABI", "Bare-metal C6000", ELF::ELFOSABI_C6000_ELFABI},
1119 {"C6000_LINUX", "Linux C6000", ELF::ELFOSABI_C6000_LINUX}
1122 const EnumEntry<unsigned> ElfMachineType[] = {
1123 ENUM_ENT(EM_NONE, "None"),
1124 ENUM_ENT(EM_M32, "WE32100"),
1125 ENUM_ENT(EM_SPARC, "Sparc"),
1126 ENUM_ENT(EM_386, "Intel 80386"),
1127 ENUM_ENT(EM_68K, "MC68000"),
1128 ENUM_ENT(EM_88K, "MC88000"),
1129 ENUM_ENT(EM_IAMCU, "EM_IAMCU"),
1130 ENUM_ENT(EM_860, "Intel 80860"),
1131 ENUM_ENT(EM_MIPS, "MIPS R3000"),
1132 ENUM_ENT(EM_S370, "IBM System/370"),
1133 ENUM_ENT(EM_MIPS_RS3_LE, "MIPS R3000 little-endian"),
1134 ENUM_ENT(EM_PARISC, "HPPA"),
1135 ENUM_ENT(EM_VPP500, "Fujitsu VPP500"),
1136 ENUM_ENT(EM_SPARC32PLUS, "Sparc v8+"),
1137 ENUM_ENT(EM_960, "Intel 80960"),
1138 ENUM_ENT(EM_PPC, "PowerPC"),
1139 ENUM_ENT(EM_PPC64, "PowerPC64"),
1140 ENUM_ENT(EM_S390, "IBM S/390"),
1141 ENUM_ENT(EM_SPU, "SPU"),
1142 ENUM_ENT(EM_V800, "NEC V800 series"),
1143 ENUM_ENT(EM_FR20, "Fujistsu FR20"),
1144 ENUM_ENT(EM_RH32, "TRW RH-32"),
1145 ENUM_ENT(EM_RCE, "Motorola RCE"),
1146 ENUM_ENT(EM_ARM, "ARM"),
1147 ENUM_ENT(EM_ALPHA, "EM_ALPHA"),
1148 ENUM_ENT(EM_SH, "Hitachi SH"),
1149 ENUM_ENT(EM_SPARCV9, "Sparc v9"),
1150 ENUM_ENT(EM_TRICORE, "Siemens Tricore"),
1151 ENUM_ENT(EM_ARC, "ARC"),
1152 ENUM_ENT(EM_H8_300, "Hitachi H8/300"),
1153 ENUM_ENT(EM_H8_300H, "Hitachi H8/300H"),
1154 ENUM_ENT(EM_H8S, "Hitachi H8S"),
1155 ENUM_ENT(EM_H8_500, "Hitachi H8/500"),
1156 ENUM_ENT(EM_IA_64, "Intel IA-64"),
1157 ENUM_ENT(EM_MIPS_X, "Stanford MIPS-X"),
1158 ENUM_ENT(EM_COLDFIRE, "Motorola Coldfire"),
1159 ENUM_ENT(EM_68HC12, "Motorola MC68HC12 Microcontroller"),
1160 ENUM_ENT(EM_MMA, "Fujitsu Multimedia Accelerator"),
1161 ENUM_ENT(EM_PCP, "Siemens PCP"),
1162 ENUM_ENT(EM_NCPU, "Sony nCPU embedded RISC processor"),
1163 ENUM_ENT(EM_NDR1, "Denso NDR1 microprocesspr"),
1164 ENUM_ENT(EM_STARCORE, "Motorola Star*Core processor"),
1165 ENUM_ENT(EM_ME16, "Toyota ME16 processor"),
1166 ENUM_ENT(EM_ST100, "STMicroelectronics ST100 processor"),
1167 ENUM_ENT(EM_TINYJ, "Advanced Logic Corp. TinyJ embedded processor"),
1168 ENUM_ENT(EM_X86_64, "Advanced Micro Devices X86-64"),
1169 ENUM_ENT(EM_PDSP, "Sony DSP processor"),
1170 ENUM_ENT(EM_PDP10, "Digital Equipment Corp. PDP-10"),
1171 ENUM_ENT(EM_PDP11, "Digital Equipment Corp. PDP-11"),
1172 ENUM_ENT(EM_FX66, "Siemens FX66 microcontroller"),
1173 ENUM_ENT(EM_ST9PLUS, "STMicroelectronics ST9+ 8/16 bit microcontroller"),
1174 ENUM_ENT(EM_ST7, "STMicroelectronics ST7 8-bit microcontroller"),
1175 ENUM_ENT(EM_68HC16, "Motorola MC68HC16 Microcontroller"),
1176 ENUM_ENT(EM_68HC11, "Motorola MC68HC11 Microcontroller"),
1177 ENUM_ENT(EM_68HC08, "Motorola MC68HC08 Microcontroller"),
1178 ENUM_ENT(EM_68HC05, "Motorola MC68HC05 Microcontroller"),
1179 ENUM_ENT(EM_SVX, "Silicon Graphics SVx"),
1180 ENUM_ENT(EM_ST19, "STMicroelectronics ST19 8-bit microcontroller"),
1181 ENUM_ENT(EM_VAX, "Digital VAX"),
1182 ENUM_ENT(EM_CRIS, "Axis Communications 32-bit embedded processor"),
1183 ENUM_ENT(EM_JAVELIN, "Infineon Technologies 32-bit embedded cpu"),
1184 ENUM_ENT(EM_FIREPATH, "Element 14 64-bit DSP processor"),
1185 ENUM_ENT(EM_ZSP, "LSI Logic's 16-bit DSP processor"),
1186 ENUM_ENT(EM_MMIX, "Donald Knuth's educational 64-bit processor"),
1187 ENUM_ENT(EM_HUANY, "Harvard Universitys's machine-independent object format"),
1188 ENUM_ENT(EM_PRISM, "Vitesse Prism"),
1189 ENUM_ENT(EM_AVR, "Atmel AVR 8-bit microcontroller"),
1190 ENUM_ENT(EM_FR30, "Fujitsu FR30"),
1191 ENUM_ENT(EM_D10V, "Mitsubishi D10V"),
1192 ENUM_ENT(EM_D30V, "Mitsubishi D30V"),
1193 ENUM_ENT(EM_V850, "NEC v850"),
1194 ENUM_ENT(EM_M32R, "Renesas M32R (formerly Mitsubishi M32r)"),
1195 ENUM_ENT(EM_MN10300, "Matsushita MN10300"),
1196 ENUM_ENT(EM_MN10200, "Matsushita MN10200"),
1197 ENUM_ENT(EM_PJ, "picoJava"),
1198 ENUM_ENT(EM_OPENRISC, "OpenRISC 32-bit embedded processor"),
1199 ENUM_ENT(EM_ARC_COMPACT, "EM_ARC_COMPACT"),
1200 ENUM_ENT(EM_XTENSA, "Tensilica Xtensa Processor"),
1201 ENUM_ENT(EM_VIDEOCORE, "Alphamosaic VideoCore processor"),
1202 ENUM_ENT(EM_TMM_GPP, "Thompson Multimedia General Purpose Processor"),
1203 ENUM_ENT(EM_NS32K, "National Semiconductor 32000 series"),
1204 ENUM_ENT(EM_TPC, "Tenor Network TPC processor"),
1205 ENUM_ENT(EM_SNP1K, "EM_SNP1K"),
1206 ENUM_ENT(EM_ST200, "STMicroelectronics ST200 microcontroller"),
1207 ENUM_ENT(EM_IP2K, "Ubicom IP2xxx 8-bit microcontrollers"),
1208 ENUM_ENT(EM_MAX, "MAX Processor"),
1209 ENUM_ENT(EM_CR, "National Semiconductor CompactRISC"),
1210 ENUM_ENT(EM_F2MC16, "Fujitsu F2MC16"),
1211 ENUM_ENT(EM_MSP430, "Texas Instruments msp430 microcontroller"),
1212 ENUM_ENT(EM_BLACKFIN, "Analog Devices Blackfin"),
1213 ENUM_ENT(EM_SE_C33, "S1C33 Family of Seiko Epson processors"),
1214 ENUM_ENT(EM_SEP, "Sharp embedded microprocessor"),
1215 ENUM_ENT(EM_ARCA, "Arca RISC microprocessor"),
1216 ENUM_ENT(EM_UNICORE, "Unicore"),
1217 ENUM_ENT(EM_EXCESS, "eXcess 16/32/64-bit configurable embedded CPU"),
1218 ENUM_ENT(EM_DXP, "Icera Semiconductor Inc. Deep Execution Processor"),
1219 ENUM_ENT(EM_ALTERA_NIOS2, "Altera Nios"),
1220 ENUM_ENT(EM_CRX, "National Semiconductor CRX microprocessor"),
1221 ENUM_ENT(EM_XGATE, "Motorola XGATE embedded processor"),
1222 ENUM_ENT(EM_C166, "Infineon Technologies xc16x"),
1223 ENUM_ENT(EM_M16C, "Renesas M16C"),
1224 ENUM_ENT(EM_DSPIC30F, "Microchip Technology dsPIC30F Digital Signal Controller"),
1225 ENUM_ENT(EM_CE, "Freescale Communication Engine RISC core"),
1226 ENUM_ENT(EM_M32C, "Renesas M32C"),
1227 ENUM_ENT(EM_TSK3000, "Altium TSK3000 core"),
1228 ENUM_ENT(EM_RS08, "Freescale RS08 embedded processor"),
1229 ENUM_ENT(EM_SHARC, "EM_SHARC"),
1230 ENUM_ENT(EM_ECOG2, "Cyan Technology eCOG2 microprocessor"),
1231 ENUM_ENT(EM_SCORE7, "SUNPLUS S+Core"),
1232 ENUM_ENT(EM_DSP24, "New Japan Radio (NJR) 24-bit DSP Processor"),
1233 ENUM_ENT(EM_VIDEOCORE3, "Broadcom VideoCore III processor"),
1234 ENUM_ENT(EM_LATTICEMICO32, "Lattice Mico32"),
1235 ENUM_ENT(EM_SE_C17, "Seiko Epson C17 family"),
1236 ENUM_ENT(EM_TI_C6000, "Texas Instruments TMS320C6000 DSP family"),
1237 ENUM_ENT(EM_TI_C2000, "Texas Instruments TMS320C2000 DSP family"),
1238 ENUM_ENT(EM_TI_C5500, "Texas Instruments TMS320C55x DSP family"),
1239 ENUM_ENT(EM_MMDSP_PLUS, "STMicroelectronics 64bit VLIW Data Signal Processor"),
1240 ENUM_ENT(EM_CYPRESS_M8C, "Cypress M8C microprocessor"),
1241 ENUM_ENT(EM_R32C, "Renesas R32C series microprocessors"),
1242 ENUM_ENT(EM_TRIMEDIA, "NXP Semiconductors TriMedia architecture family"),
1243 ENUM_ENT(EM_HEXAGON, "Qualcomm Hexagon"),
1244 ENUM_ENT(EM_8051, "Intel 8051 and variants"),
1245 ENUM_ENT(EM_STXP7X, "STMicroelectronics STxP7x family"),
1246 ENUM_ENT(EM_NDS32, "Andes Technology compact code size embedded RISC processor family"),
1247 ENUM_ENT(EM_ECOG1, "Cyan Technology eCOG1 microprocessor"),
1248 // FIXME: Following EM_ECOG1X definitions is dead code since EM_ECOG1X has
1249 // an identical number to EM_ECOG1.
1250 ENUM_ENT(EM_ECOG1X, "Cyan Technology eCOG1X family"),
1251 ENUM_ENT(EM_MAXQ30, "Dallas Semiconductor MAXQ30 Core microcontrollers"),
1252 ENUM_ENT(EM_XIMO16, "New Japan Radio (NJR) 16-bit DSP Processor"),
1253 ENUM_ENT(EM_MANIK, "M2000 Reconfigurable RISC Microprocessor"),
1254 ENUM_ENT(EM_CRAYNV2, "Cray Inc. NV2 vector architecture"),
1255 ENUM_ENT(EM_RX, "Renesas RX"),
1256 ENUM_ENT(EM_METAG, "Imagination Technologies Meta processor architecture"),
1257 ENUM_ENT(EM_MCST_ELBRUS, "MCST Elbrus general purpose hardware architecture"),
1258 ENUM_ENT(EM_ECOG16, "Cyan Technology eCOG16 family"),
1259 ENUM_ENT(EM_CR16, "National Semiconductor CompactRISC 16-bit processor"),
1260 ENUM_ENT(EM_ETPU, "Freescale Extended Time Processing Unit"),
1261 ENUM_ENT(EM_SLE9X, "Infineon Technologies SLE9X core"),
1262 ENUM_ENT(EM_L10M, "EM_L10M"),
1263 ENUM_ENT(EM_K10M, "EM_K10M"),
1264 ENUM_ENT(EM_AARCH64, "AArch64"),
1265 ENUM_ENT(EM_AVR32, "Atmel Corporation 32-bit microprocessor family"),
1266 ENUM_ENT(EM_STM8, "STMicroeletronics STM8 8-bit microcontroller"),
1267 ENUM_ENT(EM_TILE64, "Tilera TILE64 multicore architecture family"),
1268 ENUM_ENT(EM_TILEPRO, "Tilera TILEPro multicore architecture family"),
1269 ENUM_ENT(EM_MICROBLAZE, "Xilinx MicroBlaze 32-bit RISC soft processor core"),
1270 ENUM_ENT(EM_CUDA, "NVIDIA CUDA architecture"),
1271 ENUM_ENT(EM_TILEGX, "Tilera TILE-Gx multicore architecture family"),
1272 ENUM_ENT(EM_CLOUDSHIELD, "EM_CLOUDSHIELD"),
1273 ENUM_ENT(EM_COREA_1ST, "EM_COREA_1ST"),
1274 ENUM_ENT(EM_COREA_2ND, "EM_COREA_2ND"),
1275 ENUM_ENT(EM_ARC_COMPACT2, "EM_ARC_COMPACT2"),
1276 ENUM_ENT(EM_OPEN8, "EM_OPEN8"),
1277 ENUM_ENT(EM_RL78, "Renesas RL78"),
1278 ENUM_ENT(EM_VIDEOCORE5, "Broadcom VideoCore V processor"),
1279 ENUM_ENT(EM_78KOR, "EM_78KOR"),
1280 ENUM_ENT(EM_56800EX, "EM_56800EX"),
1281 ENUM_ENT(EM_AMDGPU, "EM_AMDGPU"),
1282 ENUM_ENT(EM_RISCV, "RISC-V"),
1283 ENUM_ENT(EM_LANAI, "EM_LANAI"),
1284 ENUM_ENT(EM_BPF, "EM_BPF"),
1285 ENUM_ENT(EM_VE, "NEC SX-Aurora Vector Engine"),
1286 ENUM_ENT(EM_LOONGARCH, "LoongArch"),
1289 const EnumEntry<unsigned> ElfSymbolBindings[] = {
1290 {"Local", "LOCAL", ELF::STB_LOCAL},
1291 {"Global", "GLOBAL", ELF::STB_GLOBAL},
1292 {"Weak", "WEAK", ELF::STB_WEAK},
1293 {"Unique", "UNIQUE", ELF::STB_GNU_UNIQUE}};
1295 const EnumEntry<unsigned> ElfSymbolVisibilities[] = {
1296 {"DEFAULT", "DEFAULT", ELF::STV_DEFAULT},
1297 {"INTERNAL", "INTERNAL", ELF::STV_INTERNAL},
1298 {"HIDDEN", "HIDDEN", ELF::STV_HIDDEN},
1299 {"PROTECTED", "PROTECTED", ELF::STV_PROTECTED}};
1301 const EnumEntry<unsigned> AMDGPUSymbolTypes[] = {
1302 { "AMDGPU_HSA_KERNEL", ELF::STT_AMDGPU_HSA_KERNEL }
1305 static const char *getGroupType(uint32_t Flag) {
1306 if (Flag & ELF::GRP_COMDAT)
1307 return "COMDAT";
1308 else
1309 return "(unknown)";
1312 const EnumEntry<unsigned> ElfSectionFlags[] = {
1313 ENUM_ENT(SHF_WRITE, "W"),
1314 ENUM_ENT(SHF_ALLOC, "A"),
1315 ENUM_ENT(SHF_EXECINSTR, "X"),
1316 ENUM_ENT(SHF_MERGE, "M"),
1317 ENUM_ENT(SHF_STRINGS, "S"),
1318 ENUM_ENT(SHF_INFO_LINK, "I"),
1319 ENUM_ENT(SHF_LINK_ORDER, "L"),
1320 ENUM_ENT(SHF_OS_NONCONFORMING, "O"),
1321 ENUM_ENT(SHF_GROUP, "G"),
1322 ENUM_ENT(SHF_TLS, "T"),
1323 ENUM_ENT(SHF_COMPRESSED, "C"),
1324 ENUM_ENT(SHF_EXCLUDE, "E"),
1327 const EnumEntry<unsigned> ElfGNUSectionFlags[] = {
1328 ENUM_ENT(SHF_GNU_RETAIN, "R")
1331 const EnumEntry<unsigned> ElfSolarisSectionFlags[] = {
1332 ENUM_ENT(SHF_SUNW_NODISCARD, "R")
1335 const EnumEntry<unsigned> ElfXCoreSectionFlags[] = {
1336 ENUM_ENT(XCORE_SHF_CP_SECTION, ""),
1337 ENUM_ENT(XCORE_SHF_DP_SECTION, "")
1340 const EnumEntry<unsigned> ElfARMSectionFlags[] = {
1341 ENUM_ENT(SHF_ARM_PURECODE, "y")
1344 const EnumEntry<unsigned> ElfHexagonSectionFlags[] = {
1345 ENUM_ENT(SHF_HEX_GPREL, "")
1348 const EnumEntry<unsigned> ElfMipsSectionFlags[] = {
1349 ENUM_ENT(SHF_MIPS_NODUPES, ""),
1350 ENUM_ENT(SHF_MIPS_NAMES, ""),
1351 ENUM_ENT(SHF_MIPS_LOCAL, ""),
1352 ENUM_ENT(SHF_MIPS_NOSTRIP, ""),
1353 ENUM_ENT(SHF_MIPS_GPREL, ""),
1354 ENUM_ENT(SHF_MIPS_MERGE, ""),
1355 ENUM_ENT(SHF_MIPS_ADDR, ""),
1356 ENUM_ENT(SHF_MIPS_STRING, "")
1359 const EnumEntry<unsigned> ElfX86_64SectionFlags[] = {
1360 ENUM_ENT(SHF_X86_64_LARGE, "l")
1363 static std::vector<EnumEntry<unsigned>>
1364 getSectionFlagsForTarget(unsigned EOSAbi, unsigned EMachine) {
1365 std::vector<EnumEntry<unsigned>> Ret(std::begin(ElfSectionFlags),
1366 std::end(ElfSectionFlags));
1367 switch (EOSAbi) {
1368 case ELFOSABI_SOLARIS:
1369 Ret.insert(Ret.end(), std::begin(ElfSolarisSectionFlags),
1370 std::end(ElfSolarisSectionFlags));
1371 break;
1372 default:
1373 Ret.insert(Ret.end(), std::begin(ElfGNUSectionFlags),
1374 std::end(ElfGNUSectionFlags));
1375 break;
1377 switch (EMachine) {
1378 case EM_ARM:
1379 Ret.insert(Ret.end(), std::begin(ElfARMSectionFlags),
1380 std::end(ElfARMSectionFlags));
1381 break;
1382 case EM_HEXAGON:
1383 Ret.insert(Ret.end(), std::begin(ElfHexagonSectionFlags),
1384 std::end(ElfHexagonSectionFlags));
1385 break;
1386 case EM_MIPS:
1387 Ret.insert(Ret.end(), std::begin(ElfMipsSectionFlags),
1388 std::end(ElfMipsSectionFlags));
1389 break;
1390 case EM_X86_64:
1391 Ret.insert(Ret.end(), std::begin(ElfX86_64SectionFlags),
1392 std::end(ElfX86_64SectionFlags));
1393 break;
1394 case EM_XCORE:
1395 Ret.insert(Ret.end(), std::begin(ElfXCoreSectionFlags),
1396 std::end(ElfXCoreSectionFlags));
1397 break;
1398 default:
1399 break;
1401 return Ret;
1404 static std::string getGNUFlags(unsigned EOSAbi, unsigned EMachine,
1405 uint64_t Flags) {
1406 // Here we are trying to build the flags string in the same way as GNU does.
1407 // It is not that straightforward. Imagine we have sh_flags == 0x90000000.
1408 // SHF_EXCLUDE ("E") has a value of 0x80000000 and SHF_MASKPROC is 0xf0000000.
1409 // GNU readelf will not print "E" or "Ep" in this case, but will print just
1410 // "p". It only will print "E" when no other processor flag is set.
1411 std::string Str;
1412 bool HasUnknownFlag = false;
1413 bool HasOSFlag = false;
1414 bool HasProcFlag = false;
1415 std::vector<EnumEntry<unsigned>> FlagsList =
1416 getSectionFlagsForTarget(EOSAbi, EMachine);
1417 while (Flags) {
1418 // Take the least significant bit as a flag.
1419 uint64_t Flag = Flags & -Flags;
1420 Flags -= Flag;
1422 // Find the flag in the known flags list.
1423 auto I = llvm::find_if(FlagsList, [=](const EnumEntry<unsigned> &E) {
1424 // Flags with empty names are not printed in GNU style output.
1425 return E.Value == Flag && !E.AltName.empty();
1427 if (I != FlagsList.end()) {
1428 Str += I->AltName;
1429 continue;
1432 // If we did not find a matching regular flag, then we deal with an OS
1433 // specific flag, processor specific flag or an unknown flag.
1434 if (Flag & ELF::SHF_MASKOS) {
1435 HasOSFlag = true;
1436 Flags &= ~ELF::SHF_MASKOS;
1437 } else if (Flag & ELF::SHF_MASKPROC) {
1438 HasProcFlag = true;
1439 // Mask off all the processor-specific bits. This removes the SHF_EXCLUDE
1440 // bit if set so that it doesn't also get printed.
1441 Flags &= ~ELF::SHF_MASKPROC;
1442 } else {
1443 HasUnknownFlag = true;
1447 // "o", "p" and "x" are printed last.
1448 if (HasOSFlag)
1449 Str += "o";
1450 if (HasProcFlag)
1451 Str += "p";
1452 if (HasUnknownFlag)
1453 Str += "x";
1454 return Str;
1457 static StringRef segmentTypeToString(unsigned Arch, unsigned Type) {
1458 // Check potentially overlapped processor-specific program header type.
1459 switch (Arch) {
1460 case ELF::EM_ARM:
1461 switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_ARM_EXIDX); }
1462 break;
1463 case ELF::EM_MIPS:
1464 case ELF::EM_MIPS_RS3_LE:
1465 switch (Type) {
1466 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_REGINFO);
1467 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_RTPROC);
1468 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_OPTIONS);
1469 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_ABIFLAGS);
1471 break;
1472 case ELF::EM_RISCV:
1473 switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_RISCV_ATTRIBUTES); }
1476 switch (Type) {
1477 LLVM_READOBJ_ENUM_CASE(ELF, PT_NULL);
1478 LLVM_READOBJ_ENUM_CASE(ELF, PT_LOAD);
1479 LLVM_READOBJ_ENUM_CASE(ELF, PT_DYNAMIC);
1480 LLVM_READOBJ_ENUM_CASE(ELF, PT_INTERP);
1481 LLVM_READOBJ_ENUM_CASE(ELF, PT_NOTE);
1482 LLVM_READOBJ_ENUM_CASE(ELF, PT_SHLIB);
1483 LLVM_READOBJ_ENUM_CASE(ELF, PT_PHDR);
1484 LLVM_READOBJ_ENUM_CASE(ELF, PT_TLS);
1486 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_EH_FRAME);
1487 LLVM_READOBJ_ENUM_CASE(ELF, PT_SUNW_UNWIND);
1489 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_STACK);
1490 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_RELRO);
1491 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_PROPERTY);
1493 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_MUTABLE);
1494 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_RANDOMIZE);
1495 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_WXNEEDED);
1496 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_NOBTCFI);
1497 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_SYSCALLS);
1498 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_BOOTDATA);
1499 default:
1500 return "";
1504 static std::string getGNUPtType(unsigned Arch, unsigned Type) {
1505 StringRef Seg = segmentTypeToString(Arch, Type);
1506 if (Seg.empty())
1507 return std::string("<unknown>: ") + to_string(format_hex(Type, 1));
1509 // E.g. "PT_ARM_EXIDX" -> "EXIDX".
1510 if (Seg.consume_front("PT_ARM_"))
1511 return Seg.str();
1513 // E.g. "PT_MIPS_REGINFO" -> "REGINFO".
1514 if (Seg.consume_front("PT_MIPS_"))
1515 return Seg.str();
1517 // E.g. "PT_RISCV_ATTRIBUTES"
1518 if (Seg.consume_front("PT_RISCV_"))
1519 return Seg.str();
1521 // E.g. "PT_LOAD" -> "LOAD".
1522 assert(Seg.starts_with("PT_"));
1523 return Seg.drop_front(3).str();
1526 const EnumEntry<unsigned> ElfSegmentFlags[] = {
1527 LLVM_READOBJ_ENUM_ENT(ELF, PF_X),
1528 LLVM_READOBJ_ENUM_ENT(ELF, PF_W),
1529 LLVM_READOBJ_ENUM_ENT(ELF, PF_R)
1532 const EnumEntry<unsigned> ElfHeaderMipsFlags[] = {
1533 ENUM_ENT(EF_MIPS_NOREORDER, "noreorder"),
1534 ENUM_ENT(EF_MIPS_PIC, "pic"),
1535 ENUM_ENT(EF_MIPS_CPIC, "cpic"),
1536 ENUM_ENT(EF_MIPS_ABI2, "abi2"),
1537 ENUM_ENT(EF_MIPS_32BITMODE, "32bitmode"),
1538 ENUM_ENT(EF_MIPS_FP64, "fp64"),
1539 ENUM_ENT(EF_MIPS_NAN2008, "nan2008"),
1540 ENUM_ENT(EF_MIPS_ABI_O32, "o32"),
1541 ENUM_ENT(EF_MIPS_ABI_O64, "o64"),
1542 ENUM_ENT(EF_MIPS_ABI_EABI32, "eabi32"),
1543 ENUM_ENT(EF_MIPS_ABI_EABI64, "eabi64"),
1544 ENUM_ENT(EF_MIPS_MACH_3900, "3900"),
1545 ENUM_ENT(EF_MIPS_MACH_4010, "4010"),
1546 ENUM_ENT(EF_MIPS_MACH_4100, "4100"),
1547 ENUM_ENT(EF_MIPS_MACH_4650, "4650"),
1548 ENUM_ENT(EF_MIPS_MACH_4120, "4120"),
1549 ENUM_ENT(EF_MIPS_MACH_4111, "4111"),
1550 ENUM_ENT(EF_MIPS_MACH_SB1, "sb1"),
1551 ENUM_ENT(EF_MIPS_MACH_OCTEON, "octeon"),
1552 ENUM_ENT(EF_MIPS_MACH_XLR, "xlr"),
1553 ENUM_ENT(EF_MIPS_MACH_OCTEON2, "octeon2"),
1554 ENUM_ENT(EF_MIPS_MACH_OCTEON3, "octeon3"),
1555 ENUM_ENT(EF_MIPS_MACH_5400, "5400"),
1556 ENUM_ENT(EF_MIPS_MACH_5900, "5900"),
1557 ENUM_ENT(EF_MIPS_MACH_5500, "5500"),
1558 ENUM_ENT(EF_MIPS_MACH_9000, "9000"),
1559 ENUM_ENT(EF_MIPS_MACH_LS2E, "loongson-2e"),
1560 ENUM_ENT(EF_MIPS_MACH_LS2F, "loongson-2f"),
1561 ENUM_ENT(EF_MIPS_MACH_LS3A, "loongson-3a"),
1562 ENUM_ENT(EF_MIPS_MICROMIPS, "micromips"),
1563 ENUM_ENT(EF_MIPS_ARCH_ASE_M16, "mips16"),
1564 ENUM_ENT(EF_MIPS_ARCH_ASE_MDMX, "mdmx"),
1565 ENUM_ENT(EF_MIPS_ARCH_1, "mips1"),
1566 ENUM_ENT(EF_MIPS_ARCH_2, "mips2"),
1567 ENUM_ENT(EF_MIPS_ARCH_3, "mips3"),
1568 ENUM_ENT(EF_MIPS_ARCH_4, "mips4"),
1569 ENUM_ENT(EF_MIPS_ARCH_5, "mips5"),
1570 ENUM_ENT(EF_MIPS_ARCH_32, "mips32"),
1571 ENUM_ENT(EF_MIPS_ARCH_64, "mips64"),
1572 ENUM_ENT(EF_MIPS_ARCH_32R2, "mips32r2"),
1573 ENUM_ENT(EF_MIPS_ARCH_64R2, "mips64r2"),
1574 ENUM_ENT(EF_MIPS_ARCH_32R6, "mips32r6"),
1575 ENUM_ENT(EF_MIPS_ARCH_64R6, "mips64r6")
1578 // clang-format off
1579 #define AMDGPU_MACH_ENUM_ENTS \
1580 ENUM_ENT(EF_AMDGPU_MACH_NONE, "none"), \
1581 ENUM_ENT(EF_AMDGPU_MACH_R600_R600, "r600"), \
1582 ENUM_ENT(EF_AMDGPU_MACH_R600_R630, "r630"), \
1583 ENUM_ENT(EF_AMDGPU_MACH_R600_RS880, "rs880"), \
1584 ENUM_ENT(EF_AMDGPU_MACH_R600_RV670, "rv670"), \
1585 ENUM_ENT(EF_AMDGPU_MACH_R600_RV710, "rv710"), \
1586 ENUM_ENT(EF_AMDGPU_MACH_R600_RV730, "rv730"), \
1587 ENUM_ENT(EF_AMDGPU_MACH_R600_RV770, "rv770"), \
1588 ENUM_ENT(EF_AMDGPU_MACH_R600_CEDAR, "cedar"), \
1589 ENUM_ENT(EF_AMDGPU_MACH_R600_CYPRESS, "cypress"), \
1590 ENUM_ENT(EF_AMDGPU_MACH_R600_JUNIPER, "juniper"), \
1591 ENUM_ENT(EF_AMDGPU_MACH_R600_REDWOOD, "redwood"), \
1592 ENUM_ENT(EF_AMDGPU_MACH_R600_SUMO, "sumo"), \
1593 ENUM_ENT(EF_AMDGPU_MACH_R600_BARTS, "barts"), \
1594 ENUM_ENT(EF_AMDGPU_MACH_R600_CAICOS, "caicos"), \
1595 ENUM_ENT(EF_AMDGPU_MACH_R600_CAYMAN, "cayman"), \
1596 ENUM_ENT(EF_AMDGPU_MACH_R600_TURKS, "turks"), \
1597 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX600, "gfx600"), \
1598 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX601, "gfx601"), \
1599 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX602, "gfx602"), \
1600 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX700, "gfx700"), \
1601 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX701, "gfx701"), \
1602 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX702, "gfx702"), \
1603 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX703, "gfx703"), \
1604 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX704, "gfx704"), \
1605 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX705, "gfx705"), \
1606 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX801, "gfx801"), \
1607 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX802, "gfx802"), \
1608 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX803, "gfx803"), \
1609 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX805, "gfx805"), \
1610 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX810, "gfx810"), \
1611 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX900, "gfx900"), \
1612 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX902, "gfx902"), \
1613 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX904, "gfx904"), \
1614 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX906, "gfx906"), \
1615 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX908, "gfx908"), \
1616 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX909, "gfx909"), \
1617 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX90A, "gfx90a"), \
1618 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX90C, "gfx90c"), \
1619 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX940, "gfx940"), \
1620 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX941, "gfx941"), \
1621 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX942, "gfx942"), \
1622 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX950, "gfx950"), \
1623 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1010, "gfx1010"), \
1624 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1011, "gfx1011"), \
1625 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1012, "gfx1012"), \
1626 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1013, "gfx1013"), \
1627 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1030, "gfx1030"), \
1628 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1031, "gfx1031"), \
1629 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1032, "gfx1032"), \
1630 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1033, "gfx1033"), \
1631 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1034, "gfx1034"), \
1632 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1035, "gfx1035"), \
1633 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1036, "gfx1036"), \
1634 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1100, "gfx1100"), \
1635 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1101, "gfx1101"), \
1636 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1102, "gfx1102"), \
1637 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1103, "gfx1103"), \
1638 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1150, "gfx1150"), \
1639 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1151, "gfx1151"), \
1640 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1152, "gfx1152"), \
1641 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1153, "gfx1153"), \
1642 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1200, "gfx1200"), \
1643 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX1201, "gfx1201"), \
1644 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX9_GENERIC, "gfx9-generic"), \
1645 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX9_4_GENERIC, "gfx9-4-generic"), \
1646 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX10_1_GENERIC, "gfx10-1-generic"), \
1647 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX10_3_GENERIC, "gfx10-3-generic"), \
1648 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX11_GENERIC, "gfx11-generic"), \
1649 ENUM_ENT(EF_AMDGPU_MACH_AMDGCN_GFX12_GENERIC, "gfx12-generic")
1650 // clang-format on
1652 const EnumEntry<unsigned> ElfHeaderAMDGPUFlagsABIVersion3[] = {
1653 AMDGPU_MACH_ENUM_ENTS,
1654 ENUM_ENT(EF_AMDGPU_FEATURE_XNACK_V3, "xnack"),
1655 ENUM_ENT(EF_AMDGPU_FEATURE_SRAMECC_V3, "sramecc"),
1658 const EnumEntry<unsigned> ElfHeaderAMDGPUFlagsABIVersion4[] = {
1659 AMDGPU_MACH_ENUM_ENTS,
1660 ENUM_ENT(EF_AMDGPU_FEATURE_XNACK_ANY_V4, "xnack"),
1661 ENUM_ENT(EF_AMDGPU_FEATURE_XNACK_OFF_V4, "xnack-"),
1662 ENUM_ENT(EF_AMDGPU_FEATURE_XNACK_ON_V4, "xnack+"),
1663 ENUM_ENT(EF_AMDGPU_FEATURE_SRAMECC_ANY_V4, "sramecc"),
1664 ENUM_ENT(EF_AMDGPU_FEATURE_SRAMECC_OFF_V4, "sramecc-"),
1665 ENUM_ENT(EF_AMDGPU_FEATURE_SRAMECC_ON_V4, "sramecc+"),
1668 const EnumEntry<unsigned> ElfHeaderNVPTXFlags[] = {
1669 ENUM_ENT(EF_CUDA_SM20, "sm_20"), ENUM_ENT(EF_CUDA_SM21, "sm_21"),
1670 ENUM_ENT(EF_CUDA_SM30, "sm_30"), ENUM_ENT(EF_CUDA_SM32, "sm_32"),
1671 ENUM_ENT(EF_CUDA_SM35, "sm_35"), ENUM_ENT(EF_CUDA_SM37, "sm_37"),
1672 ENUM_ENT(EF_CUDA_SM50, "sm_50"), ENUM_ENT(EF_CUDA_SM52, "sm_52"),
1673 ENUM_ENT(EF_CUDA_SM53, "sm_53"), ENUM_ENT(EF_CUDA_SM60, "sm_60"),
1674 ENUM_ENT(EF_CUDA_SM61, "sm_61"), ENUM_ENT(EF_CUDA_SM62, "sm_62"),
1675 ENUM_ENT(EF_CUDA_SM70, "sm_70"), ENUM_ENT(EF_CUDA_SM72, "sm_72"),
1676 ENUM_ENT(EF_CUDA_SM75, "sm_75"), ENUM_ENT(EF_CUDA_SM80, "sm_80"),
1677 ENUM_ENT(EF_CUDA_SM86, "sm_86"), ENUM_ENT(EF_CUDA_SM87, "sm_87"),
1678 ENUM_ENT(EF_CUDA_SM89, "sm_89"), ENUM_ENT(EF_CUDA_SM90, "sm_90"),
1681 const EnumEntry<unsigned> ElfHeaderRISCVFlags[] = {
1682 ENUM_ENT(EF_RISCV_RVC, "RVC"),
1683 ENUM_ENT(EF_RISCV_FLOAT_ABI_SINGLE, "single-float ABI"),
1684 ENUM_ENT(EF_RISCV_FLOAT_ABI_DOUBLE, "double-float ABI"),
1685 ENUM_ENT(EF_RISCV_FLOAT_ABI_QUAD, "quad-float ABI"),
1686 ENUM_ENT(EF_RISCV_RVE, "RVE"),
1687 ENUM_ENT(EF_RISCV_TSO, "TSO"),
1690 const EnumEntry<unsigned> ElfHeaderSPARCFlags[] = {
1691 ENUM_ENT(EF_SPARC_32PLUS, "V8+ ABI"),
1692 ENUM_ENT(EF_SPARC_SUN_US1, "Sun UltraSPARC I extensions"),
1693 ENUM_ENT(EF_SPARC_HAL_R1, "HAL/Fujitsu R1 extensions"),
1694 ENUM_ENT(EF_SPARC_SUN_US3, "Sun UltraSPARC III extensions"),
1695 ENUM_ENT(EF_SPARCV9_TSO, "Total Store Ordering"),
1696 ENUM_ENT(EF_SPARCV9_PSO, "Partial Store Ordering"),
1697 ENUM_ENT(EF_SPARCV9_RMO, "Relaxed Memory Ordering"),
1700 const EnumEntry<unsigned> ElfHeaderAVRFlags[] = {
1701 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR1),
1702 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR2),
1703 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR25),
1704 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR3),
1705 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR31),
1706 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR35),
1707 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR4),
1708 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR5),
1709 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR51),
1710 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR6),
1711 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVRTINY),
1712 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA1),
1713 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA2),
1714 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA3),
1715 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA4),
1716 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA5),
1717 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA6),
1718 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA7),
1719 ENUM_ENT(EF_AVR_LINKRELAX_PREPARED, "relaxable"),
1722 const EnumEntry<unsigned> ElfHeaderLoongArchFlags[] = {
1723 ENUM_ENT(EF_LOONGARCH_ABI_SOFT_FLOAT, "SOFT-FLOAT"),
1724 ENUM_ENT(EF_LOONGARCH_ABI_SINGLE_FLOAT, "SINGLE-FLOAT"),
1725 ENUM_ENT(EF_LOONGARCH_ABI_DOUBLE_FLOAT, "DOUBLE-FLOAT"),
1726 ENUM_ENT(EF_LOONGARCH_OBJABI_V0, "OBJ-v0"),
1727 ENUM_ENT(EF_LOONGARCH_OBJABI_V1, "OBJ-v1"),
1730 static const EnumEntry<unsigned> ElfHeaderXtensaFlags[] = {
1731 LLVM_READOBJ_ENUM_ENT(ELF, EF_XTENSA_MACH_NONE),
1732 LLVM_READOBJ_ENUM_ENT(ELF, EF_XTENSA_XT_INSN),
1733 LLVM_READOBJ_ENUM_ENT(ELF, EF_XTENSA_XT_LIT)
1736 const EnumEntry<unsigned> ElfSymOtherFlags[] = {
1737 LLVM_READOBJ_ENUM_ENT(ELF, STV_INTERNAL),
1738 LLVM_READOBJ_ENUM_ENT(ELF, STV_HIDDEN),
1739 LLVM_READOBJ_ENUM_ENT(ELF, STV_PROTECTED)
1742 const EnumEntry<unsigned> ElfMipsSymOtherFlags[] = {
1743 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL),
1744 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT),
1745 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PIC),
1746 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MICROMIPS)
1749 const EnumEntry<unsigned> ElfAArch64SymOtherFlags[] = {
1750 LLVM_READOBJ_ENUM_ENT(ELF, STO_AARCH64_VARIANT_PCS)
1753 const EnumEntry<unsigned> ElfMips16SymOtherFlags[] = {
1754 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL),
1755 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT),
1756 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MIPS16)
1759 const EnumEntry<unsigned> ElfRISCVSymOtherFlags[] = {
1760 LLVM_READOBJ_ENUM_ENT(ELF, STO_RISCV_VARIANT_CC)};
1762 static const char *getElfMipsOptionsOdkType(unsigned Odk) {
1763 switch (Odk) {
1764 LLVM_READOBJ_ENUM_CASE(ELF, ODK_NULL);
1765 LLVM_READOBJ_ENUM_CASE(ELF, ODK_REGINFO);
1766 LLVM_READOBJ_ENUM_CASE(ELF, ODK_EXCEPTIONS);
1767 LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAD);
1768 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWPATCH);
1769 LLVM_READOBJ_ENUM_CASE(ELF, ODK_FILL);
1770 LLVM_READOBJ_ENUM_CASE(ELF, ODK_TAGS);
1771 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWAND);
1772 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWOR);
1773 LLVM_READOBJ_ENUM_CASE(ELF, ODK_GP_GROUP);
1774 LLVM_READOBJ_ENUM_CASE(ELF, ODK_IDENT);
1775 LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAGESIZE);
1776 default:
1777 return "Unknown";
1781 template <typename ELFT>
1782 std::pair<const typename ELFT::Phdr *, const typename ELFT::Shdr *>
1783 ELFDumper<ELFT>::findDynamic() {
1784 // Try to locate the PT_DYNAMIC header.
1785 const Elf_Phdr *DynamicPhdr = nullptr;
1786 if (Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = Obj.program_headers()) {
1787 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
1788 if (Phdr.p_type != ELF::PT_DYNAMIC)
1789 continue;
1790 DynamicPhdr = &Phdr;
1791 break;
1793 } else {
1794 reportUniqueWarning(
1795 "unable to read program headers to locate the PT_DYNAMIC segment: " +
1796 toString(PhdrsOrErr.takeError()));
1799 // Try to locate the .dynamic section in the sections header table.
1800 const Elf_Shdr *DynamicSec = nullptr;
1801 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
1802 if (Sec.sh_type != ELF::SHT_DYNAMIC)
1803 continue;
1804 DynamicSec = &Sec;
1805 break;
1808 if (DynamicPhdr && ((DynamicPhdr->p_offset + DynamicPhdr->p_filesz >
1809 ObjF.getMemoryBufferRef().getBufferSize()) ||
1810 (DynamicPhdr->p_offset + DynamicPhdr->p_filesz <
1811 DynamicPhdr->p_offset))) {
1812 reportUniqueWarning(
1813 "PT_DYNAMIC segment offset (0x" +
1814 Twine::utohexstr(DynamicPhdr->p_offset) + ") + file size (0x" +
1815 Twine::utohexstr(DynamicPhdr->p_filesz) +
1816 ") exceeds the size of the file (0x" +
1817 Twine::utohexstr(ObjF.getMemoryBufferRef().getBufferSize()) + ")");
1818 // Don't use the broken dynamic header.
1819 DynamicPhdr = nullptr;
1822 if (DynamicPhdr && DynamicSec) {
1823 if (DynamicSec->sh_addr + DynamicSec->sh_size >
1824 DynamicPhdr->p_vaddr + DynamicPhdr->p_memsz ||
1825 DynamicSec->sh_addr < DynamicPhdr->p_vaddr)
1826 reportUniqueWarning(describe(*DynamicSec) +
1827 " is not contained within the "
1828 "PT_DYNAMIC segment");
1830 if (DynamicSec->sh_addr != DynamicPhdr->p_vaddr)
1831 reportUniqueWarning(describe(*DynamicSec) + " is not at the start of "
1832 "PT_DYNAMIC segment");
1835 return std::make_pair(DynamicPhdr, DynamicSec);
1838 template <typename ELFT>
1839 void ELFDumper<ELFT>::loadDynamicTable() {
1840 const Elf_Phdr *DynamicPhdr;
1841 const Elf_Shdr *DynamicSec;
1842 std::tie(DynamicPhdr, DynamicSec) = findDynamic();
1843 if (!DynamicPhdr && !DynamicSec)
1844 return;
1846 DynRegionInfo FromPhdr(ObjF, *this);
1847 bool IsPhdrTableValid = false;
1848 if (DynamicPhdr) {
1849 // Use cantFail(), because p_offset/p_filesz fields of a PT_DYNAMIC are
1850 // validated in findDynamic() and so createDRI() is not expected to fail.
1851 FromPhdr = cantFail(createDRI(DynamicPhdr->p_offset, DynamicPhdr->p_filesz,
1852 sizeof(Elf_Dyn)));
1853 FromPhdr.SizePrintName = "PT_DYNAMIC size";
1854 FromPhdr.EntSizePrintName = "";
1855 IsPhdrTableValid = !FromPhdr.template getAsArrayRef<Elf_Dyn>().empty();
1858 // Locate the dynamic table described in a section header.
1859 // Ignore sh_entsize and use the expected value for entry size explicitly.
1860 // This allows us to dump dynamic sections with a broken sh_entsize
1861 // field.
1862 DynRegionInfo FromSec(ObjF, *this);
1863 bool IsSecTableValid = false;
1864 if (DynamicSec) {
1865 Expected<DynRegionInfo> RegOrErr =
1866 createDRI(DynamicSec->sh_offset, DynamicSec->sh_size, sizeof(Elf_Dyn));
1867 if (RegOrErr) {
1868 FromSec = *RegOrErr;
1869 FromSec.Context = describe(*DynamicSec);
1870 FromSec.EntSizePrintName = "";
1871 IsSecTableValid = !FromSec.template getAsArrayRef<Elf_Dyn>().empty();
1872 } else {
1873 reportUniqueWarning("unable to read the dynamic table from " +
1874 describe(*DynamicSec) + ": " +
1875 toString(RegOrErr.takeError()));
1879 // When we only have information from one of the SHT_DYNAMIC section header or
1880 // PT_DYNAMIC program header, just use that.
1881 if (!DynamicPhdr || !DynamicSec) {
1882 if ((DynamicPhdr && IsPhdrTableValid) || (DynamicSec && IsSecTableValid)) {
1883 DynamicTable = DynamicPhdr ? FromPhdr : FromSec;
1884 parseDynamicTable();
1885 } else {
1886 reportUniqueWarning("no valid dynamic table was found");
1888 return;
1891 // At this point we have tables found from the section header and from the
1892 // dynamic segment. Usually they match, but we have to do sanity checks to
1893 // verify that.
1895 if (FromPhdr.Addr != FromSec.Addr)
1896 reportUniqueWarning("SHT_DYNAMIC section header and PT_DYNAMIC "
1897 "program header disagree about "
1898 "the location of the dynamic table");
1900 if (!IsPhdrTableValid && !IsSecTableValid) {
1901 reportUniqueWarning("no valid dynamic table was found");
1902 return;
1905 // Information in the PT_DYNAMIC program header has priority over the
1906 // information in a section header.
1907 if (IsPhdrTableValid) {
1908 if (!IsSecTableValid)
1909 reportUniqueWarning(
1910 "SHT_DYNAMIC dynamic table is invalid: PT_DYNAMIC will be used");
1911 DynamicTable = FromPhdr;
1912 } else {
1913 reportUniqueWarning(
1914 "PT_DYNAMIC dynamic table is invalid: SHT_DYNAMIC will be used");
1915 DynamicTable = FromSec;
1918 parseDynamicTable();
1921 template <typename ELFT>
1922 ELFDumper<ELFT>::ELFDumper(const object::ELFObjectFile<ELFT> &O,
1923 ScopedPrinter &Writer)
1924 : ObjDumper(Writer, O.getFileName()), ObjF(O), Obj(O.getELFFile()),
1925 FileName(O.getFileName()), DynRelRegion(O, *this),
1926 DynRelaRegion(O, *this), DynCrelRegion(O, *this), DynRelrRegion(O, *this),
1927 DynPLTRelRegion(O, *this), DynSymTabShndxRegion(O, *this),
1928 DynamicTable(O, *this) {
1929 if (!O.IsContentValid())
1930 return;
1932 typename ELFT::ShdrRange Sections = cantFail(Obj.sections());
1933 for (const Elf_Shdr &Sec : Sections) {
1934 switch (Sec.sh_type) {
1935 case ELF::SHT_SYMTAB:
1936 if (!DotSymtabSec)
1937 DotSymtabSec = &Sec;
1938 break;
1939 case ELF::SHT_DYNSYM:
1940 if (!DotDynsymSec)
1941 DotDynsymSec = &Sec;
1943 if (!DynSymRegion) {
1944 Expected<DynRegionInfo> RegOrErr =
1945 createDRI(Sec.sh_offset, Sec.sh_size, Sec.sh_entsize);
1946 if (RegOrErr) {
1947 DynSymRegion = *RegOrErr;
1948 DynSymRegion->Context = describe(Sec);
1950 if (Expected<StringRef> E = Obj.getStringTableForSymtab(Sec))
1951 DynamicStringTable = *E;
1952 else
1953 reportUniqueWarning("unable to get the string table for the " +
1954 describe(Sec) + ": " + toString(E.takeError()));
1955 } else {
1956 reportUniqueWarning("unable to read dynamic symbols from " +
1957 describe(Sec) + ": " +
1958 toString(RegOrErr.takeError()));
1961 break;
1962 case ELF::SHT_SYMTAB_SHNDX: {
1963 uint32_t SymtabNdx = Sec.sh_link;
1964 if (SymtabNdx >= Sections.size()) {
1965 reportUniqueWarning(
1966 "unable to get the associated symbol table for " + describe(Sec) +
1967 ": sh_link (" + Twine(SymtabNdx) +
1968 ") is greater than or equal to the total number of sections (" +
1969 Twine(Sections.size()) + ")");
1970 continue;
1973 if (Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
1974 Obj.getSHNDXTable(Sec)) {
1975 if (!ShndxTables.insert({&Sections[SymtabNdx], *ShndxTableOrErr})
1976 .second)
1977 reportUniqueWarning(
1978 "multiple SHT_SYMTAB_SHNDX sections are linked to " +
1979 describe(Sec));
1980 } else {
1981 reportUniqueWarning(ShndxTableOrErr.takeError());
1983 break;
1985 case ELF::SHT_GNU_versym:
1986 if (!SymbolVersionSection)
1987 SymbolVersionSection = &Sec;
1988 break;
1989 case ELF::SHT_GNU_verdef:
1990 if (!SymbolVersionDefSection)
1991 SymbolVersionDefSection = &Sec;
1992 break;
1993 case ELF::SHT_GNU_verneed:
1994 if (!SymbolVersionNeedSection)
1995 SymbolVersionNeedSection = &Sec;
1996 break;
1997 case ELF::SHT_LLVM_ADDRSIG:
1998 if (!DotAddrsigSec)
1999 DotAddrsigSec = &Sec;
2000 break;
2004 loadDynamicTable();
2007 template <typename ELFT> void ELFDumper<ELFT>::parseDynamicTable() {
2008 auto toMappedAddr = [&](uint64_t Tag, uint64_t VAddr) -> const uint8_t * {
2009 auto MappedAddrOrError = Obj.toMappedAddr(VAddr, [&](const Twine &Msg) {
2010 this->reportUniqueWarning(Msg);
2011 return Error::success();
2013 if (!MappedAddrOrError) {
2014 this->reportUniqueWarning("unable to parse DT_" +
2015 Obj.getDynamicTagAsString(Tag) + ": " +
2016 llvm::toString(MappedAddrOrError.takeError()));
2017 return nullptr;
2019 return MappedAddrOrError.get();
2022 const char *StringTableBegin = nullptr;
2023 uint64_t StringTableSize = 0;
2024 std::optional<DynRegionInfo> DynSymFromTable;
2025 for (const Elf_Dyn &Dyn : dynamic_table()) {
2026 if (Obj.getHeader().e_machine == EM_AARCH64) {
2027 switch (Dyn.d_tag) {
2028 case ELF::DT_AARCH64_AUTH_RELRSZ:
2029 DynRelrRegion.Size = Dyn.getVal();
2030 DynRelrRegion.SizePrintName = "DT_AARCH64_AUTH_RELRSZ value";
2031 continue;
2032 case ELF::DT_AARCH64_AUTH_RELRENT:
2033 DynRelrRegion.EntSize = Dyn.getVal();
2034 DynRelrRegion.EntSizePrintName = "DT_AARCH64_AUTH_RELRENT value";
2035 continue;
2038 switch (Dyn.d_tag) {
2039 case ELF::DT_HASH:
2040 HashTable = reinterpret_cast<const Elf_Hash *>(
2041 toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
2042 break;
2043 case ELF::DT_GNU_HASH:
2044 GnuHashTable = reinterpret_cast<const Elf_GnuHash *>(
2045 toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
2046 break;
2047 case ELF::DT_STRTAB:
2048 StringTableBegin = reinterpret_cast<const char *>(
2049 toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
2050 break;
2051 case ELF::DT_STRSZ:
2052 StringTableSize = Dyn.getVal();
2053 break;
2054 case ELF::DT_SYMTAB: {
2055 // If we can't map the DT_SYMTAB value to an address (e.g. when there are
2056 // no program headers), we ignore its value.
2057 if (const uint8_t *VA = toMappedAddr(Dyn.getTag(), Dyn.getPtr())) {
2058 DynSymFromTable.emplace(ObjF, *this);
2059 DynSymFromTable->Addr = VA;
2060 DynSymFromTable->EntSize = sizeof(Elf_Sym);
2061 DynSymFromTable->EntSizePrintName = "";
2063 break;
2065 case ELF::DT_SYMENT: {
2066 uint64_t Val = Dyn.getVal();
2067 if (Val != sizeof(Elf_Sym))
2068 this->reportUniqueWarning("DT_SYMENT value of 0x" +
2069 Twine::utohexstr(Val) +
2070 " is not the size of a symbol (0x" +
2071 Twine::utohexstr(sizeof(Elf_Sym)) + ")");
2072 break;
2074 case ELF::DT_RELA:
2075 DynRelaRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2076 break;
2077 case ELF::DT_RELASZ:
2078 DynRelaRegion.Size = Dyn.getVal();
2079 DynRelaRegion.SizePrintName = "DT_RELASZ value";
2080 break;
2081 case ELF::DT_RELAENT:
2082 DynRelaRegion.EntSize = Dyn.getVal();
2083 DynRelaRegion.EntSizePrintName = "DT_RELAENT value";
2084 break;
2085 case ELF::DT_CREL:
2086 DynCrelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2087 break;
2088 case ELF::DT_SONAME:
2089 SONameOffset = Dyn.getVal();
2090 break;
2091 case ELF::DT_REL:
2092 DynRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2093 break;
2094 case ELF::DT_RELSZ:
2095 DynRelRegion.Size = Dyn.getVal();
2096 DynRelRegion.SizePrintName = "DT_RELSZ value";
2097 break;
2098 case ELF::DT_RELENT:
2099 DynRelRegion.EntSize = Dyn.getVal();
2100 DynRelRegion.EntSizePrintName = "DT_RELENT value";
2101 break;
2102 case ELF::DT_RELR:
2103 case ELF::DT_ANDROID_RELR:
2104 case ELF::DT_AARCH64_AUTH_RELR:
2105 DynRelrRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2106 break;
2107 case ELF::DT_RELRSZ:
2108 case ELF::DT_ANDROID_RELRSZ:
2109 case ELF::DT_AARCH64_AUTH_RELRSZ:
2110 DynRelrRegion.Size = Dyn.getVal();
2111 DynRelrRegion.SizePrintName = Dyn.d_tag == ELF::DT_RELRSZ
2112 ? "DT_RELRSZ value"
2113 : "DT_ANDROID_RELRSZ value";
2114 break;
2115 case ELF::DT_RELRENT:
2116 case ELF::DT_ANDROID_RELRENT:
2117 case ELF::DT_AARCH64_AUTH_RELRENT:
2118 DynRelrRegion.EntSize = Dyn.getVal();
2119 DynRelrRegion.EntSizePrintName = Dyn.d_tag == ELF::DT_RELRENT
2120 ? "DT_RELRENT value"
2121 : "DT_ANDROID_RELRENT value";
2122 break;
2123 case ELF::DT_PLTREL:
2124 if (Dyn.getVal() == DT_REL)
2125 DynPLTRelRegion.EntSize = sizeof(Elf_Rel);
2126 else if (Dyn.getVal() == DT_RELA)
2127 DynPLTRelRegion.EntSize = sizeof(Elf_Rela);
2128 else if (Dyn.getVal() == DT_CREL)
2129 DynPLTRelRegion.EntSize = 1;
2130 else
2131 reportUniqueWarning(Twine("unknown DT_PLTREL value of ") +
2132 Twine((uint64_t)Dyn.getVal()));
2133 DynPLTRelRegion.EntSizePrintName = "PLTREL entry size";
2134 break;
2135 case ELF::DT_JMPREL:
2136 DynPLTRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2137 break;
2138 case ELF::DT_PLTRELSZ:
2139 DynPLTRelRegion.Size = Dyn.getVal();
2140 DynPLTRelRegion.SizePrintName = "DT_PLTRELSZ value";
2141 break;
2142 case ELF::DT_SYMTAB_SHNDX:
2143 DynSymTabShndxRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2144 DynSymTabShndxRegion.EntSize = sizeof(Elf_Word);
2145 break;
2149 if (StringTableBegin) {
2150 const uint64_t FileSize = Obj.getBufSize();
2151 const uint64_t Offset = (const uint8_t *)StringTableBegin - Obj.base();
2152 if (StringTableSize > FileSize - Offset)
2153 reportUniqueWarning(
2154 "the dynamic string table at 0x" + Twine::utohexstr(Offset) +
2155 " goes past the end of the file (0x" + Twine::utohexstr(FileSize) +
2156 ") with DT_STRSZ = 0x" + Twine::utohexstr(StringTableSize));
2157 else
2158 DynamicStringTable = StringRef(StringTableBegin, StringTableSize);
2161 const bool IsHashTableSupported = getHashTableEntSize() == 4;
2162 if (DynSymRegion) {
2163 // Often we find the information about the dynamic symbol table
2164 // location in the SHT_DYNSYM section header. However, the value in
2165 // DT_SYMTAB has priority, because it is used by dynamic loaders to
2166 // locate .dynsym at runtime. The location we find in the section header
2167 // and the location we find here should match.
2168 if (DynSymFromTable && DynSymFromTable->Addr != DynSymRegion->Addr)
2169 reportUniqueWarning(
2170 createError("SHT_DYNSYM section header and DT_SYMTAB disagree about "
2171 "the location of the dynamic symbol table"));
2173 // According to the ELF gABI: "The number of symbol table entries should
2174 // equal nchain". Check to see if the DT_HASH hash table nchain value
2175 // conflicts with the number of symbols in the dynamic symbol table
2176 // according to the section header.
2177 if (HashTable && IsHashTableSupported) {
2178 if (DynSymRegion->EntSize == 0)
2179 reportUniqueWarning("SHT_DYNSYM section has sh_entsize == 0");
2180 else if (HashTable->nchain != DynSymRegion->Size / DynSymRegion->EntSize)
2181 reportUniqueWarning(
2182 "hash table nchain (" + Twine(HashTable->nchain) +
2183 ") differs from symbol count derived from SHT_DYNSYM section "
2184 "header (" +
2185 Twine(DynSymRegion->Size / DynSymRegion->EntSize) + ")");
2189 // Delay the creation of the actual dynamic symbol table until now, so that
2190 // checks can always be made against the section header-based properties,
2191 // without worrying about tag order.
2192 if (DynSymFromTable) {
2193 if (!DynSymRegion) {
2194 DynSymRegion = DynSymFromTable;
2195 } else {
2196 DynSymRegion->Addr = DynSymFromTable->Addr;
2197 DynSymRegion->EntSize = DynSymFromTable->EntSize;
2198 DynSymRegion->EntSizePrintName = DynSymFromTable->EntSizePrintName;
2202 // Derive the dynamic symbol table size from the DT_HASH hash table, if
2203 // present.
2204 if (HashTable && IsHashTableSupported && DynSymRegion) {
2205 const uint64_t FileSize = Obj.getBufSize();
2206 const uint64_t DerivedSize =
2207 (uint64_t)HashTable->nchain * DynSymRegion->EntSize;
2208 const uint64_t Offset = (const uint8_t *)DynSymRegion->Addr - Obj.base();
2209 if (DerivedSize > FileSize - Offset)
2210 reportUniqueWarning(
2211 "the size (0x" + Twine::utohexstr(DerivedSize) +
2212 ") of the dynamic symbol table at 0x" + Twine::utohexstr(Offset) +
2213 ", derived from the hash table, goes past the end of the file (0x" +
2214 Twine::utohexstr(FileSize) + ") and will be ignored");
2215 else
2216 DynSymRegion->Size = HashTable->nchain * DynSymRegion->EntSize;
2220 template <typename ELFT> void ELFDumper<ELFT>::printVersionInfo() {
2221 // Dump version symbol section.
2222 printVersionSymbolSection(SymbolVersionSection);
2224 // Dump version definition section.
2225 printVersionDefinitionSection(SymbolVersionDefSection);
2227 // Dump version dependency section.
2228 printVersionDependencySection(SymbolVersionNeedSection);
2231 #define LLVM_READOBJ_DT_FLAG_ENT(prefix, enum) \
2232 { #enum, prefix##_##enum }
2234 const EnumEntry<unsigned> ElfDynamicDTFlags[] = {
2235 LLVM_READOBJ_DT_FLAG_ENT(DF, ORIGIN),
2236 LLVM_READOBJ_DT_FLAG_ENT(DF, SYMBOLIC),
2237 LLVM_READOBJ_DT_FLAG_ENT(DF, TEXTREL),
2238 LLVM_READOBJ_DT_FLAG_ENT(DF, BIND_NOW),
2239 LLVM_READOBJ_DT_FLAG_ENT(DF, STATIC_TLS)
2242 const EnumEntry<unsigned> ElfDynamicDTFlags1[] = {
2243 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOW),
2244 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAL),
2245 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GROUP),
2246 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODELETE),
2247 LLVM_READOBJ_DT_FLAG_ENT(DF_1, LOADFLTR),
2248 LLVM_READOBJ_DT_FLAG_ENT(DF_1, INITFIRST),
2249 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOOPEN),
2250 LLVM_READOBJ_DT_FLAG_ENT(DF_1, ORIGIN),
2251 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DIRECT),
2252 LLVM_READOBJ_DT_FLAG_ENT(DF_1, TRANS),
2253 LLVM_READOBJ_DT_FLAG_ENT(DF_1, INTERPOSE),
2254 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODEFLIB),
2255 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODUMP),
2256 LLVM_READOBJ_DT_FLAG_ENT(DF_1, CONFALT),
2257 LLVM_READOBJ_DT_FLAG_ENT(DF_1, ENDFILTEE),
2258 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELDNE),
2259 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELPND),
2260 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODIRECT),
2261 LLVM_READOBJ_DT_FLAG_ENT(DF_1, IGNMULDEF),
2262 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOKSYMS),
2263 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOHDR),
2264 LLVM_READOBJ_DT_FLAG_ENT(DF_1, EDITED),
2265 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NORELOC),
2266 LLVM_READOBJ_DT_FLAG_ENT(DF_1, SYMINTPOSE),
2267 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAUDIT),
2268 LLVM_READOBJ_DT_FLAG_ENT(DF_1, SINGLETON),
2269 LLVM_READOBJ_DT_FLAG_ENT(DF_1, PIE),
2272 const EnumEntry<unsigned> ElfDynamicDTMipsFlags[] = {
2273 LLVM_READOBJ_DT_FLAG_ENT(RHF, NONE),
2274 LLVM_READOBJ_DT_FLAG_ENT(RHF, QUICKSTART),
2275 LLVM_READOBJ_DT_FLAG_ENT(RHF, NOTPOT),
2276 LLVM_READOBJ_DT_FLAG_ENT(RHS, NO_LIBRARY_REPLACEMENT),
2277 LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_MOVE),
2278 LLVM_READOBJ_DT_FLAG_ENT(RHF, SGI_ONLY),
2279 LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_INIT),
2280 LLVM_READOBJ_DT_FLAG_ENT(RHF, DELTA_C_PLUS_PLUS),
2281 LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_START_INIT),
2282 LLVM_READOBJ_DT_FLAG_ENT(RHF, PIXIE),
2283 LLVM_READOBJ_DT_FLAG_ENT(RHF, DEFAULT_DELAY_LOAD),
2284 LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTART),
2285 LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTARTED),
2286 LLVM_READOBJ_DT_FLAG_ENT(RHF, CORD),
2287 LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_UNRES_UNDEF),
2288 LLVM_READOBJ_DT_FLAG_ENT(RHF, RLD_ORDER_SAFE)
2291 #undef LLVM_READOBJ_DT_FLAG_ENT
2293 template <typename T, typename TFlag>
2294 void printFlags(T Value, ArrayRef<EnumEntry<TFlag>> Flags, raw_ostream &OS) {
2295 SmallVector<EnumEntry<TFlag>, 10> SetFlags;
2296 for (const EnumEntry<TFlag> &Flag : Flags)
2297 if (Flag.Value != 0 && (Value & Flag.Value) == Flag.Value)
2298 SetFlags.push_back(Flag);
2300 for (const EnumEntry<TFlag> &Flag : SetFlags)
2301 OS << Flag.Name << " ";
2304 template <class ELFT>
2305 const typename ELFT::Shdr *
2306 ELFDumper<ELFT>::findSectionByName(StringRef Name) const {
2307 for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
2308 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Shdr)) {
2309 if (*NameOrErr == Name)
2310 return &Shdr;
2311 } else {
2312 reportUniqueWarning("unable to read the name of " + describe(Shdr) +
2313 ": " + toString(NameOrErr.takeError()));
2316 return nullptr;
2319 template <class ELFT>
2320 std::string ELFDumper<ELFT>::getDynamicEntry(uint64_t Type,
2321 uint64_t Value) const {
2322 auto FormatHexValue = [](uint64_t V) {
2323 std::string Str;
2324 raw_string_ostream OS(Str);
2325 const char *ConvChar =
2326 (opts::Output == opts::GNU) ? "0x%" PRIx64 : "0x%" PRIX64;
2327 OS << format(ConvChar, V);
2328 return Str;
2331 auto FormatFlags = [](uint64_t V,
2332 llvm::ArrayRef<llvm::EnumEntry<unsigned int>> Array) {
2333 std::string Str;
2334 raw_string_ostream OS(Str);
2335 printFlags(V, Array, OS);
2336 return Str;
2339 // Handle custom printing of architecture specific tags
2340 switch (Obj.getHeader().e_machine) {
2341 case EM_AARCH64:
2342 switch (Type) {
2343 case DT_AARCH64_BTI_PLT:
2344 case DT_AARCH64_PAC_PLT:
2345 case DT_AARCH64_VARIANT_PCS:
2346 case DT_AARCH64_MEMTAG_GLOBALSSZ:
2347 return std::to_string(Value);
2348 case DT_AARCH64_MEMTAG_MODE:
2349 switch (Value) {
2350 case 0:
2351 return "Synchronous (0)";
2352 case 1:
2353 return "Asynchronous (1)";
2354 default:
2355 return (Twine("Unknown (") + Twine(Value) + ")").str();
2357 case DT_AARCH64_MEMTAG_HEAP:
2358 case DT_AARCH64_MEMTAG_STACK:
2359 switch (Value) {
2360 case 0:
2361 return "Disabled (0)";
2362 case 1:
2363 return "Enabled (1)";
2364 default:
2365 return (Twine("Unknown (") + Twine(Value) + ")").str();
2367 case DT_AARCH64_MEMTAG_GLOBALS:
2368 return (Twine("0x") + utohexstr(Value, /*LowerCase=*/true)).str();
2369 default:
2370 break;
2372 break;
2373 case EM_HEXAGON:
2374 switch (Type) {
2375 case DT_HEXAGON_VER:
2376 return std::to_string(Value);
2377 case DT_HEXAGON_SYMSZ:
2378 case DT_HEXAGON_PLT:
2379 return FormatHexValue(Value);
2380 default:
2381 break;
2383 break;
2384 case EM_MIPS:
2385 switch (Type) {
2386 case DT_MIPS_RLD_VERSION:
2387 case DT_MIPS_LOCAL_GOTNO:
2388 case DT_MIPS_SYMTABNO:
2389 case DT_MIPS_UNREFEXTNO:
2390 return std::to_string(Value);
2391 case DT_MIPS_TIME_STAMP:
2392 case DT_MIPS_ICHECKSUM:
2393 case DT_MIPS_IVERSION:
2394 case DT_MIPS_BASE_ADDRESS:
2395 case DT_MIPS_MSYM:
2396 case DT_MIPS_CONFLICT:
2397 case DT_MIPS_LIBLIST:
2398 case DT_MIPS_CONFLICTNO:
2399 case DT_MIPS_LIBLISTNO:
2400 case DT_MIPS_GOTSYM:
2401 case DT_MIPS_HIPAGENO:
2402 case DT_MIPS_RLD_MAP:
2403 case DT_MIPS_DELTA_CLASS:
2404 case DT_MIPS_DELTA_CLASS_NO:
2405 case DT_MIPS_DELTA_INSTANCE:
2406 case DT_MIPS_DELTA_RELOC:
2407 case DT_MIPS_DELTA_RELOC_NO:
2408 case DT_MIPS_DELTA_SYM:
2409 case DT_MIPS_DELTA_SYM_NO:
2410 case DT_MIPS_DELTA_CLASSSYM:
2411 case DT_MIPS_DELTA_CLASSSYM_NO:
2412 case DT_MIPS_CXX_FLAGS:
2413 case DT_MIPS_PIXIE_INIT:
2414 case DT_MIPS_SYMBOL_LIB:
2415 case DT_MIPS_LOCALPAGE_GOTIDX:
2416 case DT_MIPS_LOCAL_GOTIDX:
2417 case DT_MIPS_HIDDEN_GOTIDX:
2418 case DT_MIPS_PROTECTED_GOTIDX:
2419 case DT_MIPS_OPTIONS:
2420 case DT_MIPS_INTERFACE:
2421 case DT_MIPS_DYNSTR_ALIGN:
2422 case DT_MIPS_INTERFACE_SIZE:
2423 case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
2424 case DT_MIPS_PERF_SUFFIX:
2425 case DT_MIPS_COMPACT_SIZE:
2426 case DT_MIPS_GP_VALUE:
2427 case DT_MIPS_AUX_DYNAMIC:
2428 case DT_MIPS_PLTGOT:
2429 case DT_MIPS_RWPLT:
2430 case DT_MIPS_RLD_MAP_REL:
2431 case DT_MIPS_XHASH:
2432 return FormatHexValue(Value);
2433 case DT_MIPS_FLAGS:
2434 return FormatFlags(Value, ArrayRef(ElfDynamicDTMipsFlags));
2435 default:
2436 break;
2438 break;
2439 default:
2440 break;
2443 switch (Type) {
2444 case DT_PLTREL:
2445 if (Value == DT_REL)
2446 return "REL";
2447 if (Value == DT_RELA)
2448 return "RELA";
2449 if (Value == DT_CREL)
2450 return "CREL";
2451 [[fallthrough]];
2452 case DT_PLTGOT:
2453 case DT_HASH:
2454 case DT_STRTAB:
2455 case DT_SYMTAB:
2456 case DT_RELA:
2457 case DT_INIT:
2458 case DT_FINI:
2459 case DT_REL:
2460 case DT_JMPREL:
2461 case DT_INIT_ARRAY:
2462 case DT_FINI_ARRAY:
2463 case DT_PREINIT_ARRAY:
2464 case DT_DEBUG:
2465 case DT_CREL:
2466 case DT_VERDEF:
2467 case DT_VERNEED:
2468 case DT_VERSYM:
2469 case DT_GNU_HASH:
2470 case DT_NULL:
2471 return FormatHexValue(Value);
2472 case DT_RELACOUNT:
2473 case DT_RELCOUNT:
2474 case DT_VERDEFNUM:
2475 case DT_VERNEEDNUM:
2476 return std::to_string(Value);
2477 case DT_PLTRELSZ:
2478 case DT_RELASZ:
2479 case DT_RELAENT:
2480 case DT_STRSZ:
2481 case DT_SYMENT:
2482 case DT_RELSZ:
2483 case DT_RELENT:
2484 case DT_INIT_ARRAYSZ:
2485 case DT_FINI_ARRAYSZ:
2486 case DT_PREINIT_ARRAYSZ:
2487 case DT_RELRSZ:
2488 case DT_RELRENT:
2489 case DT_AARCH64_AUTH_RELRSZ:
2490 case DT_AARCH64_AUTH_RELRENT:
2491 case DT_ANDROID_RELSZ:
2492 case DT_ANDROID_RELASZ:
2493 return std::to_string(Value) + " (bytes)";
2494 case DT_NEEDED:
2495 case DT_SONAME:
2496 case DT_AUXILIARY:
2497 case DT_USED:
2498 case DT_FILTER:
2499 case DT_RPATH:
2500 case DT_RUNPATH: {
2501 const std::map<uint64_t, const char *> TagNames = {
2502 {DT_NEEDED, "Shared library"}, {DT_SONAME, "Library soname"},
2503 {DT_AUXILIARY, "Auxiliary library"}, {DT_USED, "Not needed object"},
2504 {DT_FILTER, "Filter library"}, {DT_RPATH, "Library rpath"},
2505 {DT_RUNPATH, "Library runpath"},
2508 return (Twine(TagNames.at(Type)) + ": [" + getDynamicString(Value) + "]")
2509 .str();
2511 case DT_FLAGS:
2512 return FormatFlags(Value, ArrayRef(ElfDynamicDTFlags));
2513 case DT_FLAGS_1:
2514 return FormatFlags(Value, ArrayRef(ElfDynamicDTFlags1));
2515 default:
2516 return FormatHexValue(Value);
2520 template <class ELFT>
2521 StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const {
2522 if (DynamicStringTable.empty() && !DynamicStringTable.data()) {
2523 reportUniqueWarning("string table was not found");
2524 return "<?>";
2527 auto WarnAndReturn = [this](const Twine &Msg, uint64_t Offset) {
2528 reportUniqueWarning("string table at offset 0x" + Twine::utohexstr(Offset) +
2529 Msg);
2530 return "<?>";
2533 const uint64_t FileSize = Obj.getBufSize();
2534 const uint64_t Offset =
2535 (const uint8_t *)DynamicStringTable.data() - Obj.base();
2536 if (DynamicStringTable.size() > FileSize - Offset)
2537 return WarnAndReturn(" with size 0x" +
2538 Twine::utohexstr(DynamicStringTable.size()) +
2539 " goes past the end of the file (0x" +
2540 Twine::utohexstr(FileSize) + ")",
2541 Offset);
2543 if (Value >= DynamicStringTable.size())
2544 return WarnAndReturn(
2545 ": unable to read the string at 0x" + Twine::utohexstr(Offset + Value) +
2546 ": it goes past the end of the table (0x" +
2547 Twine::utohexstr(Offset + DynamicStringTable.size()) + ")",
2548 Offset);
2550 if (DynamicStringTable.back() != '\0')
2551 return WarnAndReturn(": unable to read the string at 0x" +
2552 Twine::utohexstr(Offset + Value) +
2553 ": the string table is not null-terminated",
2554 Offset);
2556 return DynamicStringTable.data() + Value;
2559 template <class ELFT> void ELFDumper<ELFT>::printUnwindInfo() {
2560 DwarfCFIEH::PrinterContext<ELFT> Ctx(W, ObjF);
2561 Ctx.printUnwindInformation();
2564 // The namespace is needed to fix the compilation with GCC older than 7.0+.
2565 namespace {
2566 template <> void ELFDumper<ELF32LE>::printUnwindInfo() {
2567 if (Obj.getHeader().e_machine == EM_ARM) {
2568 ARM::EHABI::PrinterContext<ELF32LE> Ctx(W, Obj, ObjF.getFileName(),
2569 DotSymtabSec);
2570 Ctx.PrintUnwindInformation();
2572 DwarfCFIEH::PrinterContext<ELF32LE> Ctx(W, ObjF);
2573 Ctx.printUnwindInformation();
2575 } // namespace
2577 template <class ELFT> void ELFDumper<ELFT>::printNeededLibraries() {
2578 ListScope D(W, "NeededLibraries");
2580 std::vector<StringRef> Libs;
2581 for (const auto &Entry : dynamic_table())
2582 if (Entry.d_tag == ELF::DT_NEEDED)
2583 Libs.push_back(getDynamicString(Entry.d_un.d_val));
2585 llvm::sort(Libs);
2587 for (StringRef L : Libs)
2588 W.printString(L);
2591 template <class ELFT>
2592 static Error checkHashTable(const ELFDumper<ELFT> &Dumper,
2593 const typename ELFT::Hash *H,
2594 bool *IsHeaderValid = nullptr) {
2595 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
2596 const uint64_t SecOffset = (const uint8_t *)H - Obj.base();
2597 if (Dumper.getHashTableEntSize() == 8) {
2598 auto It = llvm::find_if(ElfMachineType, [&](const EnumEntry<unsigned> &E) {
2599 return E.Value == Obj.getHeader().e_machine;
2601 if (IsHeaderValid)
2602 *IsHeaderValid = false;
2603 return createError("the hash table at 0x" + Twine::utohexstr(SecOffset) +
2604 " is not supported: it contains non-standard 8 "
2605 "byte entries on " +
2606 It->AltName + " platform");
2609 auto MakeError = [&](const Twine &Msg = "") {
2610 return createError("the hash table at offset 0x" +
2611 Twine::utohexstr(SecOffset) +
2612 " goes past the end of the file (0x" +
2613 Twine::utohexstr(Obj.getBufSize()) + ")" + Msg);
2616 // Each SHT_HASH section starts from two 32-bit fields: nbucket and nchain.
2617 const unsigned HeaderSize = 2 * sizeof(typename ELFT::Word);
2619 if (IsHeaderValid)
2620 *IsHeaderValid = Obj.getBufSize() - SecOffset >= HeaderSize;
2622 if (Obj.getBufSize() - SecOffset < HeaderSize)
2623 return MakeError();
2625 if (Obj.getBufSize() - SecOffset - HeaderSize <
2626 ((uint64_t)H->nbucket + H->nchain) * sizeof(typename ELFT::Word))
2627 return MakeError(", nbucket = " + Twine(H->nbucket) +
2628 ", nchain = " + Twine(H->nchain));
2629 return Error::success();
2632 template <class ELFT>
2633 static Error checkGNUHashTable(const ELFFile<ELFT> &Obj,
2634 const typename ELFT::GnuHash *GnuHashTable,
2635 bool *IsHeaderValid = nullptr) {
2636 const uint8_t *TableData = reinterpret_cast<const uint8_t *>(GnuHashTable);
2637 assert(TableData >= Obj.base() && TableData < Obj.base() + Obj.getBufSize() &&
2638 "GnuHashTable must always point to a location inside the file");
2640 uint64_t TableOffset = TableData - Obj.base();
2641 if (IsHeaderValid)
2642 *IsHeaderValid = TableOffset + /*Header size:*/ 16 < Obj.getBufSize();
2643 if (TableOffset + 16 + (uint64_t)GnuHashTable->nbuckets * 4 +
2644 (uint64_t)GnuHashTable->maskwords * sizeof(typename ELFT::Off) >=
2645 Obj.getBufSize())
2646 return createError("unable to dump the SHT_GNU_HASH "
2647 "section at 0x" +
2648 Twine::utohexstr(TableOffset) +
2649 ": it goes past the end of the file");
2650 return Error::success();
2653 template <typename ELFT> void ELFDumper<ELFT>::printHashTable() {
2654 DictScope D(W, "HashTable");
2655 if (!HashTable)
2656 return;
2658 bool IsHeaderValid;
2659 Error Err = checkHashTable(*this, HashTable, &IsHeaderValid);
2660 if (IsHeaderValid) {
2661 W.printNumber("Num Buckets", HashTable->nbucket);
2662 W.printNumber("Num Chains", HashTable->nchain);
2665 if (Err) {
2666 reportUniqueWarning(std::move(Err));
2667 return;
2670 W.printList("Buckets", HashTable->buckets());
2671 W.printList("Chains", HashTable->chains());
2674 template <class ELFT>
2675 static Expected<ArrayRef<typename ELFT::Word>>
2676 getGnuHashTableChains(std::optional<DynRegionInfo> DynSymRegion,
2677 const typename ELFT::GnuHash *GnuHashTable) {
2678 if (!DynSymRegion)
2679 return createError("no dynamic symbol table found");
2681 ArrayRef<typename ELFT::Sym> DynSymTable =
2682 DynSymRegion->template getAsArrayRef<typename ELFT::Sym>();
2683 size_t NumSyms = DynSymTable.size();
2684 if (!NumSyms)
2685 return createError("the dynamic symbol table is empty");
2687 if (GnuHashTable->symndx < NumSyms)
2688 return GnuHashTable->values(NumSyms);
2690 // A normal empty GNU hash table section produced by linker might have
2691 // symndx set to the number of dynamic symbols + 1 (for the zero symbol)
2692 // and have dummy null values in the Bloom filter and in the buckets
2693 // vector (or no values at all). It happens because the value of symndx is not
2694 // important for dynamic loaders when the GNU hash table is empty. They just
2695 // skip the whole object during symbol lookup. In such cases, the symndx value
2696 // is irrelevant and we should not report a warning.
2697 ArrayRef<typename ELFT::Word> Buckets = GnuHashTable->buckets();
2698 if (!llvm::all_of(Buckets, [](typename ELFT::Word V) { return V == 0; }))
2699 return createError(
2700 "the first hashed symbol index (" + Twine(GnuHashTable->symndx) +
2701 ") is greater than or equal to the number of dynamic symbols (" +
2702 Twine(NumSyms) + ")");
2703 // There is no way to represent an array of (dynamic symbols count - symndx)
2704 // length.
2705 return ArrayRef<typename ELFT::Word>();
2708 template <typename ELFT>
2709 void ELFDumper<ELFT>::printGnuHashTable() {
2710 DictScope D(W, "GnuHashTable");
2711 if (!GnuHashTable)
2712 return;
2714 bool IsHeaderValid;
2715 Error Err = checkGNUHashTable<ELFT>(Obj, GnuHashTable, &IsHeaderValid);
2716 if (IsHeaderValid) {
2717 W.printNumber("Num Buckets", GnuHashTable->nbuckets);
2718 W.printNumber("First Hashed Symbol Index", GnuHashTable->symndx);
2719 W.printNumber("Num Mask Words", GnuHashTable->maskwords);
2720 W.printNumber("Shift Count", GnuHashTable->shift2);
2723 if (Err) {
2724 reportUniqueWarning(std::move(Err));
2725 return;
2728 ArrayRef<typename ELFT::Off> BloomFilter = GnuHashTable->filter();
2729 W.printHexList("Bloom Filter", BloomFilter);
2731 ArrayRef<Elf_Word> Buckets = GnuHashTable->buckets();
2732 W.printList("Buckets", Buckets);
2734 Expected<ArrayRef<Elf_Word>> Chains =
2735 getGnuHashTableChains<ELFT>(DynSymRegion, GnuHashTable);
2736 if (!Chains) {
2737 reportUniqueWarning("unable to dump 'Values' for the SHT_GNU_HASH "
2738 "section: " +
2739 toString(Chains.takeError()));
2740 return;
2743 W.printHexList("Values", *Chains);
2746 template <typename ELFT> void ELFDumper<ELFT>::printHashHistograms() {
2747 // Print histogram for the .hash section.
2748 if (this->HashTable) {
2749 if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
2750 this->reportUniqueWarning(std::move(E));
2751 else
2752 printHashHistogram(*this->HashTable);
2755 // Print histogram for the .gnu.hash section.
2756 if (this->GnuHashTable) {
2757 if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
2758 this->reportUniqueWarning(std::move(E));
2759 else
2760 printGnuHashHistogram(*this->GnuHashTable);
2764 template <typename ELFT>
2765 void ELFDumper<ELFT>::printHashHistogram(const Elf_Hash &HashTable) const {
2766 size_t NBucket = HashTable.nbucket;
2767 size_t NChain = HashTable.nchain;
2768 ArrayRef<Elf_Word> Buckets = HashTable.buckets();
2769 ArrayRef<Elf_Word> Chains = HashTable.chains();
2770 size_t TotalSyms = 0;
2771 // If hash table is correct, we have at least chains with 0 length.
2772 size_t MaxChain = 1;
2774 if (NChain == 0 || NBucket == 0)
2775 return;
2777 std::vector<size_t> ChainLen(NBucket, 0);
2778 // Go over all buckets and note chain lengths of each bucket (total
2779 // unique chain lengths).
2780 for (size_t B = 0; B < NBucket; ++B) {
2781 BitVector Visited(NChain);
2782 for (size_t C = Buckets[B]; C < NChain; C = Chains[C]) {
2783 if (C == ELF::STN_UNDEF)
2784 break;
2785 if (Visited[C]) {
2786 this->reportUniqueWarning(
2787 ".hash section is invalid: bucket " + Twine(C) +
2788 ": a cycle was detected in the linked chain");
2789 break;
2791 Visited[C] = true;
2792 if (MaxChain <= ++ChainLen[B])
2793 ++MaxChain;
2795 TotalSyms += ChainLen[B];
2798 if (!TotalSyms)
2799 return;
2801 std::vector<size_t> Count(MaxChain, 0);
2802 // Count how long is the chain for each bucket.
2803 for (size_t B = 0; B < NBucket; B++)
2804 ++Count[ChainLen[B]];
2805 // Print Number of buckets with each chain lengths and their cumulative
2806 // coverage of the symbols.
2807 printHashHistogramStats(NBucket, MaxChain, TotalSyms, Count, /*IsGnu=*/false);
2810 template <class ELFT>
2811 void ELFDumper<ELFT>::printGnuHashHistogram(
2812 const Elf_GnuHash &GnuHashTable) const {
2813 Expected<ArrayRef<Elf_Word>> ChainsOrErr =
2814 getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHashTable);
2815 if (!ChainsOrErr) {
2816 this->reportUniqueWarning("unable to print the GNU hash table histogram: " +
2817 toString(ChainsOrErr.takeError()));
2818 return;
2821 ArrayRef<Elf_Word> Chains = *ChainsOrErr;
2822 size_t Symndx = GnuHashTable.symndx;
2823 size_t TotalSyms = 0;
2824 size_t MaxChain = 1;
2826 size_t NBucket = GnuHashTable.nbuckets;
2827 if (Chains.empty() || NBucket == 0)
2828 return;
2830 ArrayRef<Elf_Word> Buckets = GnuHashTable.buckets();
2831 std::vector<size_t> ChainLen(NBucket, 0);
2832 for (size_t B = 0; B < NBucket; ++B) {
2833 if (!Buckets[B])
2834 continue;
2835 size_t Len = 1;
2836 for (size_t C = Buckets[B] - Symndx;
2837 C < Chains.size() && (Chains[C] & 1) == 0; ++C)
2838 if (MaxChain < ++Len)
2839 ++MaxChain;
2840 ChainLen[B] = Len;
2841 TotalSyms += Len;
2843 ++MaxChain;
2845 if (!TotalSyms)
2846 return;
2848 std::vector<size_t> Count(MaxChain, 0);
2849 for (size_t B = 0; B < NBucket; ++B)
2850 ++Count[ChainLen[B]];
2851 // Print Number of buckets with each chain lengths and their cumulative
2852 // coverage of the symbols.
2853 printHashHistogramStats(NBucket, MaxChain, TotalSyms, Count, /*IsGnu=*/true);
2856 template <typename ELFT> void ELFDumper<ELFT>::printLoadName() {
2857 StringRef SOName = "<Not found>";
2858 if (SONameOffset)
2859 SOName = getDynamicString(*SONameOffset);
2860 W.printString("LoadName", SOName);
2863 template <class ELFT> void ELFDumper<ELFT>::printArchSpecificInfo() {
2864 switch (Obj.getHeader().e_machine) {
2865 case EM_HEXAGON:
2866 printAttributes(ELF::SHT_HEXAGON_ATTRIBUTES,
2867 std::make_unique<HexagonAttributeParser>(&W),
2868 llvm::endianness::little);
2869 break;
2870 case EM_ARM:
2871 printAttributes(
2872 ELF::SHT_ARM_ATTRIBUTES, std::make_unique<ARMAttributeParser>(&W),
2873 Obj.isLE() ? llvm::endianness::little : llvm::endianness::big);
2874 break;
2875 case EM_RISCV:
2876 if (Obj.isLE())
2877 printAttributes(ELF::SHT_RISCV_ATTRIBUTES,
2878 std::make_unique<RISCVAttributeParser>(&W),
2879 llvm::endianness::little);
2880 else
2881 reportUniqueWarning("attribute printing not implemented for big-endian "
2882 "RISC-V objects");
2883 break;
2884 case EM_MSP430:
2885 printAttributes(ELF::SHT_MSP430_ATTRIBUTES,
2886 std::make_unique<MSP430AttributeParser>(&W),
2887 llvm::endianness::little);
2888 break;
2889 case EM_MIPS: {
2890 printMipsABIFlags();
2891 printMipsOptions();
2892 printMipsReginfo();
2893 MipsGOTParser<ELFT> Parser(*this);
2894 if (Error E = Parser.findGOT(dynamic_table(), dynamic_symbols()))
2895 reportUniqueWarning(std::move(E));
2896 else if (!Parser.isGotEmpty())
2897 printMipsGOT(Parser);
2899 if (Error E = Parser.findPLT(dynamic_table()))
2900 reportUniqueWarning(std::move(E));
2901 else if (!Parser.isPltEmpty())
2902 printMipsPLT(Parser);
2903 break;
2905 default:
2906 break;
2910 template <class ELFT>
2911 void ELFDumper<ELFT>::printAttributes(
2912 unsigned AttrShType, std::unique_ptr<ELFAttributeParser> AttrParser,
2913 llvm::endianness Endianness) {
2914 assert((AttrShType != ELF::SHT_NULL) && AttrParser &&
2915 "Incomplete ELF attribute implementation");
2916 DictScope BA(W, "BuildAttributes");
2917 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
2918 if (Sec.sh_type != AttrShType)
2919 continue;
2921 ArrayRef<uint8_t> Contents;
2922 if (Expected<ArrayRef<uint8_t>> ContentOrErr =
2923 Obj.getSectionContents(Sec)) {
2924 Contents = *ContentOrErr;
2925 if (Contents.empty()) {
2926 reportUniqueWarning("the " + describe(Sec) + " is empty");
2927 continue;
2929 } else {
2930 reportUniqueWarning("unable to read the content of the " + describe(Sec) +
2931 ": " + toString(ContentOrErr.takeError()));
2932 continue;
2935 W.printHex("FormatVersion", Contents[0]);
2937 if (Error E = AttrParser->parse(Contents, Endianness))
2938 reportUniqueWarning("unable to dump attributes from the " +
2939 describe(Sec) + ": " + toString(std::move(E)));
2943 namespace {
2945 template <class ELFT> class MipsGOTParser {
2946 public:
2947 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
2948 using Entry = typename ELFT::Addr;
2949 using Entries = ArrayRef<Entry>;
2951 const bool IsStatic;
2952 const ELFFile<ELFT> &Obj;
2953 const ELFDumper<ELFT> &Dumper;
2955 MipsGOTParser(const ELFDumper<ELFT> &D);
2956 Error findGOT(Elf_Dyn_Range DynTable, Elf_Sym_Range DynSyms);
2957 Error findPLT(Elf_Dyn_Range DynTable);
2959 bool isGotEmpty() const { return GotEntries.empty(); }
2960 bool isPltEmpty() const { return PltEntries.empty(); }
2962 uint64_t getGp() const;
2964 const Entry *getGotLazyResolver() const;
2965 const Entry *getGotModulePointer() const;
2966 const Entry *getPltLazyResolver() const;
2967 const Entry *getPltModulePointer() const;
2969 Entries getLocalEntries() const;
2970 Entries getGlobalEntries() const;
2971 Entries getOtherEntries() const;
2972 Entries getPltEntries() const;
2974 uint64_t getGotAddress(const Entry * E) const;
2975 int64_t getGotOffset(const Entry * E) const;
2976 const Elf_Sym *getGotSym(const Entry *E) const;
2978 uint64_t getPltAddress(const Entry * E) const;
2979 const Elf_Sym *getPltSym(const Entry *E) const;
2981 StringRef getPltStrTable() const { return PltStrTable; }
2982 const Elf_Shdr *getPltSymTable() const { return PltSymTable; }
2984 private:
2985 const Elf_Shdr *GotSec;
2986 size_t LocalNum;
2987 size_t GlobalNum;
2989 const Elf_Shdr *PltSec;
2990 const Elf_Shdr *PltRelSec;
2991 const Elf_Shdr *PltSymTable;
2992 StringRef FileName;
2994 Elf_Sym_Range GotDynSyms;
2995 StringRef PltStrTable;
2997 Entries GotEntries;
2998 Entries PltEntries;
3001 } // end anonymous namespace
3003 template <class ELFT>
3004 MipsGOTParser<ELFT>::MipsGOTParser(const ELFDumper<ELFT> &D)
3005 : IsStatic(D.dynamic_table().empty()), Obj(D.getElfObject().getELFFile()),
3006 Dumper(D), GotSec(nullptr), LocalNum(0), GlobalNum(0), PltSec(nullptr),
3007 PltRelSec(nullptr), PltSymTable(nullptr),
3008 FileName(D.getElfObject().getFileName()) {}
3010 template <class ELFT>
3011 Error MipsGOTParser<ELFT>::findGOT(Elf_Dyn_Range DynTable,
3012 Elf_Sym_Range DynSyms) {
3013 // See "Global Offset Table" in Chapter 5 in the following document
3014 // for detailed GOT description.
3015 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
3017 // Find static GOT secton.
3018 if (IsStatic) {
3019 GotSec = Dumper.findSectionByName(".got");
3020 if (!GotSec)
3021 return Error::success();
3023 ArrayRef<uint8_t> Content =
3024 unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
3025 GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
3026 Content.size() / sizeof(Entry));
3027 LocalNum = GotEntries.size();
3028 return Error::success();
3031 // Lookup dynamic table tags which define the GOT layout.
3032 std::optional<uint64_t> DtPltGot;
3033 std::optional<uint64_t> DtLocalGotNum;
3034 std::optional<uint64_t> DtGotSym;
3035 for (const auto &Entry : DynTable) {
3036 switch (Entry.getTag()) {
3037 case ELF::DT_PLTGOT:
3038 DtPltGot = Entry.getVal();
3039 break;
3040 case ELF::DT_MIPS_LOCAL_GOTNO:
3041 DtLocalGotNum = Entry.getVal();
3042 break;
3043 case ELF::DT_MIPS_GOTSYM:
3044 DtGotSym = Entry.getVal();
3045 break;
3049 if (!DtPltGot && !DtLocalGotNum && !DtGotSym)
3050 return Error::success();
3052 if (!DtPltGot)
3053 return createError("cannot find PLTGOT dynamic tag");
3054 if (!DtLocalGotNum)
3055 return createError("cannot find MIPS_LOCAL_GOTNO dynamic tag");
3056 if (!DtGotSym)
3057 return createError("cannot find MIPS_GOTSYM dynamic tag");
3059 size_t DynSymTotal = DynSyms.size();
3060 if (*DtGotSym > DynSymTotal)
3061 return createError("DT_MIPS_GOTSYM value (" + Twine(*DtGotSym) +
3062 ") exceeds the number of dynamic symbols (" +
3063 Twine(DynSymTotal) + ")");
3065 GotSec = findNotEmptySectionByAddress(Obj, FileName, *DtPltGot);
3066 if (!GotSec)
3067 return createError("there is no non-empty GOT section at 0x" +
3068 Twine::utohexstr(*DtPltGot));
3070 LocalNum = *DtLocalGotNum;
3071 GlobalNum = DynSymTotal - *DtGotSym;
3073 ArrayRef<uint8_t> Content =
3074 unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
3075 GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
3076 Content.size() / sizeof(Entry));
3077 GotDynSyms = DynSyms.drop_front(*DtGotSym);
3079 return Error::success();
3082 template <class ELFT>
3083 Error MipsGOTParser<ELFT>::findPLT(Elf_Dyn_Range DynTable) {
3084 // Lookup dynamic table tags which define the PLT layout.
3085 std::optional<uint64_t> DtMipsPltGot;
3086 std::optional<uint64_t> DtJmpRel;
3087 for (const auto &Entry : DynTable) {
3088 switch (Entry.getTag()) {
3089 case ELF::DT_MIPS_PLTGOT:
3090 DtMipsPltGot = Entry.getVal();
3091 break;
3092 case ELF::DT_JMPREL:
3093 DtJmpRel = Entry.getVal();
3094 break;
3098 if (!DtMipsPltGot && !DtJmpRel)
3099 return Error::success();
3101 // Find PLT section.
3102 if (!DtMipsPltGot)
3103 return createError("cannot find MIPS_PLTGOT dynamic tag");
3104 if (!DtJmpRel)
3105 return createError("cannot find JMPREL dynamic tag");
3107 PltSec = findNotEmptySectionByAddress(Obj, FileName, *DtMipsPltGot);
3108 if (!PltSec)
3109 return createError("there is no non-empty PLTGOT section at 0x" +
3110 Twine::utohexstr(*DtMipsPltGot));
3112 PltRelSec = findNotEmptySectionByAddress(Obj, FileName, *DtJmpRel);
3113 if (!PltRelSec)
3114 return createError("there is no non-empty RELPLT section at 0x" +
3115 Twine::utohexstr(*DtJmpRel));
3117 if (Expected<ArrayRef<uint8_t>> PltContentOrErr =
3118 Obj.getSectionContents(*PltSec))
3119 PltEntries =
3120 Entries(reinterpret_cast<const Entry *>(PltContentOrErr->data()),
3121 PltContentOrErr->size() / sizeof(Entry));
3122 else
3123 return createError("unable to read PLTGOT section content: " +
3124 toString(PltContentOrErr.takeError()));
3126 if (Expected<const Elf_Shdr *> PltSymTableOrErr =
3127 Obj.getSection(PltRelSec->sh_link))
3128 PltSymTable = *PltSymTableOrErr;
3129 else
3130 return createError("unable to get a symbol table linked to the " +
3131 describe(Obj, *PltRelSec) + ": " +
3132 toString(PltSymTableOrErr.takeError()));
3134 if (Expected<StringRef> StrTabOrErr =
3135 Obj.getStringTableForSymtab(*PltSymTable))
3136 PltStrTable = *StrTabOrErr;
3137 else
3138 return createError("unable to get a string table for the " +
3139 describe(Obj, *PltSymTable) + ": " +
3140 toString(StrTabOrErr.takeError()));
3142 return Error::success();
3145 template <class ELFT> uint64_t MipsGOTParser<ELFT>::getGp() const {
3146 return GotSec->sh_addr + 0x7ff0;
3149 template <class ELFT>
3150 const typename MipsGOTParser<ELFT>::Entry *
3151 MipsGOTParser<ELFT>::getGotLazyResolver() const {
3152 return LocalNum > 0 ? &GotEntries[0] : nullptr;
3155 template <class ELFT>
3156 const typename MipsGOTParser<ELFT>::Entry *
3157 MipsGOTParser<ELFT>::getGotModulePointer() const {
3158 if (LocalNum < 2)
3159 return nullptr;
3160 const Entry &E = GotEntries[1];
3161 if ((E >> (sizeof(Entry) * 8 - 1)) == 0)
3162 return nullptr;
3163 return &E;
3166 template <class ELFT>
3167 typename MipsGOTParser<ELFT>::Entries
3168 MipsGOTParser<ELFT>::getLocalEntries() const {
3169 size_t Skip = getGotModulePointer() ? 2 : 1;
3170 if (LocalNum - Skip <= 0)
3171 return Entries();
3172 return GotEntries.slice(Skip, LocalNum - Skip);
3175 template <class ELFT>
3176 typename MipsGOTParser<ELFT>::Entries
3177 MipsGOTParser<ELFT>::getGlobalEntries() const {
3178 if (GlobalNum == 0)
3179 return Entries();
3180 return GotEntries.slice(LocalNum, GlobalNum);
3183 template <class ELFT>
3184 typename MipsGOTParser<ELFT>::Entries
3185 MipsGOTParser<ELFT>::getOtherEntries() const {
3186 size_t OtherNum = GotEntries.size() - LocalNum - GlobalNum;
3187 if (OtherNum == 0)
3188 return Entries();
3189 return GotEntries.slice(LocalNum + GlobalNum, OtherNum);
3192 template <class ELFT>
3193 uint64_t MipsGOTParser<ELFT>::getGotAddress(const Entry *E) const {
3194 int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
3195 return GotSec->sh_addr + Offset;
3198 template <class ELFT>
3199 int64_t MipsGOTParser<ELFT>::getGotOffset(const Entry *E) const {
3200 int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
3201 return Offset - 0x7ff0;
3204 template <class ELFT>
3205 const typename MipsGOTParser<ELFT>::Elf_Sym *
3206 MipsGOTParser<ELFT>::getGotSym(const Entry *E) const {
3207 int64_t Offset = std::distance(GotEntries.data(), E);
3208 return &GotDynSyms[Offset - LocalNum];
3211 template <class ELFT>
3212 const typename MipsGOTParser<ELFT>::Entry *
3213 MipsGOTParser<ELFT>::getPltLazyResolver() const {
3214 return PltEntries.empty() ? nullptr : &PltEntries[0];
3217 template <class ELFT>
3218 const typename MipsGOTParser<ELFT>::Entry *
3219 MipsGOTParser<ELFT>::getPltModulePointer() const {
3220 return PltEntries.size() < 2 ? nullptr : &PltEntries[1];
3223 template <class ELFT>
3224 typename MipsGOTParser<ELFT>::Entries
3225 MipsGOTParser<ELFT>::getPltEntries() const {
3226 if (PltEntries.size() <= 2)
3227 return Entries();
3228 return PltEntries.slice(2, PltEntries.size() - 2);
3231 template <class ELFT>
3232 uint64_t MipsGOTParser<ELFT>::getPltAddress(const Entry *E) const {
3233 int64_t Offset = std::distance(PltEntries.data(), E) * sizeof(Entry);
3234 return PltSec->sh_addr + Offset;
3237 template <class ELFT>
3238 const typename MipsGOTParser<ELFT>::Elf_Sym *
3239 MipsGOTParser<ELFT>::getPltSym(const Entry *E) const {
3240 int64_t Offset = std::distance(getPltEntries().data(), E);
3241 if (PltRelSec->sh_type == ELF::SHT_REL) {
3242 Elf_Rel_Range Rels = unwrapOrError(FileName, Obj.rels(*PltRelSec));
3243 return unwrapOrError(FileName,
3244 Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
3245 } else {
3246 Elf_Rela_Range Rels = unwrapOrError(FileName, Obj.relas(*PltRelSec));
3247 return unwrapOrError(FileName,
3248 Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
3252 const EnumEntry<unsigned> ElfMipsISAExtType[] = {
3253 {"None", Mips::AFL_EXT_NONE},
3254 {"Broadcom SB-1", Mips::AFL_EXT_SB1},
3255 {"Cavium Networks Octeon", Mips::AFL_EXT_OCTEON},
3256 {"Cavium Networks Octeon2", Mips::AFL_EXT_OCTEON2},
3257 {"Cavium Networks OcteonP", Mips::AFL_EXT_OCTEONP},
3258 {"Cavium Networks Octeon3", Mips::AFL_EXT_OCTEON3},
3259 {"LSI R4010", Mips::AFL_EXT_4010},
3260 {"Loongson 2E", Mips::AFL_EXT_LOONGSON_2E},
3261 {"Loongson 2F", Mips::AFL_EXT_LOONGSON_2F},
3262 {"Loongson 3A", Mips::AFL_EXT_LOONGSON_3A},
3263 {"MIPS R4650", Mips::AFL_EXT_4650},
3264 {"MIPS R5900", Mips::AFL_EXT_5900},
3265 {"MIPS R10000", Mips::AFL_EXT_10000},
3266 {"NEC VR4100", Mips::AFL_EXT_4100},
3267 {"NEC VR4111/VR4181", Mips::AFL_EXT_4111},
3268 {"NEC VR4120", Mips::AFL_EXT_4120},
3269 {"NEC VR5400", Mips::AFL_EXT_5400},
3270 {"NEC VR5500", Mips::AFL_EXT_5500},
3271 {"RMI Xlr", Mips::AFL_EXT_XLR},
3272 {"Toshiba R3900", Mips::AFL_EXT_3900}
3275 const EnumEntry<unsigned> ElfMipsASEFlags[] = {
3276 {"DSP", Mips::AFL_ASE_DSP},
3277 {"DSPR2", Mips::AFL_ASE_DSPR2},
3278 {"Enhanced VA Scheme", Mips::AFL_ASE_EVA},
3279 {"MCU", Mips::AFL_ASE_MCU},
3280 {"MDMX", Mips::AFL_ASE_MDMX},
3281 {"MIPS-3D", Mips::AFL_ASE_MIPS3D},
3282 {"MT", Mips::AFL_ASE_MT},
3283 {"SmartMIPS", Mips::AFL_ASE_SMARTMIPS},
3284 {"VZ", Mips::AFL_ASE_VIRT},
3285 {"MSA", Mips::AFL_ASE_MSA},
3286 {"MIPS16", Mips::AFL_ASE_MIPS16},
3287 {"microMIPS", Mips::AFL_ASE_MICROMIPS},
3288 {"XPA", Mips::AFL_ASE_XPA},
3289 {"CRC", Mips::AFL_ASE_CRC},
3290 {"GINV", Mips::AFL_ASE_GINV},
3293 const EnumEntry<unsigned> ElfMipsFpABIType[] = {
3294 {"Hard or soft float", Mips::Val_GNU_MIPS_ABI_FP_ANY},
3295 {"Hard float (double precision)", Mips::Val_GNU_MIPS_ABI_FP_DOUBLE},
3296 {"Hard float (single precision)", Mips::Val_GNU_MIPS_ABI_FP_SINGLE},
3297 {"Soft float", Mips::Val_GNU_MIPS_ABI_FP_SOFT},
3298 {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)",
3299 Mips::Val_GNU_MIPS_ABI_FP_OLD_64},
3300 {"Hard float (32-bit CPU, Any FPU)", Mips::Val_GNU_MIPS_ABI_FP_XX},
3301 {"Hard float (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64},
3302 {"Hard float compat (32-bit CPU, 64-bit FPU)",
3303 Mips::Val_GNU_MIPS_ABI_FP_64A}
3306 static const EnumEntry<unsigned> ElfMipsFlags1[] {
3307 {"ODDSPREG", Mips::AFL_FLAGS1_ODDSPREG},
3310 static int getMipsRegisterSize(uint8_t Flag) {
3311 switch (Flag) {
3312 case Mips::AFL_REG_NONE:
3313 return 0;
3314 case Mips::AFL_REG_32:
3315 return 32;
3316 case Mips::AFL_REG_64:
3317 return 64;
3318 case Mips::AFL_REG_128:
3319 return 128;
3320 default:
3321 return -1;
3325 template <class ELFT>
3326 static void printMipsReginfoData(ScopedPrinter &W,
3327 const Elf_Mips_RegInfo<ELFT> &Reginfo) {
3328 W.printHex("GP", Reginfo.ri_gp_value);
3329 W.printHex("General Mask", Reginfo.ri_gprmask);
3330 W.printHex("Co-Proc Mask0", Reginfo.ri_cprmask[0]);
3331 W.printHex("Co-Proc Mask1", Reginfo.ri_cprmask[1]);
3332 W.printHex("Co-Proc Mask2", Reginfo.ri_cprmask[2]);
3333 W.printHex("Co-Proc Mask3", Reginfo.ri_cprmask[3]);
3336 template <class ELFT> void ELFDumper<ELFT>::printMipsReginfo() {
3337 const Elf_Shdr *RegInfoSec = findSectionByName(".reginfo");
3338 if (!RegInfoSec) {
3339 W.startLine() << "There is no .reginfo section in the file.\n";
3340 return;
3343 Expected<ArrayRef<uint8_t>> ContentsOrErr =
3344 Obj.getSectionContents(*RegInfoSec);
3345 if (!ContentsOrErr) {
3346 this->reportUniqueWarning(
3347 "unable to read the content of the .reginfo section (" +
3348 describe(*RegInfoSec) + "): " + toString(ContentsOrErr.takeError()));
3349 return;
3352 if (ContentsOrErr->size() < sizeof(Elf_Mips_RegInfo<ELFT>)) {
3353 this->reportUniqueWarning("the .reginfo section has an invalid size (0x" +
3354 Twine::utohexstr(ContentsOrErr->size()) + ")");
3355 return;
3358 DictScope GS(W, "MIPS RegInfo");
3359 printMipsReginfoData(W, *reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(
3360 ContentsOrErr->data()));
3363 template <class ELFT>
3364 static Expected<const Elf_Mips_Options<ELFT> *>
3365 readMipsOptions(const uint8_t *SecBegin, ArrayRef<uint8_t> &SecData,
3366 bool &IsSupported) {
3367 if (SecData.size() < sizeof(Elf_Mips_Options<ELFT>))
3368 return createError("the .MIPS.options section has an invalid size (0x" +
3369 Twine::utohexstr(SecData.size()) + ")");
3371 const Elf_Mips_Options<ELFT> *O =
3372 reinterpret_cast<const Elf_Mips_Options<ELFT> *>(SecData.data());
3373 const uint8_t Size = O->size;
3374 if (Size > SecData.size()) {
3375 const uint64_t Offset = SecData.data() - SecBegin;
3376 const uint64_t SecSize = Offset + SecData.size();
3377 return createError("a descriptor of size 0x" + Twine::utohexstr(Size) +
3378 " at offset 0x" + Twine::utohexstr(Offset) +
3379 " goes past the end of the .MIPS.options "
3380 "section of size 0x" +
3381 Twine::utohexstr(SecSize));
3384 IsSupported = O->kind == ODK_REGINFO;
3385 const size_t ExpectedSize =
3386 sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>);
3388 if (IsSupported)
3389 if (Size < ExpectedSize)
3390 return createError(
3391 "a .MIPS.options entry of kind " +
3392 Twine(getElfMipsOptionsOdkType(O->kind)) +
3393 " has an invalid size (0x" + Twine::utohexstr(Size) +
3394 "), the expected size is 0x" + Twine::utohexstr(ExpectedSize));
3396 SecData = SecData.drop_front(Size);
3397 return O;
3400 template <class ELFT> void ELFDumper<ELFT>::printMipsOptions() {
3401 const Elf_Shdr *MipsOpts = findSectionByName(".MIPS.options");
3402 if (!MipsOpts) {
3403 W.startLine() << "There is no .MIPS.options section in the file.\n";
3404 return;
3407 DictScope GS(W, "MIPS Options");
3409 ArrayRef<uint8_t> Data =
3410 unwrapOrError(ObjF.getFileName(), Obj.getSectionContents(*MipsOpts));
3411 const uint8_t *const SecBegin = Data.begin();
3412 while (!Data.empty()) {
3413 bool IsSupported;
3414 Expected<const Elf_Mips_Options<ELFT> *> OptsOrErr =
3415 readMipsOptions<ELFT>(SecBegin, Data, IsSupported);
3416 if (!OptsOrErr) {
3417 reportUniqueWarning(OptsOrErr.takeError());
3418 break;
3421 unsigned Kind = (*OptsOrErr)->kind;
3422 const char *Type = getElfMipsOptionsOdkType(Kind);
3423 if (!IsSupported) {
3424 W.startLine() << "Unsupported MIPS options tag: " << Type << " (" << Kind
3425 << ")\n";
3426 continue;
3429 DictScope GS(W, Type);
3430 if (Kind == ODK_REGINFO)
3431 printMipsReginfoData(W, (*OptsOrErr)->getRegInfo());
3432 else
3433 llvm_unreachable("unexpected .MIPS.options section descriptor kind");
3437 template <class ELFT> void ELFDumper<ELFT>::printStackMap() const {
3438 const Elf_Shdr *StackMapSection = findSectionByName(".llvm_stackmaps");
3439 if (!StackMapSection)
3440 return;
3442 auto Warn = [&](Error &&E) {
3443 this->reportUniqueWarning("unable to read the stack map from " +
3444 describe(*StackMapSection) + ": " +
3445 toString(std::move(E)));
3448 Expected<ArrayRef<uint8_t>> ContentOrErr =
3449 Obj.getSectionContents(*StackMapSection);
3450 if (!ContentOrErr) {
3451 Warn(ContentOrErr.takeError());
3452 return;
3455 if (Error E =
3456 StackMapParser<ELFT::Endianness>::validateHeader(*ContentOrErr)) {
3457 Warn(std::move(E));
3458 return;
3461 prettyPrintStackMap(W, StackMapParser<ELFT::Endianness>(*ContentOrErr));
3464 template <class ELFT>
3465 void ELFDumper<ELFT>::printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
3466 const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
3467 Expected<RelSymbol<ELFT>> Target = getRelocationTarget(R, SymTab);
3468 if (!Target)
3469 reportUniqueWarning("unable to print relocation " + Twine(RelIndex) +
3470 " in " + describe(Sec) + ": " +
3471 toString(Target.takeError()));
3472 else
3473 printRelRelaReloc(R, *Target);
3476 template <class ELFT>
3477 std::vector<EnumEntry<unsigned>>
3478 ELFDumper<ELFT>::getOtherFlagsFromSymbol(const Elf_Ehdr &Header,
3479 const Elf_Sym &Symbol) const {
3480 std::vector<EnumEntry<unsigned>> SymOtherFlags(std::begin(ElfSymOtherFlags),
3481 std::end(ElfSymOtherFlags));
3482 if (Header.e_machine == EM_MIPS) {
3483 // Someone in their infinite wisdom decided to make STO_MIPS_MIPS16
3484 // flag overlap with other ST_MIPS_xxx flags. So consider both
3485 // cases separately.
3486 if ((Symbol.st_other & STO_MIPS_MIPS16) == STO_MIPS_MIPS16)
3487 SymOtherFlags.insert(SymOtherFlags.end(),
3488 std::begin(ElfMips16SymOtherFlags),
3489 std::end(ElfMips16SymOtherFlags));
3490 else
3491 SymOtherFlags.insert(SymOtherFlags.end(),
3492 std::begin(ElfMipsSymOtherFlags),
3493 std::end(ElfMipsSymOtherFlags));
3494 } else if (Header.e_machine == EM_AARCH64) {
3495 SymOtherFlags.insert(SymOtherFlags.end(),
3496 std::begin(ElfAArch64SymOtherFlags),
3497 std::end(ElfAArch64SymOtherFlags));
3498 } else if (Header.e_machine == EM_RISCV) {
3499 SymOtherFlags.insert(SymOtherFlags.end(), std::begin(ElfRISCVSymOtherFlags),
3500 std::end(ElfRISCVSymOtherFlags));
3502 return SymOtherFlags;
3505 static inline void printFields(formatted_raw_ostream &OS, StringRef Str1,
3506 StringRef Str2) {
3507 OS.PadToColumn(2u);
3508 OS << Str1;
3509 OS.PadToColumn(37u);
3510 OS << Str2 << "\n";
3511 OS.flush();
3514 template <class ELFT>
3515 static std::string getSectionHeadersNumString(const ELFFile<ELFT> &Obj,
3516 StringRef FileName) {
3517 const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3518 if (ElfHeader.e_shnum != 0)
3519 return to_string(ElfHeader.e_shnum);
3521 Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3522 if (!ArrOrErr) {
3523 // In this case we can ignore an error, because we have already reported a
3524 // warning about the broken section header table earlier.
3525 consumeError(ArrOrErr.takeError());
3526 return "<?>";
3529 if (ArrOrErr->empty())
3530 return "0";
3531 return "0 (" + to_string((*ArrOrErr)[0].sh_size) + ")";
3534 template <class ELFT>
3535 static std::string getSectionHeaderTableIndexString(const ELFFile<ELFT> &Obj,
3536 StringRef FileName) {
3537 const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3538 if (ElfHeader.e_shstrndx != SHN_XINDEX)
3539 return to_string(ElfHeader.e_shstrndx);
3541 Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3542 if (!ArrOrErr) {
3543 // In this case we can ignore an error, because we have already reported a
3544 // warning about the broken section header table earlier.
3545 consumeError(ArrOrErr.takeError());
3546 return "<?>";
3549 if (ArrOrErr->empty())
3550 return "65535 (corrupt: out of range)";
3551 return to_string(ElfHeader.e_shstrndx) + " (" +
3552 to_string((*ArrOrErr)[0].sh_link) + ")";
3555 static const EnumEntry<unsigned> *getObjectFileEnumEntry(unsigned Type) {
3556 auto It = llvm::find_if(ElfObjectFileType, [&](const EnumEntry<unsigned> &E) {
3557 return E.Value == Type;
3559 if (It != ArrayRef(ElfObjectFileType).end())
3560 return It;
3561 return nullptr;
3564 template <class ELFT>
3565 void GNUELFDumper<ELFT>::printFileSummary(StringRef FileStr, ObjectFile &Obj,
3566 ArrayRef<std::string> InputFilenames,
3567 const Archive *A) {
3568 if (InputFilenames.size() > 1 || A) {
3569 this->W.startLine() << "\n";
3570 this->W.printString("File", FileStr);
3574 template <class ELFT> void GNUELFDumper<ELFT>::printFileHeaders() {
3575 const Elf_Ehdr &e = this->Obj.getHeader();
3576 OS << "ELF Header:\n";
3577 OS << " Magic: ";
3578 std::string Str;
3579 for (int i = 0; i < ELF::EI_NIDENT; i++)
3580 OS << format(" %02x", static_cast<int>(e.e_ident[i]));
3581 OS << "\n";
3582 Str = enumToString(e.e_ident[ELF::EI_CLASS], ArrayRef(ElfClass));
3583 printFields(OS, "Class:", Str);
3584 Str = enumToString(e.e_ident[ELF::EI_DATA], ArrayRef(ElfDataEncoding));
3585 printFields(OS, "Data:", Str);
3586 OS.PadToColumn(2u);
3587 OS << "Version:";
3588 OS.PadToColumn(37u);
3589 OS << utohexstr(e.e_ident[ELF::EI_VERSION]);
3590 if (e.e_version == ELF::EV_CURRENT)
3591 OS << " (current)";
3592 OS << "\n";
3593 auto OSABI = ArrayRef(ElfOSABI);
3594 if (e.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH &&
3595 e.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) {
3596 switch (e.e_machine) {
3597 case ELF::EM_ARM:
3598 OSABI = ArrayRef(ARMElfOSABI);
3599 break;
3600 case ELF::EM_AMDGPU:
3601 OSABI = ArrayRef(AMDGPUElfOSABI);
3602 break;
3603 default:
3604 break;
3607 Str = enumToString(e.e_ident[ELF::EI_OSABI], OSABI);
3608 printFields(OS, "OS/ABI:", Str);
3609 printFields(OS,
3610 "ABI Version:", std::to_string(e.e_ident[ELF::EI_ABIVERSION]));
3612 if (const EnumEntry<unsigned> *E = getObjectFileEnumEntry(e.e_type)) {
3613 Str = E->AltName.str();
3614 } else {
3615 if (e.e_type >= ET_LOPROC)
3616 Str = "Processor Specific: (" + utohexstr(e.e_type, /*LowerCase=*/true) + ")";
3617 else if (e.e_type >= ET_LOOS)
3618 Str = "OS Specific: (" + utohexstr(e.e_type, /*LowerCase=*/true) + ")";
3619 else
3620 Str = "<unknown>: " + utohexstr(e.e_type, /*LowerCase=*/true);
3622 printFields(OS, "Type:", Str);
3624 Str = enumToString(e.e_machine, ArrayRef(ElfMachineType));
3625 printFields(OS, "Machine:", Str);
3626 Str = "0x" + utohexstr(e.e_version);
3627 printFields(OS, "Version:", Str);
3628 Str = "0x" + utohexstr(e.e_entry);
3629 printFields(OS, "Entry point address:", Str);
3630 Str = to_string(e.e_phoff) + " (bytes into file)";
3631 printFields(OS, "Start of program headers:", Str);
3632 Str = to_string(e.e_shoff) + " (bytes into file)";
3633 printFields(OS, "Start of section headers:", Str);
3634 std::string ElfFlags;
3635 if (e.e_machine == EM_MIPS)
3636 ElfFlags = printFlags(
3637 e.e_flags, ArrayRef(ElfHeaderMipsFlags), unsigned(ELF::EF_MIPS_ARCH),
3638 unsigned(ELF::EF_MIPS_ABI), unsigned(ELF::EF_MIPS_MACH));
3639 else if (e.e_machine == EM_RISCV)
3640 ElfFlags = printFlags(e.e_flags, ArrayRef(ElfHeaderRISCVFlags));
3641 else if (e.e_machine == EM_SPARC32PLUS || e.e_machine == EM_SPARCV9)
3642 ElfFlags = printFlags(e.e_flags, ArrayRef(ElfHeaderSPARCFlags),
3643 unsigned(ELF::EF_SPARCV9_MM));
3644 else if (e.e_machine == EM_AVR)
3645 ElfFlags = printFlags(e.e_flags, ArrayRef(ElfHeaderAVRFlags),
3646 unsigned(ELF::EF_AVR_ARCH_MASK));
3647 else if (e.e_machine == EM_LOONGARCH)
3648 ElfFlags = printFlags(e.e_flags, ArrayRef(ElfHeaderLoongArchFlags),
3649 unsigned(ELF::EF_LOONGARCH_ABI_MODIFIER_MASK),
3650 unsigned(ELF::EF_LOONGARCH_OBJABI_MASK));
3651 else if (e.e_machine == EM_XTENSA)
3652 ElfFlags = printFlags(e.e_flags, ArrayRef(ElfHeaderXtensaFlags),
3653 unsigned(ELF::EF_XTENSA_MACH));
3654 else if (e.e_machine == EM_CUDA)
3655 ElfFlags = printFlags(e.e_flags, ArrayRef(ElfHeaderNVPTXFlags),
3656 unsigned(ELF::EF_CUDA_SM));
3657 else if (e.e_machine == EM_AMDGPU) {
3658 switch (e.e_ident[ELF::EI_ABIVERSION]) {
3659 default:
3660 break;
3661 case 0:
3662 // ELFOSABI_AMDGPU_PAL, ELFOSABI_AMDGPU_MESA3D support *_V3 flags.
3663 [[fallthrough]];
3664 case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
3665 ElfFlags =
3666 printFlags(e.e_flags, ArrayRef(ElfHeaderAMDGPUFlagsABIVersion3),
3667 unsigned(ELF::EF_AMDGPU_MACH));
3668 break;
3669 case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
3670 case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
3671 ElfFlags =
3672 printFlags(e.e_flags, ArrayRef(ElfHeaderAMDGPUFlagsABIVersion4),
3673 unsigned(ELF::EF_AMDGPU_MACH),
3674 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
3675 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
3676 break;
3677 case ELF::ELFABIVERSION_AMDGPU_HSA_V6: {
3678 ElfFlags =
3679 printFlags(e.e_flags, ArrayRef(ElfHeaderAMDGPUFlagsABIVersion4),
3680 unsigned(ELF::EF_AMDGPU_MACH),
3681 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
3682 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
3683 if (auto GenericV = e.e_flags & ELF::EF_AMDGPU_GENERIC_VERSION) {
3684 ElfFlags +=
3685 ", generic_v" +
3686 to_string(GenericV >> ELF::EF_AMDGPU_GENERIC_VERSION_OFFSET);
3688 } break;
3691 Str = "0x" + utohexstr(e.e_flags);
3692 if (!ElfFlags.empty())
3693 Str = Str + ", " + ElfFlags;
3694 printFields(OS, "Flags:", Str);
3695 Str = to_string(e.e_ehsize) + " (bytes)";
3696 printFields(OS, "Size of this header:", Str);
3697 Str = to_string(e.e_phentsize) + " (bytes)";
3698 printFields(OS, "Size of program headers:", Str);
3699 Str = to_string(e.e_phnum);
3700 printFields(OS, "Number of program headers:", Str);
3701 Str = to_string(e.e_shentsize) + " (bytes)";
3702 printFields(OS, "Size of section headers:", Str);
3703 Str = getSectionHeadersNumString(this->Obj, this->FileName);
3704 printFields(OS, "Number of section headers:", Str);
3705 Str = getSectionHeaderTableIndexString(this->Obj, this->FileName);
3706 printFields(OS, "Section header string table index:", Str);
3709 template <class ELFT> std::vector<GroupSection> ELFDumper<ELFT>::getGroups() {
3710 auto GetSignature = [&](const Elf_Sym &Sym, unsigned SymNdx,
3711 const Elf_Shdr &Symtab) -> StringRef {
3712 Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(Symtab);
3713 if (!StrTableOrErr) {
3714 reportUniqueWarning("unable to get the string table for " +
3715 describe(Symtab) + ": " +
3716 toString(StrTableOrErr.takeError()));
3717 return "<?>";
3720 StringRef Strings = *StrTableOrErr;
3721 if (Sym.st_name >= Strings.size()) {
3722 reportUniqueWarning("unable to get the name of the symbol with index " +
3723 Twine(SymNdx) + ": st_name (0x" +
3724 Twine::utohexstr(Sym.st_name) +
3725 ") is past the end of the string table of size 0x" +
3726 Twine::utohexstr(Strings.size()));
3727 return "<?>";
3730 return StrTableOrErr->data() + Sym.st_name;
3733 std::vector<GroupSection> Ret;
3734 uint64_t I = 0;
3735 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
3736 ++I;
3737 if (Sec.sh_type != ELF::SHT_GROUP)
3738 continue;
3740 StringRef Signature = "<?>";
3741 if (Expected<const Elf_Shdr *> SymtabOrErr = Obj.getSection(Sec.sh_link)) {
3742 if (Expected<const Elf_Sym *> SymOrErr =
3743 Obj.template getEntry<Elf_Sym>(**SymtabOrErr, Sec.sh_info))
3744 Signature = GetSignature(**SymOrErr, Sec.sh_info, **SymtabOrErr);
3745 else
3746 reportUniqueWarning("unable to get the signature symbol for " +
3747 describe(Sec) + ": " +
3748 toString(SymOrErr.takeError()));
3749 } else {
3750 reportUniqueWarning("unable to get the symbol table for " +
3751 describe(Sec) + ": " +
3752 toString(SymtabOrErr.takeError()));
3755 ArrayRef<Elf_Word> Data;
3756 if (Expected<ArrayRef<Elf_Word>> ContentsOrErr =
3757 Obj.template getSectionContentsAsArray<Elf_Word>(Sec)) {
3758 if (ContentsOrErr->empty())
3759 reportUniqueWarning("unable to read the section group flag from the " +
3760 describe(Sec) + ": the section is empty");
3761 else
3762 Data = *ContentsOrErr;
3763 } else {
3764 reportUniqueWarning("unable to get the content of the " + describe(Sec) +
3765 ": " + toString(ContentsOrErr.takeError()));
3768 Ret.push_back({getPrintableSectionName(Sec),
3769 maybeDemangle(Signature),
3770 Sec.sh_name,
3771 I - 1,
3772 Sec.sh_link,
3773 Sec.sh_info,
3774 Data.empty() ? Elf_Word(0) : Data[0],
3775 {}});
3777 if (Data.empty())
3778 continue;
3780 std::vector<GroupMember> &GM = Ret.back().Members;
3781 for (uint32_t Ndx : Data.slice(1)) {
3782 if (Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(Ndx)) {
3783 GM.push_back({getPrintableSectionName(**SecOrErr), Ndx});
3784 } else {
3785 reportUniqueWarning("unable to get the section with index " +
3786 Twine(Ndx) + " when dumping the " + describe(Sec) +
3787 ": " + toString(SecOrErr.takeError()));
3788 GM.push_back({"<?>", Ndx});
3792 return Ret;
3795 static DenseMap<uint64_t, const GroupSection *>
3796 mapSectionsToGroups(ArrayRef<GroupSection> Groups) {
3797 DenseMap<uint64_t, const GroupSection *> Ret;
3798 for (const GroupSection &G : Groups)
3799 for (const GroupMember &GM : G.Members)
3800 Ret.insert({GM.Index, &G});
3801 return Ret;
3804 template <class ELFT> void GNUELFDumper<ELFT>::printGroupSections() {
3805 std::vector<GroupSection> V = this->getGroups();
3806 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
3807 for (const GroupSection &G : V) {
3808 OS << "\n"
3809 << getGroupType(G.Type) << " group section ["
3810 << format_decimal(G.Index, 5) << "] `" << G.Name << "' [" << G.Signature
3811 << "] contains " << G.Members.size() << " sections:\n"
3812 << " [Index] Name\n";
3813 for (const GroupMember &GM : G.Members) {
3814 const GroupSection *MainGroup = Map[GM.Index];
3815 if (MainGroup != &G)
3816 this->reportUniqueWarning(
3817 "section with index " + Twine(GM.Index) +
3818 ", included in the group section with index " +
3819 Twine(MainGroup->Index) +
3820 ", was also found in the group section with index " +
3821 Twine(G.Index));
3822 OS << " [" << format_decimal(GM.Index, 5) << "] " << GM.Name << "\n";
3826 if (V.empty())
3827 OS << "There are no section groups in this file.\n";
3830 template <class ELFT>
3831 void GNUELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
3832 const RelSymbol<ELFT> &RelSym) {
3833 // First two fields are bit width dependent. The rest of them are fixed width.
3834 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3835 Field Fields[5] = {0, 10 + Bias, 19 + 2 * Bias, 42 + 2 * Bias, 53 + 2 * Bias};
3836 unsigned Width = ELFT::Is64Bits ? 16 : 8;
3838 Fields[0].Str = to_string(format_hex_no_prefix(R.Offset, Width));
3839 Fields[1].Str = to_string(format_hex_no_prefix(R.Info, Width));
3841 SmallString<32> RelocName;
3842 this->Obj.getRelocationTypeName(R.Type, RelocName);
3843 Fields[2].Str = RelocName.c_str();
3845 if (RelSym.Sym)
3846 Fields[3].Str =
3847 to_string(format_hex_no_prefix(RelSym.Sym->getValue(), Width));
3848 if (RelSym.Sym && RelSym.Name.empty())
3849 Fields[4].Str = "<null>";
3850 else
3851 Fields[4].Str = std::string(RelSym.Name);
3853 for (const Field &F : Fields)
3854 printField(F);
3856 std::string Addend;
3857 if (std::optional<int64_t> A = R.Addend) {
3858 int64_t RelAddend = *A;
3859 if (!Fields[4].Str.empty()) {
3860 if (RelAddend < 0) {
3861 Addend = " - ";
3862 RelAddend = -static_cast<uint64_t>(RelAddend);
3863 } else {
3864 Addend = " + ";
3867 Addend += utohexstr(RelAddend, /*LowerCase=*/true);
3869 OS << Addend << "\n";
3872 template <class ELFT>
3873 static void printRelocHeaderFields(formatted_raw_ostream &OS, unsigned SType,
3874 const typename ELFT::Ehdr &EHeader,
3875 uint64_t CrelHdr = 0) {
3876 bool IsRela = SType == ELF::SHT_RELA || SType == ELF::SHT_ANDROID_RELA;
3877 if (ELFT::Is64Bits)
3878 OS << " Offset Info Type Symbol's "
3879 "Value Symbol's Name";
3880 else
3881 OS << " Offset Info Type Sym. Value Symbol's Name";
3882 if (IsRela || (SType == ELF::SHT_CREL && (CrelHdr & CREL_HDR_ADDEND)))
3883 OS << " + Addend";
3884 OS << "\n";
3887 template <class ELFT>
3888 void GNUELFDumper<ELFT>::printDynamicRelocHeader(unsigned Type, StringRef Name,
3889 const DynRegionInfo &Reg) {
3890 uint64_t Offset = Reg.Addr - this->Obj.base();
3891 OS << "\n'" << Name.str().c_str() << "' relocation section at offset 0x"
3892 << utohexstr(Offset, /*LowerCase=*/true);
3893 if (Type != ELF::SHT_CREL)
3894 OS << " contains " << Reg.Size << " bytes";
3895 OS << ":\n";
3896 printRelocHeaderFields<ELFT>(OS, Type, this->Obj.getHeader());
3899 template <class ELFT>
3900 static bool isRelocationSec(const typename ELFT::Shdr &Sec,
3901 const typename ELFT::Ehdr &EHeader) {
3902 return Sec.sh_type == ELF::SHT_REL || Sec.sh_type == ELF::SHT_RELA ||
3903 Sec.sh_type == ELF::SHT_RELR || Sec.sh_type == ELF::SHT_CREL ||
3904 Sec.sh_type == ELF::SHT_ANDROID_REL ||
3905 Sec.sh_type == ELF::SHT_ANDROID_RELA ||
3906 Sec.sh_type == ELF::SHT_ANDROID_RELR ||
3907 (EHeader.e_machine == EM_AARCH64 &&
3908 Sec.sh_type == ELF::SHT_AARCH64_AUTH_RELR);
3911 template <class ELFT> void GNUELFDumper<ELFT>::printRelocations() {
3912 auto PrintAsRelr = [&](const Elf_Shdr &Sec) {
3913 return Sec.sh_type == ELF::SHT_RELR ||
3914 Sec.sh_type == ELF::SHT_ANDROID_RELR ||
3915 (this->Obj.getHeader().e_machine == EM_AARCH64 &&
3916 Sec.sh_type == ELF::SHT_AARCH64_AUTH_RELR);
3918 auto GetEntriesNum = [&](const Elf_Shdr &Sec) -> Expected<size_t> {
3919 // Android's packed relocation section needs to be unpacked first
3920 // to get the actual number of entries.
3921 if (Sec.sh_type == ELF::SHT_ANDROID_REL ||
3922 Sec.sh_type == ELF::SHT_ANDROID_RELA) {
3923 Expected<std::vector<typename ELFT::Rela>> RelasOrErr =
3924 this->Obj.android_relas(Sec);
3925 if (!RelasOrErr)
3926 return RelasOrErr.takeError();
3927 return RelasOrErr->size();
3930 if (Sec.sh_type == ELF::SHT_CREL) {
3931 Expected<ArrayRef<uint8_t>> ContentsOrErr =
3932 this->Obj.getSectionContents(Sec);
3933 if (!ContentsOrErr)
3934 return ContentsOrErr.takeError();
3935 auto NumOrErr = this->Obj.getCrelHeader(*ContentsOrErr);
3936 if (!NumOrErr)
3937 return NumOrErr.takeError();
3938 return *NumOrErr / 8;
3941 if (PrintAsRelr(Sec)) {
3942 Expected<Elf_Relr_Range> RelrsOrErr = this->Obj.relrs(Sec);
3943 if (!RelrsOrErr)
3944 return RelrsOrErr.takeError();
3945 return this->Obj.decode_relrs(*RelrsOrErr).size();
3948 return Sec.getEntityCount();
3951 bool HasRelocSections = false;
3952 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
3953 if (!isRelocationSec<ELFT>(Sec, this->Obj.getHeader()))
3954 continue;
3955 HasRelocSections = true;
3957 std::string EntriesNum = "<?>";
3958 if (Expected<size_t> NumOrErr = GetEntriesNum(Sec))
3959 EntriesNum = std::to_string(*NumOrErr);
3960 else
3961 this->reportUniqueWarning("unable to get the number of relocations in " +
3962 this->describe(Sec) + ": " +
3963 toString(NumOrErr.takeError()));
3965 uintX_t Offset = Sec.sh_offset;
3966 StringRef Name = this->getPrintableSectionName(Sec);
3967 OS << "\nRelocation section '" << Name << "' at offset 0x"
3968 << utohexstr(Offset, /*LowerCase=*/true) << " contains " << EntriesNum
3969 << " entries:\n";
3971 if (PrintAsRelr(Sec)) {
3972 printRelr(Sec);
3973 } else {
3974 uint64_t CrelHdr = 0;
3975 // For CREL, read the header and call printRelocationsHelper only if
3976 // GetEntriesNum(Sec) succeeded.
3977 if (Sec.sh_type == ELF::SHT_CREL && EntriesNum != "<?>") {
3978 CrelHdr = cantFail(this->Obj.getCrelHeader(
3979 cantFail(this->Obj.getSectionContents(Sec))));
3981 printRelocHeaderFields<ELFT>(OS, Sec.sh_type, this->Obj.getHeader(),
3982 CrelHdr);
3983 if (Sec.sh_type != ELF::SHT_CREL || EntriesNum != "<?>")
3984 this->printRelocationsHelper(Sec);
3987 if (!HasRelocSections)
3988 OS << "\nThere are no relocations in this file.\n";
3991 template <class ELFT> void GNUELFDumper<ELFT>::printRelr(const Elf_Shdr &Sec) {
3992 Expected<Elf_Relr_Range> RangeOrErr = this->Obj.relrs(Sec);
3993 if (!RangeOrErr) {
3994 this->reportUniqueWarning("unable to read relocations from " +
3995 this->describe(Sec) + ": " +
3996 toString(RangeOrErr.takeError()));
3997 return;
3999 if (ELFT::Is64Bits)
4000 OS << "Index: Entry Address Symbolic Address\n";
4001 else
4002 OS << "Index: Entry Address Symbolic Address\n";
4004 // If .symtab is available, collect its defined symbols and sort them by
4005 // st_value.
4006 SmallVector<std::pair<uint64_t, std::string>, 0> Syms;
4007 if (this->DotSymtabSec) {
4008 Elf_Sym_Range Symtab;
4009 std::optional<StringRef> Strtab;
4010 std::tie(Symtab, Strtab) = this->getSymtabAndStrtab();
4011 if (Symtab.size() && Strtab) {
4012 for (auto [I, Sym] : enumerate(Symtab)) {
4013 if (!Sym.st_shndx)
4014 continue;
4015 Syms.emplace_back(Sym.st_value,
4016 this->getFullSymbolName(Sym, I, ArrayRef<Elf_Word>(),
4017 *Strtab, false));
4021 llvm::stable_sort(Syms);
4023 typename ELFT::uint Base = 0;
4024 size_t I = 0;
4025 auto Print = [&](uint64_t Where) {
4026 OS << format_hex_no_prefix(Where, ELFT::Is64Bits ? 16 : 8);
4027 for (; I < Syms.size() && Syms[I].first <= Where; ++I)
4029 // Try symbolizing the address. Find the nearest symbol before or at the
4030 // address and print the symbol and the address difference.
4031 if (I) {
4032 OS << " " << Syms[I - 1].second;
4033 if (Syms[I - 1].first < Where)
4034 OS << " + 0x" << Twine::utohexstr(Where - Syms[I - 1].first);
4036 OS << '\n';
4038 for (auto [Index, R] : enumerate(*RangeOrErr)) {
4039 typename ELFT::uint Entry = R;
4040 OS << formatv("{0:4}: ", Index)
4041 << format_hex_no_prefix(Entry, ELFT::Is64Bits ? 16 : 8) << ' ';
4042 if ((Entry & 1) == 0) {
4043 Print(Entry);
4044 Base = Entry + sizeof(typename ELFT::uint);
4045 } else {
4046 bool First = true;
4047 for (auto Where = Base; Entry >>= 1;
4048 Where += sizeof(typename ELFT::uint)) {
4049 if (Entry & 1) {
4050 if (First)
4051 First = false;
4052 else
4053 OS.indent(ELFT::Is64Bits ? 24 : 16);
4054 Print(Where);
4057 Base += (CHAR_BIT * sizeof(Entry) - 1) * sizeof(typename ELFT::uint);
4062 // Print the offset of a particular section from anyone of the ranges:
4063 // [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER].
4064 // If 'Type' does not fall within any of those ranges, then a string is
4065 // returned as '<unknown>' followed by the type value.
4066 static std::string getSectionTypeOffsetString(unsigned Type) {
4067 if (Type >= SHT_LOOS && Type <= SHT_HIOS)
4068 return "LOOS+0x" + utohexstr(Type - SHT_LOOS);
4069 else if (Type >= SHT_LOPROC && Type <= SHT_HIPROC)
4070 return "LOPROC+0x" + utohexstr(Type - SHT_LOPROC);
4071 else if (Type >= SHT_LOUSER && Type <= SHT_HIUSER)
4072 return "LOUSER+0x" + utohexstr(Type - SHT_LOUSER);
4073 return "0x" + utohexstr(Type) + ": <unknown>";
4076 static std::string getSectionTypeString(unsigned Machine, unsigned Type) {
4077 StringRef Name = getELFSectionTypeName(Machine, Type);
4079 // Handle SHT_GNU_* type names.
4080 if (Name.consume_front("SHT_GNU_")) {
4081 if (Name == "HASH")
4082 return "GNU_HASH";
4083 // E.g. SHT_GNU_verneed -> VERNEED.
4084 return Name.upper();
4087 if (Name == "SHT_SYMTAB_SHNDX")
4088 return "SYMTAB SECTION INDICES";
4090 if (Name.consume_front("SHT_"))
4091 return Name.str();
4092 return getSectionTypeOffsetString(Type);
4095 static void printSectionDescription(formatted_raw_ostream &OS,
4096 unsigned EMachine) {
4097 OS << "Key to Flags:\n";
4098 OS << " W (write), A (alloc), X (execute), M (merge), S (strings), I "
4099 "(info),\n";
4100 OS << " L (link order), O (extra OS processing required), G (group), T "
4101 "(TLS),\n";
4102 OS << " C (compressed), x (unknown), o (OS specific), E (exclude),\n";
4103 OS << " R (retain)";
4105 if (EMachine == EM_X86_64)
4106 OS << ", l (large)";
4107 else if (EMachine == EM_ARM)
4108 OS << ", y (purecode)";
4110 OS << ", p (processor specific)\n";
4113 template <class ELFT> void GNUELFDumper<ELFT>::printSectionHeaders() {
4114 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
4115 if (Sections.empty()) {
4116 OS << "\nThere are no sections in this file.\n";
4117 Expected<StringRef> SecStrTableOrErr =
4118 this->Obj.getSectionStringTable(Sections, this->WarningHandler);
4119 if (!SecStrTableOrErr)
4120 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4121 return;
4123 unsigned Bias = ELFT::Is64Bits ? 0 : 8;
4124 OS << "There are " << to_string(Sections.size())
4125 << " section headers, starting at offset "
4126 << "0x" << utohexstr(this->Obj.getHeader().e_shoff, /*LowerCase=*/true) << ":\n\n";
4127 OS << "Section Headers:\n";
4128 Field Fields[11] = {
4129 {"[Nr]", 2}, {"Name", 7}, {"Type", 25},
4130 {"Address", 41}, {"Off", 58 - Bias}, {"Size", 65 - Bias},
4131 {"ES", 72 - Bias}, {"Flg", 75 - Bias}, {"Lk", 79 - Bias},
4132 {"Inf", 82 - Bias}, {"Al", 86 - Bias}};
4133 for (const Field &F : Fields)
4134 printField(F);
4135 OS << "\n";
4137 StringRef SecStrTable;
4138 if (Expected<StringRef> SecStrTableOrErr =
4139 this->Obj.getSectionStringTable(Sections, this->WarningHandler))
4140 SecStrTable = *SecStrTableOrErr;
4141 else
4142 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4144 size_t SectionIndex = 0;
4145 for (const Elf_Shdr &Sec : Sections) {
4146 Fields[0].Str = to_string(SectionIndex);
4147 if (SecStrTable.empty())
4148 Fields[1].Str = "<no-strings>";
4149 else
4150 Fields[1].Str = std::string(unwrapOrError<StringRef>(
4151 this->FileName, this->Obj.getSectionName(Sec, SecStrTable)));
4152 Fields[2].Str =
4153 getSectionTypeString(this->Obj.getHeader().e_machine, Sec.sh_type);
4154 Fields[3].Str =
4155 to_string(format_hex_no_prefix(Sec.sh_addr, ELFT::Is64Bits ? 16 : 8));
4156 Fields[4].Str = to_string(format_hex_no_prefix(Sec.sh_offset, 6));
4157 Fields[5].Str = to_string(format_hex_no_prefix(Sec.sh_size, 6));
4158 Fields[6].Str = to_string(format_hex_no_prefix(Sec.sh_entsize, 2));
4159 Fields[7].Str = getGNUFlags(this->Obj.getHeader().e_ident[ELF::EI_OSABI],
4160 this->Obj.getHeader().e_machine, Sec.sh_flags);
4161 Fields[8].Str = to_string(Sec.sh_link);
4162 Fields[9].Str = to_string(Sec.sh_info);
4163 Fields[10].Str = to_string(Sec.sh_addralign);
4165 OS.PadToColumn(Fields[0].Column);
4166 OS << "[" << right_justify(Fields[0].Str, 2) << "]";
4167 for (int i = 1; i < 7; i++)
4168 printField(Fields[i]);
4169 OS.PadToColumn(Fields[7].Column);
4170 OS << right_justify(Fields[7].Str, 3);
4171 OS.PadToColumn(Fields[8].Column);
4172 OS << right_justify(Fields[8].Str, 2);
4173 OS.PadToColumn(Fields[9].Column);
4174 OS << right_justify(Fields[9].Str, 3);
4175 OS.PadToColumn(Fields[10].Column);
4176 OS << right_justify(Fields[10].Str, 2);
4177 OS << "\n";
4178 ++SectionIndex;
4180 printSectionDescription(OS, this->Obj.getHeader().e_machine);
4183 template <class ELFT>
4184 void GNUELFDumper<ELFT>::printSymtabMessage(const Elf_Shdr *Symtab,
4185 size_t Entries,
4186 bool NonVisibilityBitsUsed,
4187 bool ExtraSymInfo) const {
4188 StringRef Name;
4189 if (Symtab)
4190 Name = this->getPrintableSectionName(*Symtab);
4191 if (!Name.empty())
4192 OS << "\nSymbol table '" << Name << "'";
4193 else
4194 OS << "\nSymbol table for image";
4195 OS << " contains " << Entries << " entries:\n";
4197 if (ELFT::Is64Bits) {
4198 OS << " Num: Value Size Type Bind Vis";
4199 if (ExtraSymInfo)
4200 OS << "+Other";
4201 } else {
4202 OS << " Num: Value Size Type Bind Vis";
4203 if (ExtraSymInfo)
4204 OS << "+Other";
4207 OS.PadToColumn((ELFT::Is64Bits ? 56 : 48) + (NonVisibilityBitsUsed ? 13 : 0));
4208 if (ExtraSymInfo)
4209 OS << "Ndx(SecName) Name [+ Version Info]\n";
4210 else
4211 OS << "Ndx Name\n";
4214 template <class ELFT>
4215 std::string GNUELFDumper<ELFT>::getSymbolSectionNdx(
4216 const Elf_Sym &Symbol, unsigned SymIndex, DataRegion<Elf_Word> ShndxTable,
4217 bool ExtraSymInfo) const {
4218 unsigned SectionIndex = Symbol.st_shndx;
4219 switch (SectionIndex) {
4220 case ELF::SHN_UNDEF:
4221 return "UND";
4222 case ELF::SHN_ABS:
4223 return "ABS";
4224 case ELF::SHN_COMMON:
4225 return "COM";
4226 case ELF::SHN_XINDEX: {
4227 Expected<uint32_t> IndexOrErr =
4228 object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, ShndxTable);
4229 if (!IndexOrErr) {
4230 assert(Symbol.st_shndx == SHN_XINDEX &&
4231 "getExtendedSymbolTableIndex should only fail due to an invalid "
4232 "SHT_SYMTAB_SHNDX table/reference");
4233 this->reportUniqueWarning(IndexOrErr.takeError());
4234 return "RSV[0xffff]";
4236 SectionIndex = *IndexOrErr;
4237 break;
4239 default:
4240 // Find if:
4241 // Processor specific
4242 if (SectionIndex >= ELF::SHN_LOPROC && SectionIndex <= ELF::SHN_HIPROC)
4243 return std::string("PRC[0x") +
4244 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
4245 // OS specific
4246 if (SectionIndex >= ELF::SHN_LOOS && SectionIndex <= ELF::SHN_HIOS)
4247 return std::string("OS[0x") +
4248 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
4249 // Architecture reserved:
4250 if (SectionIndex >= ELF::SHN_LORESERVE &&
4251 SectionIndex <= ELF::SHN_HIRESERVE)
4252 return std::string("RSV[0x") +
4253 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
4254 break;
4257 std::string Extra;
4258 if (ExtraSymInfo) {
4259 auto Sec = this->Obj.getSection(SectionIndex);
4260 if (!Sec) {
4261 this->reportUniqueWarning(Sec.takeError());
4262 } else {
4263 auto SecName = this->Obj.getSectionName(**Sec);
4264 if (!SecName)
4265 this->reportUniqueWarning(SecName.takeError());
4266 else
4267 Extra = Twine(" (" + *SecName + ")").str();
4270 return to_string(format_decimal(SectionIndex, 3)) + Extra;
4273 template <class ELFT>
4274 void GNUELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
4275 DataRegion<Elf_Word> ShndxTable,
4276 std::optional<StringRef> StrTable,
4277 bool IsDynamic, bool NonVisibilityBitsUsed,
4278 bool ExtraSymInfo) const {
4279 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4280 Field Fields[8] = {0, 8, 17 + Bias, 23 + Bias,
4281 31 + Bias, 38 + Bias, 48 + Bias, 51 + Bias};
4282 Fields[0].Str = to_string(format_decimal(SymIndex, 6)) + ":";
4283 Fields[1].Str =
4284 to_string(format_hex_no_prefix(Symbol.st_value, ELFT::Is64Bits ? 16 : 8));
4285 Fields[2].Str = to_string(format_decimal(Symbol.st_size, 5));
4287 unsigned char SymbolType = Symbol.getType();
4288 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
4289 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
4290 Fields[3].Str = enumToString(SymbolType, ArrayRef(AMDGPUSymbolTypes));
4291 else
4292 Fields[3].Str = enumToString(SymbolType, ArrayRef(ElfSymbolTypes));
4294 Fields[4].Str =
4295 enumToString(Symbol.getBinding(), ArrayRef(ElfSymbolBindings));
4296 Fields[5].Str =
4297 enumToString(Symbol.getVisibility(), ArrayRef(ElfSymbolVisibilities));
4299 if (Symbol.st_other & ~0x3) {
4300 if (this->Obj.getHeader().e_machine == ELF::EM_AARCH64) {
4301 uint8_t Other = Symbol.st_other & ~0x3;
4302 if (Other & STO_AARCH64_VARIANT_PCS) {
4303 Other &= ~STO_AARCH64_VARIANT_PCS;
4304 Fields[5].Str += " [VARIANT_PCS";
4305 if (Other != 0)
4306 Fields[5].Str.append(" | " + utohexstr(Other, /*LowerCase=*/true));
4307 Fields[5].Str.append("]");
4309 } else if (this->Obj.getHeader().e_machine == ELF::EM_RISCV) {
4310 uint8_t Other = Symbol.st_other & ~0x3;
4311 if (Other & STO_RISCV_VARIANT_CC) {
4312 Other &= ~STO_RISCV_VARIANT_CC;
4313 Fields[5].Str += " [VARIANT_CC";
4314 if (Other != 0)
4315 Fields[5].Str.append(" | " + utohexstr(Other, /*LowerCase=*/true));
4316 Fields[5].Str.append("]");
4318 } else {
4319 Fields[5].Str +=
4320 " [<other: " + to_string(format_hex(Symbol.st_other, 2)) + ">]";
4324 Fields[6].Column += NonVisibilityBitsUsed ? 13 : 0;
4325 Fields[6].Str =
4326 getSymbolSectionNdx(Symbol, SymIndex, ShndxTable, ExtraSymInfo);
4328 Fields[7].Column += ExtraSymInfo ? 10 : 0;
4329 Fields[7].Str = this->getFullSymbolName(Symbol, SymIndex, ShndxTable,
4330 StrTable, IsDynamic);
4331 for (const Field &Entry : Fields)
4332 printField(Entry);
4333 OS << "\n";
4336 template <class ELFT>
4337 void GNUELFDumper<ELFT>::printHashedSymbol(const Elf_Sym *Symbol,
4338 unsigned SymIndex,
4339 DataRegion<Elf_Word> ShndxTable,
4340 StringRef StrTable,
4341 uint32_t Bucket) {
4342 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4343 Field Fields[9] = {0, 6, 11, 20 + Bias, 25 + Bias,
4344 34 + Bias, 41 + Bias, 49 + Bias, 53 + Bias};
4345 Fields[0].Str = to_string(format_decimal(SymIndex, 5));
4346 Fields[1].Str = to_string(format_decimal(Bucket, 3)) + ":";
4348 Fields[2].Str = to_string(
4349 format_hex_no_prefix(Symbol->st_value, ELFT::Is64Bits ? 16 : 8));
4350 Fields[3].Str = to_string(format_decimal(Symbol->st_size, 5));
4352 unsigned char SymbolType = Symbol->getType();
4353 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
4354 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
4355 Fields[4].Str = enumToString(SymbolType, ArrayRef(AMDGPUSymbolTypes));
4356 else
4357 Fields[4].Str = enumToString(SymbolType, ArrayRef(ElfSymbolTypes));
4359 Fields[5].Str =
4360 enumToString(Symbol->getBinding(), ArrayRef(ElfSymbolBindings));
4361 Fields[6].Str =
4362 enumToString(Symbol->getVisibility(), ArrayRef(ElfSymbolVisibilities));
4363 Fields[7].Str = getSymbolSectionNdx(*Symbol, SymIndex, ShndxTable);
4364 Fields[8].Str =
4365 this->getFullSymbolName(*Symbol, SymIndex, ShndxTable, StrTable, true);
4367 for (const Field &Entry : Fields)
4368 printField(Entry);
4369 OS << "\n";
4372 template <class ELFT>
4373 void GNUELFDumper<ELFT>::printSymbols(bool PrintSymbols,
4374 bool PrintDynamicSymbols,
4375 bool ExtraSymInfo) {
4376 if (!PrintSymbols && !PrintDynamicSymbols)
4377 return;
4378 // GNU readelf prints both the .dynsym and .symtab with --symbols.
4379 this->printSymbolsHelper(true, ExtraSymInfo);
4380 if (PrintSymbols)
4381 this->printSymbolsHelper(false, ExtraSymInfo);
4384 template <class ELFT>
4385 void GNUELFDumper<ELFT>::printHashTableSymbols(const Elf_Hash &SysVHash) {
4386 if (this->DynamicStringTable.empty())
4387 return;
4389 if (ELFT::Is64Bits)
4390 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4391 else
4392 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4393 OS << "\n";
4395 Elf_Sym_Range DynSyms = this->dynamic_symbols();
4396 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
4397 if (!FirstSym) {
4398 this->reportUniqueWarning(
4399 Twine("unable to print symbols for the .hash table: the "
4400 "dynamic symbol table ") +
4401 (this->DynSymRegion ? "is empty" : "was not found"));
4402 return;
4405 DataRegion<Elf_Word> ShndxTable(
4406 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
4407 auto Buckets = SysVHash.buckets();
4408 auto Chains = SysVHash.chains();
4409 for (uint32_t Buc = 0; Buc < SysVHash.nbucket; Buc++) {
4410 if (Buckets[Buc] == ELF::STN_UNDEF)
4411 continue;
4412 BitVector Visited(SysVHash.nchain);
4413 for (uint32_t Ch = Buckets[Buc]; Ch < SysVHash.nchain; Ch = Chains[Ch]) {
4414 if (Ch == ELF::STN_UNDEF)
4415 break;
4417 if (Visited[Ch]) {
4418 this->reportUniqueWarning(".hash section is invalid: bucket " +
4419 Twine(Ch) +
4420 ": a cycle was detected in the linked chain");
4421 break;
4424 printHashedSymbol(FirstSym + Ch, Ch, ShndxTable, this->DynamicStringTable,
4425 Buc);
4426 Visited[Ch] = true;
4431 template <class ELFT>
4432 void GNUELFDumper<ELFT>::printGnuHashTableSymbols(const Elf_GnuHash &GnuHash) {
4433 if (this->DynamicStringTable.empty())
4434 return;
4436 Elf_Sym_Range DynSyms = this->dynamic_symbols();
4437 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
4438 if (!FirstSym) {
4439 this->reportUniqueWarning(
4440 Twine("unable to print symbols for the .gnu.hash table: the "
4441 "dynamic symbol table ") +
4442 (this->DynSymRegion ? "is empty" : "was not found"));
4443 return;
4446 auto GetSymbol = [&](uint64_t SymIndex,
4447 uint64_t SymsTotal) -> const Elf_Sym * {
4448 if (SymIndex >= SymsTotal) {
4449 this->reportUniqueWarning(
4450 "unable to print hashed symbol with index " + Twine(SymIndex) +
4451 ", which is greater than or equal to the number of dynamic symbols "
4452 "(" +
4453 Twine::utohexstr(SymsTotal) + ")");
4454 return nullptr;
4456 return FirstSym + SymIndex;
4459 Expected<ArrayRef<Elf_Word>> ValuesOrErr =
4460 getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHash);
4461 ArrayRef<Elf_Word> Values;
4462 if (!ValuesOrErr)
4463 this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH "
4464 "section: " +
4465 toString(ValuesOrErr.takeError()));
4466 else
4467 Values = *ValuesOrErr;
4469 DataRegion<Elf_Word> ShndxTable(
4470 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
4471 ArrayRef<Elf_Word> Buckets = GnuHash.buckets();
4472 for (uint32_t Buc = 0; Buc < GnuHash.nbuckets; Buc++) {
4473 if (Buckets[Buc] == ELF::STN_UNDEF)
4474 continue;
4475 uint32_t Index = Buckets[Buc];
4476 // Print whole chain.
4477 while (true) {
4478 uint32_t SymIndex = Index++;
4479 if (const Elf_Sym *Sym = GetSymbol(SymIndex, DynSyms.size()))
4480 printHashedSymbol(Sym, SymIndex, ShndxTable, this->DynamicStringTable,
4481 Buc);
4482 else
4483 break;
4485 if (SymIndex < GnuHash.symndx) {
4486 this->reportUniqueWarning(
4487 "unable to read the hash value for symbol with index " +
4488 Twine(SymIndex) +
4489 ", which is less than the index of the first hashed symbol (" +
4490 Twine(GnuHash.symndx) + ")");
4491 break;
4494 // Chain ends at symbol with stopper bit.
4495 if ((Values[SymIndex - GnuHash.symndx] & 1) == 1)
4496 break;
4501 template <class ELFT> void GNUELFDumper<ELFT>::printHashSymbols() {
4502 if (this->HashTable) {
4503 OS << "\n Symbol table of .hash for image:\n";
4504 if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
4505 this->reportUniqueWarning(std::move(E));
4506 else
4507 printHashTableSymbols(*this->HashTable);
4510 // Try printing the .gnu.hash table.
4511 if (this->GnuHashTable) {
4512 OS << "\n Symbol table of .gnu.hash for image:\n";
4513 if (ELFT::Is64Bits)
4514 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4515 else
4516 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4517 OS << "\n";
4519 if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
4520 this->reportUniqueWarning(std::move(E));
4521 else
4522 printGnuHashTableSymbols(*this->GnuHashTable);
4526 template <class ELFT> void GNUELFDumper<ELFT>::printSectionDetails() {
4527 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
4528 if (Sections.empty()) {
4529 OS << "\nThere are no sections in this file.\n";
4530 Expected<StringRef> SecStrTableOrErr =
4531 this->Obj.getSectionStringTable(Sections, this->WarningHandler);
4532 if (!SecStrTableOrErr)
4533 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4534 return;
4536 OS << "There are " << to_string(Sections.size())
4537 << " section headers, starting at offset "
4538 << "0x" << utohexstr(this->Obj.getHeader().e_shoff, /*LowerCase=*/true) << ":\n\n";
4540 OS << "Section Headers:\n";
4542 auto PrintFields = [&](ArrayRef<Field> V) {
4543 for (const Field &F : V)
4544 printField(F);
4545 OS << "\n";
4548 PrintFields({{"[Nr]", 2}, {"Name", 7}});
4550 constexpr bool Is64 = ELFT::Is64Bits;
4551 PrintFields({{"Type", 7},
4552 {Is64 ? "Address" : "Addr", 23},
4553 {"Off", Is64 ? 40 : 32},
4554 {"Size", Is64 ? 47 : 39},
4555 {"ES", Is64 ? 54 : 46},
4556 {"Lk", Is64 ? 59 : 51},
4557 {"Inf", Is64 ? 62 : 54},
4558 {"Al", Is64 ? 66 : 57}});
4559 PrintFields({{"Flags", 7}});
4561 StringRef SecStrTable;
4562 if (Expected<StringRef> SecStrTableOrErr =
4563 this->Obj.getSectionStringTable(Sections, this->WarningHandler))
4564 SecStrTable = *SecStrTableOrErr;
4565 else
4566 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4568 size_t SectionIndex = 0;
4569 const unsigned AddrSize = Is64 ? 16 : 8;
4570 for (const Elf_Shdr &S : Sections) {
4571 StringRef Name = "<?>";
4572 if (Expected<StringRef> NameOrErr =
4573 this->Obj.getSectionName(S, SecStrTable))
4574 Name = *NameOrErr;
4575 else
4576 this->reportUniqueWarning(NameOrErr.takeError());
4578 OS.PadToColumn(2);
4579 OS << "[" << right_justify(to_string(SectionIndex), 2) << "]";
4580 PrintFields({{Name, 7}});
4581 PrintFields(
4582 {{getSectionTypeString(this->Obj.getHeader().e_machine, S.sh_type), 7},
4583 {to_string(format_hex_no_prefix(S.sh_addr, AddrSize)), 23},
4584 {to_string(format_hex_no_prefix(S.sh_offset, 6)), Is64 ? 39 : 32},
4585 {to_string(format_hex_no_prefix(S.sh_size, 6)), Is64 ? 47 : 39},
4586 {to_string(format_hex_no_prefix(S.sh_entsize, 2)), Is64 ? 54 : 46},
4587 {to_string(S.sh_link), Is64 ? 59 : 51},
4588 {to_string(S.sh_info), Is64 ? 63 : 55},
4589 {to_string(S.sh_addralign), Is64 ? 66 : 58}});
4591 OS.PadToColumn(7);
4592 OS << "[" << to_string(format_hex_no_prefix(S.sh_flags, AddrSize)) << "]: ";
4594 DenseMap<unsigned, StringRef> FlagToName = {
4595 {SHF_WRITE, "WRITE"}, {SHF_ALLOC, "ALLOC"},
4596 {SHF_EXECINSTR, "EXEC"}, {SHF_MERGE, "MERGE"},
4597 {SHF_STRINGS, "STRINGS"}, {SHF_INFO_LINK, "INFO LINK"},
4598 {SHF_LINK_ORDER, "LINK ORDER"}, {SHF_OS_NONCONFORMING, "OS NONCONF"},
4599 {SHF_GROUP, "GROUP"}, {SHF_TLS, "TLS"},
4600 {SHF_COMPRESSED, "COMPRESSED"}, {SHF_EXCLUDE, "EXCLUDE"}};
4602 uint64_t Flags = S.sh_flags;
4603 uint64_t UnknownFlags = 0;
4604 ListSeparator LS;
4605 while (Flags) {
4606 // Take the least significant bit as a flag.
4607 uint64_t Flag = Flags & -Flags;
4608 Flags -= Flag;
4610 auto It = FlagToName.find(Flag);
4611 if (It != FlagToName.end())
4612 OS << LS << It->second;
4613 else
4614 UnknownFlags |= Flag;
4617 auto PrintUnknownFlags = [&](uint64_t Mask, StringRef Name) {
4618 uint64_t FlagsToPrint = UnknownFlags & Mask;
4619 if (!FlagsToPrint)
4620 return;
4622 OS << LS << Name << " ("
4623 << to_string(format_hex_no_prefix(FlagsToPrint, AddrSize)) << ")";
4624 UnknownFlags &= ~Mask;
4627 PrintUnknownFlags(SHF_MASKOS, "OS");
4628 PrintUnknownFlags(SHF_MASKPROC, "PROC");
4629 PrintUnknownFlags(uint64_t(-1), "UNKNOWN");
4631 OS << "\n";
4632 ++SectionIndex;
4634 if (!(S.sh_flags & SHF_COMPRESSED))
4635 continue;
4636 Expected<ArrayRef<uint8_t>> Data = this->Obj.getSectionContents(S);
4637 if (!Data || Data->size() < sizeof(Elf_Chdr)) {
4638 consumeError(Data.takeError());
4639 reportWarning(createError("SHF_COMPRESSED section '" + Name +
4640 "' does not have an Elf_Chdr header"),
4641 this->FileName);
4642 OS.indent(7);
4643 OS << "[<corrupt>]";
4644 } else {
4645 OS.indent(7);
4646 auto *Chdr = reinterpret_cast<const Elf_Chdr *>(Data->data());
4647 if (Chdr->ch_type == ELFCOMPRESS_ZLIB)
4648 OS << "ZLIB";
4649 else if (Chdr->ch_type == ELFCOMPRESS_ZSTD)
4650 OS << "ZSTD";
4651 else
4652 OS << format("[<unknown>: 0x%x]", unsigned(Chdr->ch_type));
4653 OS << ", " << format_hex_no_prefix(Chdr->ch_size, ELFT::Is64Bits ? 16 : 8)
4654 << ", " << Chdr->ch_addralign;
4656 OS << '\n';
4660 static inline std::string printPhdrFlags(unsigned Flag) {
4661 std::string Str;
4662 Str = (Flag & PF_R) ? "R" : " ";
4663 Str += (Flag & PF_W) ? "W" : " ";
4664 Str += (Flag & PF_X) ? "E" : " ";
4665 return Str;
4668 template <class ELFT>
4669 static bool checkTLSSections(const typename ELFT::Phdr &Phdr,
4670 const typename ELFT::Shdr &Sec) {
4671 if (Sec.sh_flags & ELF::SHF_TLS) {
4672 // .tbss must only be shown in the PT_TLS segment.
4673 if (Sec.sh_type == ELF::SHT_NOBITS)
4674 return Phdr.p_type == ELF::PT_TLS;
4676 // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO
4677 // segments.
4678 return (Phdr.p_type == ELF::PT_TLS) || (Phdr.p_type == ELF::PT_LOAD) ||
4679 (Phdr.p_type == ELF::PT_GNU_RELRO);
4682 // PT_TLS must only have SHF_TLS sections.
4683 return Phdr.p_type != ELF::PT_TLS;
4686 template <class ELFT>
4687 static bool checkPTDynamic(const typename ELFT::Phdr &Phdr,
4688 const typename ELFT::Shdr &Sec) {
4689 if (Phdr.p_type != ELF::PT_DYNAMIC || Phdr.p_memsz == 0 || Sec.sh_size != 0)
4690 return true;
4692 // We get here when we have an empty section. Only non-empty sections can be
4693 // at the start or at the end of PT_DYNAMIC.
4694 // Is section within the phdr both based on offset and VMA?
4695 bool CheckOffset = (Sec.sh_type == ELF::SHT_NOBITS) ||
4696 (Sec.sh_offset > Phdr.p_offset &&
4697 Sec.sh_offset < Phdr.p_offset + Phdr.p_filesz);
4698 bool CheckVA = !(Sec.sh_flags & ELF::SHF_ALLOC) ||
4699 (Sec.sh_addr > Phdr.p_vaddr && Sec.sh_addr < Phdr.p_memsz);
4700 return CheckOffset && CheckVA;
4703 template <class ELFT>
4704 void GNUELFDumper<ELFT>::printProgramHeaders(
4705 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
4706 const bool ShouldPrintSectionMapping = (PrintSectionMapping != cl::BOU_FALSE);
4707 // Exit early if no program header or section mapping details were requested.
4708 if (!PrintProgramHeaders && !ShouldPrintSectionMapping)
4709 return;
4711 if (PrintProgramHeaders) {
4712 const Elf_Ehdr &Header = this->Obj.getHeader();
4713 if (Header.e_phnum == 0) {
4714 OS << "\nThere are no program headers in this file.\n";
4715 } else {
4716 printProgramHeaders();
4720 if (ShouldPrintSectionMapping)
4721 printSectionMapping();
4724 template <class ELFT> void GNUELFDumper<ELFT>::printProgramHeaders() {
4725 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4726 const Elf_Ehdr &Header = this->Obj.getHeader();
4727 Field Fields[8] = {2, 17, 26, 37 + Bias,
4728 48 + Bias, 56 + Bias, 64 + Bias, 68 + Bias};
4729 OS << "\nElf file type is "
4730 << enumToString(Header.e_type, ArrayRef(ElfObjectFileType)) << "\n"
4731 << "Entry point " << format_hex(Header.e_entry, 3) << "\n"
4732 << "There are " << Header.e_phnum << " program headers,"
4733 << " starting at offset " << Header.e_phoff << "\n\n"
4734 << "Program Headers:\n";
4735 if (ELFT::Is64Bits)
4736 OS << " Type Offset VirtAddr PhysAddr "
4737 << " FileSiz MemSiz Flg Align\n";
4738 else
4739 OS << " Type Offset VirtAddr PhysAddr FileSiz "
4740 << "MemSiz Flg Align\n";
4742 unsigned Width = ELFT::Is64Bits ? 18 : 10;
4743 unsigned SizeWidth = ELFT::Is64Bits ? 8 : 7;
4745 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4746 if (!PhdrsOrErr) {
4747 this->reportUniqueWarning("unable to dump program headers: " +
4748 toString(PhdrsOrErr.takeError()));
4749 return;
4752 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4753 Fields[0].Str = getGNUPtType(Header.e_machine, Phdr.p_type);
4754 Fields[1].Str = to_string(format_hex(Phdr.p_offset, 8));
4755 Fields[2].Str = to_string(format_hex(Phdr.p_vaddr, Width));
4756 Fields[3].Str = to_string(format_hex(Phdr.p_paddr, Width));
4757 Fields[4].Str = to_string(format_hex(Phdr.p_filesz, SizeWidth));
4758 Fields[5].Str = to_string(format_hex(Phdr.p_memsz, SizeWidth));
4759 Fields[6].Str = printPhdrFlags(Phdr.p_flags);
4760 Fields[7].Str = to_string(format_hex(Phdr.p_align, 1));
4761 for (const Field &F : Fields)
4762 printField(F);
4763 if (Phdr.p_type == ELF::PT_INTERP) {
4764 OS << "\n";
4765 auto ReportBadInterp = [&](const Twine &Msg) {
4766 this->reportUniqueWarning(
4767 "unable to read program interpreter name at offset 0x" +
4768 Twine::utohexstr(Phdr.p_offset) + ": " + Msg);
4771 if (Phdr.p_offset >= this->Obj.getBufSize()) {
4772 ReportBadInterp("it goes past the end of the file (0x" +
4773 Twine::utohexstr(this->Obj.getBufSize()) + ")");
4774 continue;
4777 const char *Data =
4778 reinterpret_cast<const char *>(this->Obj.base()) + Phdr.p_offset;
4779 size_t MaxSize = this->Obj.getBufSize() - Phdr.p_offset;
4780 size_t Len = strnlen(Data, MaxSize);
4781 if (Len == MaxSize) {
4782 ReportBadInterp("it is not null-terminated");
4783 continue;
4786 OS << " [Requesting program interpreter: ";
4787 OS << StringRef(Data, Len) << "]";
4789 OS << "\n";
4793 template <class ELFT> void GNUELFDumper<ELFT>::printSectionMapping() {
4794 OS << "\n Section to Segment mapping:\n Segment Sections...\n";
4795 DenseSet<const Elf_Shdr *> BelongsToSegment;
4796 int Phnum = 0;
4798 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4799 if (!PhdrsOrErr) {
4800 this->reportUniqueWarning(
4801 "can't read program headers to build section to segment mapping: " +
4802 toString(PhdrsOrErr.takeError()));
4803 return;
4806 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4807 std::string Sections;
4808 OS << format(" %2.2d ", Phnum++);
4809 // Check if each section is in a segment and then print mapping.
4810 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4811 if (Sec.sh_type == ELF::SHT_NULL)
4812 continue;
4814 // readelf additionally makes sure it does not print zero sized sections
4815 // at end of segments and for PT_DYNAMIC both start and end of section
4816 // .tbss must only be shown in PT_TLS section.
4817 if (isSectionInSegment<ELFT>(Phdr, Sec) &&
4818 checkTLSSections<ELFT>(Phdr, Sec) &&
4819 checkPTDynamic<ELFT>(Phdr, Sec)) {
4820 Sections +=
4821 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4822 " ";
4823 BelongsToSegment.insert(&Sec);
4826 OS << Sections << "\n";
4827 OS.flush();
4830 // Display sections that do not belong to a segment.
4831 std::string Sections;
4832 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4833 if (BelongsToSegment.find(&Sec) == BelongsToSegment.end())
4834 Sections +=
4835 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4836 ' ';
4838 if (!Sections.empty()) {
4839 OS << " None " << Sections << '\n';
4840 OS.flush();
4844 namespace {
4846 template <class ELFT>
4847 RelSymbol<ELFT> getSymbolForReloc(const ELFDumper<ELFT> &Dumper,
4848 const Relocation<ELFT> &Reloc) {
4849 using Elf_Sym = typename ELFT::Sym;
4850 auto WarnAndReturn = [&](const Elf_Sym *Sym,
4851 const Twine &Reason) -> RelSymbol<ELFT> {
4852 Dumper.reportUniqueWarning(
4853 "unable to get name of the dynamic symbol with index " +
4854 Twine(Reloc.Symbol) + ": " + Reason);
4855 return {Sym, "<corrupt>"};
4858 ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols();
4859 const Elf_Sym *FirstSym = Symbols.begin();
4860 if (!FirstSym)
4861 return WarnAndReturn(nullptr, "no dynamic symbol table found");
4863 // We might have an object without a section header. In this case the size of
4864 // Symbols is zero, because there is no way to know the size of the dynamic
4865 // table. We should allow this case and not print a warning.
4866 if (!Symbols.empty() && Reloc.Symbol >= Symbols.size())
4867 return WarnAndReturn(
4868 nullptr,
4869 "index is greater than or equal to the number of dynamic symbols (" +
4870 Twine(Symbols.size()) + ")");
4872 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
4873 const uint64_t FileSize = Obj.getBufSize();
4874 const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) +
4875 (uint64_t)Reloc.Symbol * sizeof(Elf_Sym);
4876 if (SymOffset + sizeof(Elf_Sym) > FileSize)
4877 return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(SymOffset) +
4878 " goes past the end of the file (0x" +
4879 Twine::utohexstr(FileSize) + ")");
4881 const Elf_Sym *Sym = FirstSym + Reloc.Symbol;
4882 Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable());
4883 if (!ErrOrName)
4884 return WarnAndReturn(Sym, toString(ErrOrName.takeError()));
4886 return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(*ErrOrName)};
4888 } // namespace
4890 template <class ELFT>
4891 static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj,
4892 typename ELFT::DynRange Tags) {
4893 size_t Max = 0;
4894 for (const typename ELFT::Dyn &Dyn : Tags)
4895 Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size());
4896 return Max;
4899 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicTable() {
4900 Elf_Dyn_Range Table = this->dynamic_table();
4901 if (Table.empty())
4902 return;
4904 OS << "Dynamic section at offset "
4905 << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable.Addr) -
4906 this->Obj.base(),
4908 << " contains " << Table.size() << " entries:\n";
4910 // The type name is surrounded with round brackets, hence add 2.
4911 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2;
4912 // The "Name/Value" column should be indented from the "Type" column by N
4913 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
4914 // space (1) = 3.
4915 OS << " Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type"
4916 << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
4918 std::string ValueFmt = " %-" + std::to_string(MaxTagSize) + "s ";
4919 for (auto Entry : Table) {
4920 uintX_t Tag = Entry.getTag();
4921 std::string Type =
4922 std::string("(") + this->Obj.getDynamicTagAsString(Tag) + ")";
4923 std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
4924 OS << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10)
4925 << format(ValueFmt.c_str(), Type.c_str()) << Value << "\n";
4929 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicRelocations() {
4930 this->printDynamicRelocationsHelper();
4933 template <class ELFT>
4934 void ELFDumper<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) {
4935 printRelRelaReloc(R, getSymbolForReloc(*this, R));
4938 template <class ELFT>
4939 void ELFDumper<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) {
4940 this->forEachRelocationDo(
4941 Sec, [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
4942 const Elf_Shdr *SymTab) { printReloc(R, Ndx, Sec, SymTab); });
4945 template <class ELFT> void ELFDumper<ELFT>::printDynamicRelocationsHelper() {
4946 const bool IsMips64EL = this->Obj.isMips64EL();
4947 auto DumpCrelRegion = [&](DynRegionInfo &Region) {
4948 // While the size is unknown, a valid CREL has at least one byte. We can
4949 // check whether Addr is in bounds, and then decode CREL until the file
4950 // end.
4951 Region.Size = Region.EntSize = 1;
4952 if (!Region.template getAsArrayRef<uint8_t>().empty()) {
4953 const uint64_t Offset =
4954 Region.Addr - reinterpret_cast<const uint8_t *>(
4955 ObjF.getMemoryBufferRef().getBufferStart());
4956 const uint64_t ObjSize = ObjF.getMemoryBufferRef().getBufferSize();
4957 auto RelsOrRelas =
4958 Obj.decodeCrel(ArrayRef<uint8_t>(Region.Addr, ObjSize - Offset));
4959 if (!RelsOrRelas) {
4960 reportUniqueWarning(toString(RelsOrRelas.takeError()));
4961 } else {
4962 for (const Elf_Rel &R : RelsOrRelas->first)
4963 printDynamicReloc(Relocation<ELFT>(R, false));
4964 for (const Elf_Rela &R : RelsOrRelas->second)
4965 printDynamicReloc(Relocation<ELFT>(R, false));
4970 if (this->DynCrelRegion.Addr) {
4971 printDynamicRelocHeader(ELF::SHT_CREL, "CREL", this->DynCrelRegion);
4972 DumpCrelRegion(this->DynCrelRegion);
4975 if (this->DynRelaRegion.Size > 0) {
4976 printDynamicRelocHeader(ELF::SHT_RELA, "RELA", this->DynRelaRegion);
4977 for (const Elf_Rela &Rela :
4978 this->DynRelaRegion.template getAsArrayRef<Elf_Rela>())
4979 printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
4982 if (this->DynRelRegion.Size > 0) {
4983 printDynamicRelocHeader(ELF::SHT_REL, "REL", this->DynRelRegion);
4984 for (const Elf_Rel &Rel :
4985 this->DynRelRegion.template getAsArrayRef<Elf_Rel>())
4986 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4989 if (this->DynRelrRegion.Size > 0) {
4990 printDynamicRelocHeader(ELF::SHT_REL, "RELR", this->DynRelrRegion);
4991 Elf_Relr_Range Relrs =
4992 this->DynRelrRegion.template getAsArrayRef<Elf_Relr>();
4993 for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs))
4994 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4997 if (this->DynPLTRelRegion.Size) {
4998 if (this->DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) {
4999 printDynamicRelocHeader(ELF::SHT_RELA, "PLT", this->DynPLTRelRegion);
5000 for (const Elf_Rela &Rela :
5001 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rela>())
5002 printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
5003 } else if (this->DynPLTRelRegion.EntSize == 1) {
5004 DumpCrelRegion(this->DynPLTRelRegion);
5005 } else {
5006 printDynamicRelocHeader(ELF::SHT_REL, "PLT", this->DynPLTRelRegion);
5007 for (const Elf_Rel &Rel :
5008 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rel>())
5009 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
5014 template <class ELFT>
5015 void GNUELFDumper<ELFT>::printGNUVersionSectionProlog(
5016 const typename ELFT::Shdr &Sec, const Twine &Label, unsigned EntriesNum) {
5017 // Don't inline the SecName, because it might report a warning to stderr and
5018 // corrupt the output.
5019 StringRef SecName = this->getPrintableSectionName(Sec);
5020 OS << Label << " section '" << SecName << "' "
5021 << "contains " << EntriesNum << " entries:\n";
5023 StringRef LinkedSecName = "<corrupt>";
5024 if (Expected<const typename ELFT::Shdr *> LinkedSecOrErr =
5025 this->Obj.getSection(Sec.sh_link))
5026 LinkedSecName = this->getPrintableSectionName(**LinkedSecOrErr);
5027 else
5028 this->reportUniqueWarning("invalid section linked to " +
5029 this->describe(Sec) + ": " +
5030 toString(LinkedSecOrErr.takeError()));
5032 OS << " Addr: " << format_hex_no_prefix(Sec.sh_addr, 16)
5033 << " Offset: " << format_hex(Sec.sh_offset, 8)
5034 << " Link: " << Sec.sh_link << " (" << LinkedSecName << ")\n";
5037 template <class ELFT>
5038 void GNUELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
5039 if (!Sec)
5040 return;
5042 printGNUVersionSectionProlog(*Sec, "Version symbols",
5043 Sec->sh_size / sizeof(Elf_Versym));
5044 Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
5045 this->getVersionTable(*Sec, /*SymTab=*/nullptr,
5046 /*StrTab=*/nullptr, /*SymTabSec=*/nullptr);
5047 if (!VerTableOrErr) {
5048 this->reportUniqueWarning(VerTableOrErr.takeError());
5049 return;
5052 SmallVector<std::optional<VersionEntry>, 0> *VersionMap = nullptr;
5053 if (Expected<SmallVector<std::optional<VersionEntry>, 0> *> MapOrErr =
5054 this->getVersionMap())
5055 VersionMap = *MapOrErr;
5056 else
5057 this->reportUniqueWarning(MapOrErr.takeError());
5059 ArrayRef<Elf_Versym> VerTable = *VerTableOrErr;
5060 std::vector<StringRef> Versions;
5061 for (size_t I = 0, E = VerTable.size(); I < E; ++I) {
5062 unsigned Ndx = VerTable[I].vs_index;
5063 if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) {
5064 Versions.emplace_back(Ndx == VER_NDX_LOCAL ? "*local*" : "*global*");
5065 continue;
5068 if (!VersionMap) {
5069 Versions.emplace_back("<corrupt>");
5070 continue;
5073 bool IsDefault;
5074 Expected<StringRef> NameOrErr = this->Obj.getSymbolVersionByIndex(
5075 Ndx, IsDefault, *VersionMap, /*IsSymHidden=*/std::nullopt);
5076 if (!NameOrErr) {
5077 this->reportUniqueWarning("unable to get a version for entry " +
5078 Twine(I) + " of " + this->describe(*Sec) +
5079 ": " + toString(NameOrErr.takeError()));
5080 Versions.emplace_back("<corrupt>");
5081 continue;
5083 Versions.emplace_back(*NameOrErr);
5086 // readelf prints 4 entries per line.
5087 uint64_t Entries = VerTable.size();
5088 for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) {
5089 OS << " " << format_hex_no_prefix(VersymRow, 3) << ":";
5090 for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) {
5091 unsigned Ndx = VerTable[VersymRow + I].vs_index;
5092 OS << format("%4x%c", Ndx & VERSYM_VERSION,
5093 Ndx & VERSYM_HIDDEN ? 'h' : ' ');
5094 OS << left_justify("(" + std::string(Versions[VersymRow + I]) + ")", 13);
5096 OS << '\n';
5098 OS << '\n';
5101 static std::string versionFlagToString(unsigned Flags) {
5102 if (Flags == 0)
5103 return "none";
5105 std::string Ret;
5106 auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) {
5107 if (!(Flags & Flag))
5108 return;
5109 if (!Ret.empty())
5110 Ret += " | ";
5111 Ret += Name;
5112 Flags &= ~Flag;
5115 AddFlag(VER_FLG_BASE, "BASE");
5116 AddFlag(VER_FLG_WEAK, "WEAK");
5117 AddFlag(VER_FLG_INFO, "INFO");
5118 AddFlag(~0, "<unknown>");
5119 return Ret;
5122 template <class ELFT>
5123 void GNUELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
5124 if (!Sec)
5125 return;
5127 printGNUVersionSectionProlog(*Sec, "Version definition", Sec->sh_info);
5129 Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
5130 if (!V) {
5131 this->reportUniqueWarning(V.takeError());
5132 return;
5135 for (const VerDef &Def : *V) {
5136 OS << format(" 0x%04x: Rev: %u Flags: %s Index: %u Cnt: %u Name: %s\n",
5137 Def.Offset, Def.Version,
5138 versionFlagToString(Def.Flags).c_str(), Def.Ndx, Def.Cnt,
5139 Def.Name.data());
5140 unsigned I = 0;
5141 for (const VerdAux &Aux : Def.AuxV)
5142 OS << format(" 0x%04x: Parent %u: %s\n", Aux.Offset, ++I,
5143 Aux.Name.data());
5146 OS << '\n';
5149 template <class ELFT>
5150 void GNUELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
5151 if (!Sec)
5152 return;
5154 unsigned VerneedNum = Sec->sh_info;
5155 printGNUVersionSectionProlog(*Sec, "Version needs", VerneedNum);
5157 Expected<std::vector<VerNeed>> V =
5158 this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
5159 if (!V) {
5160 this->reportUniqueWarning(V.takeError());
5161 return;
5164 for (const VerNeed &VN : *V) {
5165 OS << format(" 0x%04x: Version: %u File: %s Cnt: %u\n", VN.Offset,
5166 VN.Version, VN.File.data(), VN.Cnt);
5167 for (const VernAux &Aux : VN.AuxV)
5168 OS << format(" 0x%04x: Name: %s Flags: %s Version: %u\n", Aux.Offset,
5169 Aux.Name.data(), versionFlagToString(Aux.Flags).c_str(),
5170 Aux.Other);
5172 OS << '\n';
5175 template <class ELFT>
5176 void GNUELFDumper<ELFT>::printHashHistogramStats(size_t NBucket,
5177 size_t MaxChain,
5178 size_t TotalSyms,
5179 ArrayRef<size_t> Count,
5180 bool IsGnu) const {
5181 size_t CumulativeNonZero = 0;
5182 OS << "Histogram for" << (IsGnu ? " `.gnu.hash'" : "")
5183 << " bucket list length (total of " << NBucket << " buckets)\n"
5184 << " Length Number % of total Coverage\n";
5185 for (size_t I = 0; I < MaxChain; ++I) {
5186 CumulativeNonZero += Count[I] * I;
5187 OS << format("%7lu %-10lu (%5.1f%%) %5.1f%%\n", I, Count[I],
5188 (Count[I] * 100.0) / NBucket,
5189 (CumulativeNonZero * 100.0) / TotalSyms);
5193 template <class ELFT> void GNUELFDumper<ELFT>::printCGProfile() {
5194 OS << "GNUStyle::printCGProfile not implemented\n";
5197 template <class ELFT>
5198 void GNUELFDumper<ELFT>::printBBAddrMaps(bool /*PrettyPGOAnalysis*/) {
5199 OS << "GNUStyle::printBBAddrMaps not implemented\n";
5202 static Expected<std::vector<uint64_t>> toULEB128Array(ArrayRef<uint8_t> Data) {
5203 std::vector<uint64_t> Ret;
5204 const uint8_t *Cur = Data.begin();
5205 const uint8_t *End = Data.end();
5206 while (Cur != End) {
5207 unsigned Size;
5208 const char *Err = nullptr;
5209 Ret.push_back(decodeULEB128(Cur, &Size, End, &Err));
5210 if (Err)
5211 return createError(Err);
5212 Cur += Size;
5214 return Ret;
5217 template <class ELFT>
5218 static Expected<std::vector<uint64_t>>
5219 decodeAddrsigSection(const ELFFile<ELFT> &Obj, const typename ELFT::Shdr &Sec) {
5220 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Sec);
5221 if (!ContentsOrErr)
5222 return ContentsOrErr.takeError();
5224 if (Expected<std::vector<uint64_t>> SymsOrErr =
5225 toULEB128Array(*ContentsOrErr))
5226 return *SymsOrErr;
5227 else
5228 return createError("unable to decode " + describe(Obj, Sec) + ": " +
5229 toString(SymsOrErr.takeError()));
5232 template <class ELFT> void GNUELFDumper<ELFT>::printAddrsig() {
5233 if (!this->DotAddrsigSec)
5234 return;
5236 Expected<std::vector<uint64_t>> SymsOrErr =
5237 decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
5238 if (!SymsOrErr) {
5239 this->reportUniqueWarning(SymsOrErr.takeError());
5240 return;
5243 StringRef Name = this->getPrintableSectionName(*this->DotAddrsigSec);
5244 OS << "\nAddress-significant symbols section '" << Name << "'"
5245 << " contains " << SymsOrErr->size() << " entries:\n";
5246 OS << " Num: Name\n";
5248 Field Fields[2] = {0, 8};
5249 size_t SymIndex = 0;
5250 for (uint64_t Sym : *SymsOrErr) {
5251 Fields[0].Str = to_string(format_decimal(++SymIndex, 6)) + ":";
5252 Fields[1].Str = this->getStaticSymbolName(Sym);
5253 for (const Field &Entry : Fields)
5254 printField(Entry);
5255 OS << "\n";
5259 template <class ELFT>
5260 static bool printAArch64PAuthABICoreInfo(raw_ostream &OS, uint32_t DataSize,
5261 ArrayRef<uint8_t> Desc) {
5262 OS << " AArch64 PAuth ABI core info: ";
5263 // DataSize - size without padding, Desc.size() - size with padding
5264 if (DataSize != 16) {
5265 OS << format("<corrupted size: expected 16, got %d>", DataSize);
5266 return false;
5269 uint64_t Platform =
5270 support::endian::read64<ELFT::Endianness>(Desc.data() + 0);
5271 uint64_t Version = support::endian::read64<ELFT::Endianness>(Desc.data() + 8);
5273 const char *PlatformDesc = [Platform]() {
5274 switch (Platform) {
5275 case AARCH64_PAUTH_PLATFORM_INVALID:
5276 return "invalid";
5277 case AARCH64_PAUTH_PLATFORM_BAREMETAL:
5278 return "baremetal";
5279 case AARCH64_PAUTH_PLATFORM_LLVM_LINUX:
5280 return "llvm_linux";
5281 default:
5282 return "unknown";
5284 }();
5286 std::string VersionDesc = [Platform, Version]() -> std::string {
5287 if (Platform != AARCH64_PAUTH_PLATFORM_LLVM_LINUX)
5288 return "";
5289 if (Version >= (1 << (AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST + 1)))
5290 return "unknown";
5292 std::array<StringRef, AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST + 1>
5293 Flags;
5294 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS] = "Intrinsics";
5295 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS] = "Calls";
5296 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS] = "Returns";
5297 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS] = "AuthTraps";
5298 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR] =
5299 "VTPtrAddressDiscrimination";
5300 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR] =
5301 "VTPtrTypeDiscrimination";
5302 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI] = "InitFini";
5303 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC] =
5304 "InitFiniAddressDiscrimination";
5305 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT] = "ELFGOT";
5306 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS] = "IndirectGotos";
5307 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR] =
5308 "TypeInfoVTPtrDiscrimination";
5309 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR] =
5310 "FPtrTypeDiscrimination";
5312 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
5313 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
5314 "Update when new enum items are defined");
5316 std::string Desc;
5317 for (uint32_t I = 0, End = Flags.size(); I < End; ++I) {
5318 if (!(Version & (1ULL << I)))
5319 Desc += '!';
5320 Desc +=
5321 Twine("PointerAuth" + Flags[I] + (I == End - 1 ? "" : ", ")).str();
5323 return Desc;
5324 }();
5326 OS << format("platform 0x%" PRIx64 " (%s), version 0x%" PRIx64, Platform,
5327 PlatformDesc, Version);
5328 if (!VersionDesc.empty())
5329 OS << format(" (%s)", VersionDesc.c_str());
5331 return true;
5334 template <typename ELFT>
5335 static std::string getGNUProperty(uint32_t Type, uint32_t DataSize,
5336 ArrayRef<uint8_t> Data) {
5337 std::string str;
5338 raw_string_ostream OS(str);
5339 uint32_t PrData;
5340 auto DumpBit = [&](uint32_t Flag, StringRef Name) {
5341 if (PrData & Flag) {
5342 PrData &= ~Flag;
5343 OS << Name;
5344 if (PrData)
5345 OS << ", ";
5349 switch (Type) {
5350 default:
5351 OS << format("<application-specific type 0x%x>", Type);
5352 return str;
5353 case GNU_PROPERTY_STACK_SIZE: {
5354 OS << "stack size: ";
5355 if (DataSize == sizeof(typename ELFT::uint))
5356 OS << formatv("{0:x}",
5357 (uint64_t)(*(const typename ELFT::Addr *)Data.data()));
5358 else
5359 OS << format("<corrupt length: 0x%x>", DataSize);
5360 return str;
5362 case GNU_PROPERTY_NO_COPY_ON_PROTECTED:
5363 OS << "no copy on protected";
5364 if (DataSize)
5365 OS << format(" <corrupt length: 0x%x>", DataSize);
5366 return str;
5367 case GNU_PROPERTY_AARCH64_FEATURE_1_AND:
5368 case GNU_PROPERTY_X86_FEATURE_1_AND:
5369 OS << ((Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) ? "aarch64 feature: "
5370 : "x86 feature: ");
5371 if (DataSize != 4) {
5372 OS << format("<corrupt length: 0x%x>", DataSize);
5373 return str;
5375 PrData = endian::read32<ELFT::Endianness>(Data.data());
5376 if (PrData == 0) {
5377 OS << "<None>";
5378 return str;
5380 if (Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) {
5381 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI, "BTI");
5382 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC, "PAC");
5383 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_GCS, "GCS");
5384 } else {
5385 DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT, "IBT");
5386 DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK, "SHSTK");
5388 if (PrData)
5389 OS << format("<unknown flags: 0x%x>", PrData);
5390 return str;
5391 case GNU_PROPERTY_AARCH64_FEATURE_PAUTH:
5392 printAArch64PAuthABICoreInfo<ELFT>(OS, DataSize, Data);
5393 return str;
5394 case GNU_PROPERTY_X86_FEATURE_2_NEEDED:
5395 case GNU_PROPERTY_X86_FEATURE_2_USED:
5396 OS << "x86 feature "
5397 << (Type == GNU_PROPERTY_X86_FEATURE_2_NEEDED ? "needed: " : "used: ");
5398 if (DataSize != 4) {
5399 OS << format("<corrupt length: 0x%x>", DataSize);
5400 return str;
5402 PrData = endian::read32<ELFT::Endianness>(Data.data());
5403 if (PrData == 0) {
5404 OS << "<None>";
5405 return str;
5407 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86, "x86");
5408 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87, "x87");
5409 DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX, "MMX");
5410 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM, "XMM");
5411 DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM, "YMM");
5412 DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM, "ZMM");
5413 DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR, "FXSR");
5414 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE, "XSAVE");
5415 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT, "XSAVEOPT");
5416 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC, "XSAVEC");
5417 if (PrData)
5418 OS << format("<unknown flags: 0x%x>", PrData);
5419 return str;
5420 case GNU_PROPERTY_X86_ISA_1_NEEDED:
5421 case GNU_PROPERTY_X86_ISA_1_USED:
5422 OS << "x86 ISA "
5423 << (Type == GNU_PROPERTY_X86_ISA_1_NEEDED ? "needed: " : "used: ");
5424 if (DataSize != 4) {
5425 OS << format("<corrupt length: 0x%x>", DataSize);
5426 return str;
5428 PrData = endian::read32<ELFT::Endianness>(Data.data());
5429 if (PrData == 0) {
5430 OS << "<None>";
5431 return str;
5433 DumpBit(GNU_PROPERTY_X86_ISA_1_BASELINE, "x86-64-baseline");
5434 DumpBit(GNU_PROPERTY_X86_ISA_1_V2, "x86-64-v2");
5435 DumpBit(GNU_PROPERTY_X86_ISA_1_V3, "x86-64-v3");
5436 DumpBit(GNU_PROPERTY_X86_ISA_1_V4, "x86-64-v4");
5437 if (PrData)
5438 OS << format("<unknown flags: 0x%x>", PrData);
5439 return str;
5443 template <typename ELFT>
5444 static SmallVector<std::string, 4> getGNUPropertyList(ArrayRef<uint8_t> Arr) {
5445 using Elf_Word = typename ELFT::Word;
5447 SmallVector<std::string, 4> Properties;
5448 while (Arr.size() >= 8) {
5449 uint32_t Type = *reinterpret_cast<const Elf_Word *>(Arr.data());
5450 uint32_t DataSize = *reinterpret_cast<const Elf_Word *>(Arr.data() + 4);
5451 Arr = Arr.drop_front(8);
5453 // Take padding size into account if present.
5454 uint64_t PaddedSize = alignTo(DataSize, sizeof(typename ELFT::uint));
5455 std::string str;
5456 raw_string_ostream OS(str);
5457 if (Arr.size() < PaddedSize) {
5458 OS << format("<corrupt type (0x%x) datasz: 0x%x>", Type, DataSize);
5459 Properties.push_back(str);
5460 break;
5462 Properties.push_back(
5463 getGNUProperty<ELFT>(Type, DataSize, Arr.take_front(PaddedSize)));
5464 Arr = Arr.drop_front(PaddedSize);
5467 if (!Arr.empty())
5468 Properties.push_back("<corrupted GNU_PROPERTY_TYPE_0>");
5470 return Properties;
5473 struct GNUAbiTag {
5474 std::string OSName;
5475 std::string ABI;
5476 bool IsValid;
5479 template <typename ELFT> static GNUAbiTag getGNUAbiTag(ArrayRef<uint8_t> Desc) {
5480 typedef typename ELFT::Word Elf_Word;
5482 ArrayRef<Elf_Word> Words(reinterpret_cast<const Elf_Word *>(Desc.begin()),
5483 reinterpret_cast<const Elf_Word *>(Desc.end()));
5485 if (Words.size() < 4)
5486 return {"", "", /*IsValid=*/false};
5488 static const char *OSNames[] = {
5489 "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable", "NaCl",
5491 StringRef OSName = "Unknown";
5492 if (Words[0] < std::size(OSNames))
5493 OSName = OSNames[Words[0]];
5494 uint32_t Major = Words[1], Minor = Words[2], Patch = Words[3];
5495 std::string str;
5496 raw_string_ostream ABI(str);
5497 ABI << Major << "." << Minor << "." << Patch;
5498 return {std::string(OSName), str, /*IsValid=*/true};
5501 static std::string getGNUBuildId(ArrayRef<uint8_t> Desc) {
5502 std::string str;
5503 raw_string_ostream OS(str);
5504 for (uint8_t B : Desc)
5505 OS << format_hex_no_prefix(B, 2);
5506 return str;
5509 static StringRef getDescAsStringRef(ArrayRef<uint8_t> Desc) {
5510 return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
5513 template <typename ELFT>
5514 static bool printGNUNote(raw_ostream &OS, uint32_t NoteType,
5515 ArrayRef<uint8_t> Desc) {
5516 // Return true if we were able to pretty-print the note, false otherwise.
5517 switch (NoteType) {
5518 default:
5519 return false;
5520 case ELF::NT_GNU_ABI_TAG: {
5521 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
5522 if (!AbiTag.IsValid)
5523 OS << " <corrupt GNU_ABI_TAG>";
5524 else
5525 OS << " OS: " << AbiTag.OSName << ", ABI: " << AbiTag.ABI;
5526 break;
5528 case ELF::NT_GNU_BUILD_ID: {
5529 OS << " Build ID: " << getGNUBuildId(Desc);
5530 break;
5532 case ELF::NT_GNU_GOLD_VERSION:
5533 OS << " Version: " << getDescAsStringRef(Desc);
5534 break;
5535 case ELF::NT_GNU_PROPERTY_TYPE_0:
5536 OS << " Properties:";
5537 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
5538 OS << " " << Property << "\n";
5539 break;
5541 OS << '\n';
5542 return true;
5545 using AndroidNoteProperties = std::vector<std::pair<StringRef, std::string>>;
5546 static AndroidNoteProperties getAndroidNoteProperties(uint32_t NoteType,
5547 ArrayRef<uint8_t> Desc) {
5548 AndroidNoteProperties Props;
5549 switch (NoteType) {
5550 case ELF::NT_ANDROID_TYPE_MEMTAG:
5551 if (Desc.empty()) {
5552 Props.emplace_back("Invalid .note.android.memtag", "");
5553 return Props;
5556 switch (Desc[0] & NT_MEMTAG_LEVEL_MASK) {
5557 case NT_MEMTAG_LEVEL_NONE:
5558 Props.emplace_back("Tagging Mode", "NONE");
5559 break;
5560 case NT_MEMTAG_LEVEL_ASYNC:
5561 Props.emplace_back("Tagging Mode", "ASYNC");
5562 break;
5563 case NT_MEMTAG_LEVEL_SYNC:
5564 Props.emplace_back("Tagging Mode", "SYNC");
5565 break;
5566 default:
5567 Props.emplace_back(
5568 "Tagging Mode",
5569 ("Unknown (" + Twine::utohexstr(Desc[0] & NT_MEMTAG_LEVEL_MASK) + ")")
5570 .str());
5571 break;
5573 Props.emplace_back("Heap",
5574 (Desc[0] & NT_MEMTAG_HEAP) ? "Enabled" : "Disabled");
5575 Props.emplace_back("Stack",
5576 (Desc[0] & NT_MEMTAG_STACK) ? "Enabled" : "Disabled");
5577 break;
5578 default:
5579 return Props;
5581 return Props;
5584 static bool printAndroidNote(raw_ostream &OS, uint32_t NoteType,
5585 ArrayRef<uint8_t> Desc) {
5586 // Return true if we were able to pretty-print the note, false otherwise.
5587 AndroidNoteProperties Props = getAndroidNoteProperties(NoteType, Desc);
5588 if (Props.empty())
5589 return false;
5590 for (const auto &KV : Props)
5591 OS << " " << KV.first << ": " << KV.second << '\n';
5592 return true;
5595 template <class ELFT>
5596 void GNUELFDumper<ELFT>::printMemtag(
5597 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
5598 const ArrayRef<uint8_t> AndroidNoteDesc,
5599 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) {
5600 OS << "Memtag Dynamic Entries:\n";
5601 if (DynamicEntries.empty())
5602 OS << " < none found >\n";
5603 for (const auto &DynamicEntryKV : DynamicEntries)
5604 OS << " " << DynamicEntryKV.first << ": " << DynamicEntryKV.second
5605 << "\n";
5607 if (!AndroidNoteDesc.empty()) {
5608 OS << "Memtag Android Note:\n";
5609 printAndroidNote(OS, ELF::NT_ANDROID_TYPE_MEMTAG, AndroidNoteDesc);
5612 if (Descriptors.empty())
5613 return;
5615 OS << "Memtag Global Descriptors:\n";
5616 for (const auto &[Addr, BytesToTag] : Descriptors) {
5617 OS << " 0x" << utohexstr(Addr, /*LowerCase=*/true) << ": 0x"
5618 << utohexstr(BytesToTag, /*LowerCase=*/true) << "\n";
5622 template <typename ELFT>
5623 static bool printLLVMOMPOFFLOADNote(raw_ostream &OS, uint32_t NoteType,
5624 ArrayRef<uint8_t> Desc) {
5625 switch (NoteType) {
5626 default:
5627 return false;
5628 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
5629 OS << " Version: " << getDescAsStringRef(Desc);
5630 break;
5631 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
5632 OS << " Producer: " << getDescAsStringRef(Desc);
5633 break;
5634 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
5635 OS << " Producer version: " << getDescAsStringRef(Desc);
5636 break;
5638 OS << '\n';
5639 return true;
5642 const EnumEntry<unsigned> FreeBSDFeatureCtlFlags[] = {
5643 {"ASLR_DISABLE", NT_FREEBSD_FCTL_ASLR_DISABLE},
5644 {"PROTMAX_DISABLE", NT_FREEBSD_FCTL_PROTMAX_DISABLE},
5645 {"STKGAP_DISABLE", NT_FREEBSD_FCTL_STKGAP_DISABLE},
5646 {"WXNEEDED", NT_FREEBSD_FCTL_WXNEEDED},
5647 {"LA48", NT_FREEBSD_FCTL_LA48},
5648 {"ASG_DISABLE", NT_FREEBSD_FCTL_ASG_DISABLE},
5651 struct FreeBSDNote {
5652 std::string Type;
5653 std::string Value;
5656 template <typename ELFT>
5657 static std::optional<FreeBSDNote>
5658 getFreeBSDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc, bool IsCore) {
5659 if (IsCore)
5660 return std::nullopt; // No pretty-printing yet.
5661 switch (NoteType) {
5662 case ELF::NT_FREEBSD_ABI_TAG:
5663 if (Desc.size() != 4)
5664 return std::nullopt;
5665 return FreeBSDNote{"ABI tag",
5666 utostr(endian::read32<ELFT::Endianness>(Desc.data()))};
5667 case ELF::NT_FREEBSD_ARCH_TAG:
5668 return FreeBSDNote{"Arch tag", toStringRef(Desc).str()};
5669 case ELF::NT_FREEBSD_FEATURE_CTL: {
5670 if (Desc.size() != 4)
5671 return std::nullopt;
5672 unsigned Value = endian::read32<ELFT::Endianness>(Desc.data());
5673 std::string FlagsStr;
5674 raw_string_ostream OS(FlagsStr);
5675 printFlags(Value, ArrayRef(FreeBSDFeatureCtlFlags), OS);
5676 if (FlagsStr.empty())
5677 OS << "0x" << utohexstr(Value);
5678 else
5679 OS << "(0x" << utohexstr(Value) << ")";
5680 return FreeBSDNote{"Feature flags", FlagsStr};
5682 default:
5683 return std::nullopt;
5687 struct AMDNote {
5688 std::string Type;
5689 std::string Value;
5692 template <typename ELFT>
5693 static AMDNote getAMDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
5694 switch (NoteType) {
5695 default:
5696 return {"", ""};
5697 case ELF::NT_AMD_HSA_CODE_OBJECT_VERSION: {
5698 struct CodeObjectVersion {
5699 support::aligned_ulittle32_t MajorVersion;
5700 support::aligned_ulittle32_t MinorVersion;
5702 if (Desc.size() != sizeof(CodeObjectVersion))
5703 return {"AMD HSA Code Object Version",
5704 "Invalid AMD HSA Code Object Version"};
5705 std::string VersionString;
5706 raw_string_ostream StrOS(VersionString);
5707 auto Version = reinterpret_cast<const CodeObjectVersion *>(Desc.data());
5708 StrOS << "[Major: " << Version->MajorVersion
5709 << ", Minor: " << Version->MinorVersion << "]";
5710 return {"AMD HSA Code Object Version", VersionString};
5712 case ELF::NT_AMD_HSA_HSAIL: {
5713 struct HSAILProperties {
5714 support::aligned_ulittle32_t HSAILMajorVersion;
5715 support::aligned_ulittle32_t HSAILMinorVersion;
5716 uint8_t Profile;
5717 uint8_t MachineModel;
5718 uint8_t DefaultFloatRound;
5720 if (Desc.size() != sizeof(HSAILProperties))
5721 return {"AMD HSA HSAIL Properties", "Invalid AMD HSA HSAIL Properties"};
5722 auto Properties = reinterpret_cast<const HSAILProperties *>(Desc.data());
5723 std::string HSAILPropetiesString;
5724 raw_string_ostream StrOS(HSAILPropetiesString);
5725 StrOS << "[HSAIL Major: " << Properties->HSAILMajorVersion
5726 << ", HSAIL Minor: " << Properties->HSAILMinorVersion
5727 << ", Profile: " << uint32_t(Properties->Profile)
5728 << ", Machine Model: " << uint32_t(Properties->MachineModel)
5729 << ", Default Float Round: "
5730 << uint32_t(Properties->DefaultFloatRound) << "]";
5731 return {"AMD HSA HSAIL Properties", HSAILPropetiesString};
5733 case ELF::NT_AMD_HSA_ISA_VERSION: {
5734 struct IsaVersion {
5735 support::aligned_ulittle16_t VendorNameSize;
5736 support::aligned_ulittle16_t ArchitectureNameSize;
5737 support::aligned_ulittle32_t Major;
5738 support::aligned_ulittle32_t Minor;
5739 support::aligned_ulittle32_t Stepping;
5741 if (Desc.size() < sizeof(IsaVersion))
5742 return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"};
5743 auto Isa = reinterpret_cast<const IsaVersion *>(Desc.data());
5744 if (Desc.size() < sizeof(IsaVersion) +
5745 Isa->VendorNameSize + Isa->ArchitectureNameSize ||
5746 Isa->VendorNameSize == 0 || Isa->ArchitectureNameSize == 0)
5747 return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"};
5748 std::string IsaString;
5749 raw_string_ostream StrOS(IsaString);
5750 StrOS << "[Vendor: "
5751 << StringRef((const char*)Desc.data() + sizeof(IsaVersion), Isa->VendorNameSize - 1)
5752 << ", Architecture: "
5753 << StringRef((const char*)Desc.data() + sizeof(IsaVersion) + Isa->VendorNameSize,
5754 Isa->ArchitectureNameSize - 1)
5755 << ", Major: " << Isa->Major << ", Minor: " << Isa->Minor
5756 << ", Stepping: " << Isa->Stepping << "]";
5757 return {"AMD HSA ISA Version", IsaString};
5759 case ELF::NT_AMD_HSA_METADATA: {
5760 if (Desc.size() == 0)
5761 return {"AMD HSA Metadata", ""};
5762 return {
5763 "AMD HSA Metadata",
5764 std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size() - 1)};
5766 case ELF::NT_AMD_HSA_ISA_NAME: {
5767 if (Desc.size() == 0)
5768 return {"AMD HSA ISA Name", ""};
5769 return {
5770 "AMD HSA ISA Name",
5771 std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
5773 case ELF::NT_AMD_PAL_METADATA: {
5774 struct PALMetadata {
5775 support::aligned_ulittle32_t Key;
5776 support::aligned_ulittle32_t Value;
5778 if (Desc.size() % sizeof(PALMetadata) != 0)
5779 return {"AMD PAL Metadata", "Invalid AMD PAL Metadata"};
5780 auto Isa = reinterpret_cast<const PALMetadata *>(Desc.data());
5781 std::string MetadataString;
5782 raw_string_ostream StrOS(MetadataString);
5783 for (size_t I = 0, E = Desc.size() / sizeof(PALMetadata); I < E; ++I) {
5784 StrOS << "[" << Isa[I].Key << ": " << Isa[I].Value << "]";
5786 return {"AMD PAL Metadata", MetadataString};
5791 struct AMDGPUNote {
5792 std::string Type;
5793 std::string Value;
5796 template <typename ELFT>
5797 static AMDGPUNote getAMDGPUNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
5798 switch (NoteType) {
5799 default:
5800 return {"", ""};
5801 case ELF::NT_AMDGPU_METADATA: {
5802 StringRef MsgPackString =
5803 StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
5804 msgpack::Document MsgPackDoc;
5805 if (!MsgPackDoc.readFromBlob(MsgPackString, /*Multi=*/false))
5806 return {"", ""};
5808 std::string MetadataString;
5810 // FIXME: Metadata Verifier only works with AMDHSA.
5811 // This is an ugly workaround to avoid the verifier for other MD
5812 // formats (e.g. amdpal)
5813 if (MsgPackString.contains("amdhsa.")) {
5814 AMDGPU::HSAMD::V3::MetadataVerifier Verifier(true);
5815 if (!Verifier.verify(MsgPackDoc.getRoot()))
5816 MetadataString = "Invalid AMDGPU Metadata\n";
5819 raw_string_ostream StrOS(MetadataString);
5820 if (MsgPackDoc.getRoot().isScalar()) {
5821 // TODO: passing a scalar root to toYAML() asserts:
5822 // (PolymorphicTraits<T>::getKind(Val) != NodeKind::Scalar &&
5823 // "plain scalar documents are not supported")
5824 // To avoid this crash we print the raw data instead.
5825 return {"", ""};
5827 MsgPackDoc.toYAML(StrOS);
5828 return {"AMDGPU Metadata", MetadataString};
5833 struct CoreFileMapping {
5834 uint64_t Start, End, Offset;
5835 StringRef Filename;
5838 struct CoreNote {
5839 uint64_t PageSize;
5840 std::vector<CoreFileMapping> Mappings;
5843 static Expected<CoreNote> readCoreNote(DataExtractor Desc) {
5844 // Expected format of the NT_FILE note description:
5845 // 1. # of file mappings (call it N)
5846 // 2. Page size
5847 // 3. N (start, end, offset) triples
5848 // 4. N packed filenames (null delimited)
5849 // Each field is an Elf_Addr, except for filenames which are char* strings.
5851 CoreNote Ret;
5852 const int Bytes = Desc.getAddressSize();
5854 if (!Desc.isValidOffsetForAddress(2))
5855 return createError("the note of size 0x" + Twine::utohexstr(Desc.size()) +
5856 " is too short, expected at least 0x" +
5857 Twine::utohexstr(Bytes * 2));
5858 if (Desc.getData().back() != 0)
5859 return createError("the note is not NUL terminated");
5861 uint64_t DescOffset = 0;
5862 uint64_t FileCount = Desc.getAddress(&DescOffset);
5863 Ret.PageSize = Desc.getAddress(&DescOffset);
5865 if (!Desc.isValidOffsetForAddress(3 * FileCount * Bytes))
5866 return createError("unable to read file mappings (found " +
5867 Twine(FileCount) + "): the note of size 0x" +
5868 Twine::utohexstr(Desc.size()) + " is too short");
5870 uint64_t FilenamesOffset = 0;
5871 DataExtractor Filenames(
5872 Desc.getData().drop_front(DescOffset + 3 * FileCount * Bytes),
5873 Desc.isLittleEndian(), Desc.getAddressSize());
5875 Ret.Mappings.resize(FileCount);
5876 size_t I = 0;
5877 for (CoreFileMapping &Mapping : Ret.Mappings) {
5878 ++I;
5879 if (!Filenames.isValidOffsetForDataOfSize(FilenamesOffset, 1))
5880 return createError(
5881 "unable to read the file name for the mapping with index " +
5882 Twine(I) + ": the note of size 0x" + Twine::utohexstr(Desc.size()) +
5883 " is truncated");
5884 Mapping.Start = Desc.getAddress(&DescOffset);
5885 Mapping.End = Desc.getAddress(&DescOffset);
5886 Mapping.Offset = Desc.getAddress(&DescOffset);
5887 Mapping.Filename = Filenames.getCStrRef(&FilenamesOffset);
5890 return Ret;
5893 template <typename ELFT>
5894 static void printCoreNote(raw_ostream &OS, const CoreNote &Note) {
5895 // Length of "0x<address>" string.
5896 const int FieldWidth = ELFT::Is64Bits ? 18 : 10;
5898 OS << " Page size: " << format_decimal(Note.PageSize, 0) << '\n';
5899 OS << " " << right_justify("Start", FieldWidth) << " "
5900 << right_justify("End", FieldWidth) << " "
5901 << right_justify("Page Offset", FieldWidth) << '\n';
5902 for (const CoreFileMapping &Mapping : Note.Mappings) {
5903 OS << " " << format_hex(Mapping.Start, FieldWidth) << " "
5904 << format_hex(Mapping.End, FieldWidth) << " "
5905 << format_hex(Mapping.Offset, FieldWidth) << "\n "
5906 << Mapping.Filename << '\n';
5910 const NoteType GenericNoteTypes[] = {
5911 {ELF::NT_VERSION, "NT_VERSION (version)"},
5912 {ELF::NT_ARCH, "NT_ARCH (architecture)"},
5913 {ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN, "OPEN"},
5914 {ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC, "func"},
5917 const NoteType GNUNoteTypes[] = {
5918 {ELF::NT_GNU_ABI_TAG, "NT_GNU_ABI_TAG (ABI version tag)"},
5919 {ELF::NT_GNU_HWCAP, "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"},
5920 {ELF::NT_GNU_BUILD_ID, "NT_GNU_BUILD_ID (unique build ID bitstring)"},
5921 {ELF::NT_GNU_GOLD_VERSION, "NT_GNU_GOLD_VERSION (gold version)"},
5922 {ELF::NT_GNU_PROPERTY_TYPE_0, "NT_GNU_PROPERTY_TYPE_0 (property note)"},
5925 const NoteType FreeBSDCoreNoteTypes[] = {
5926 {ELF::NT_FREEBSD_THRMISC, "NT_THRMISC (thrmisc structure)"},
5927 {ELF::NT_FREEBSD_PROCSTAT_PROC, "NT_PROCSTAT_PROC (proc data)"},
5928 {ELF::NT_FREEBSD_PROCSTAT_FILES, "NT_PROCSTAT_FILES (files data)"},
5929 {ELF::NT_FREEBSD_PROCSTAT_VMMAP, "NT_PROCSTAT_VMMAP (vmmap data)"},
5930 {ELF::NT_FREEBSD_PROCSTAT_GROUPS, "NT_PROCSTAT_GROUPS (groups data)"},
5931 {ELF::NT_FREEBSD_PROCSTAT_UMASK, "NT_PROCSTAT_UMASK (umask data)"},
5932 {ELF::NT_FREEBSD_PROCSTAT_RLIMIT, "NT_PROCSTAT_RLIMIT (rlimit data)"},
5933 {ELF::NT_FREEBSD_PROCSTAT_OSREL, "NT_PROCSTAT_OSREL (osreldate data)"},
5934 {ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS,
5935 "NT_PROCSTAT_PSSTRINGS (ps_strings data)"},
5936 {ELF::NT_FREEBSD_PROCSTAT_AUXV, "NT_PROCSTAT_AUXV (auxv data)"},
5939 const NoteType FreeBSDNoteTypes[] = {
5940 {ELF::NT_FREEBSD_ABI_TAG, "NT_FREEBSD_ABI_TAG (ABI version tag)"},
5941 {ELF::NT_FREEBSD_NOINIT_TAG, "NT_FREEBSD_NOINIT_TAG (no .init tag)"},
5942 {ELF::NT_FREEBSD_ARCH_TAG, "NT_FREEBSD_ARCH_TAG (architecture tag)"},
5943 {ELF::NT_FREEBSD_FEATURE_CTL,
5944 "NT_FREEBSD_FEATURE_CTL (FreeBSD feature control)"},
5947 const NoteType NetBSDCoreNoteTypes[] = {
5948 {ELF::NT_NETBSDCORE_PROCINFO,
5949 "NT_NETBSDCORE_PROCINFO (procinfo structure)"},
5950 {ELF::NT_NETBSDCORE_AUXV, "NT_NETBSDCORE_AUXV (ELF auxiliary vector data)"},
5951 {ELF::NT_NETBSDCORE_LWPSTATUS, "PT_LWPSTATUS (ptrace_lwpstatus structure)"},
5954 const NoteType OpenBSDCoreNoteTypes[] = {
5955 {ELF::NT_OPENBSD_PROCINFO, "NT_OPENBSD_PROCINFO (procinfo structure)"},
5956 {ELF::NT_OPENBSD_AUXV, "NT_OPENBSD_AUXV (ELF auxiliary vector data)"},
5957 {ELF::NT_OPENBSD_REGS, "NT_OPENBSD_REGS (regular registers)"},
5958 {ELF::NT_OPENBSD_FPREGS, "NT_OPENBSD_FPREGS (floating point registers)"},
5959 {ELF::NT_OPENBSD_WCOOKIE, "NT_OPENBSD_WCOOKIE (window cookie)"},
5962 const NoteType AMDNoteTypes[] = {
5963 {ELF::NT_AMD_HSA_CODE_OBJECT_VERSION,
5964 "NT_AMD_HSA_CODE_OBJECT_VERSION (AMD HSA Code Object Version)"},
5965 {ELF::NT_AMD_HSA_HSAIL, "NT_AMD_HSA_HSAIL (AMD HSA HSAIL Properties)"},
5966 {ELF::NT_AMD_HSA_ISA_VERSION, "NT_AMD_HSA_ISA_VERSION (AMD HSA ISA Version)"},
5967 {ELF::NT_AMD_HSA_METADATA, "NT_AMD_HSA_METADATA (AMD HSA Metadata)"},
5968 {ELF::NT_AMD_HSA_ISA_NAME, "NT_AMD_HSA_ISA_NAME (AMD HSA ISA Name)"},
5969 {ELF::NT_AMD_PAL_METADATA, "NT_AMD_PAL_METADATA (AMD PAL Metadata)"},
5972 const NoteType AMDGPUNoteTypes[] = {
5973 {ELF::NT_AMDGPU_METADATA, "NT_AMDGPU_METADATA (AMDGPU Metadata)"},
5976 const NoteType LLVMOMPOFFLOADNoteTypes[] = {
5977 {ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION,
5978 "NT_LLVM_OPENMP_OFFLOAD_VERSION (image format version)"},
5979 {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER,
5980 "NT_LLVM_OPENMP_OFFLOAD_PRODUCER (producing toolchain)"},
5981 {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION,
5982 "NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION (producing toolchain version)"},
5985 const NoteType AndroidNoteTypes[] = {
5986 {ELF::NT_ANDROID_TYPE_IDENT, "NT_ANDROID_TYPE_IDENT"},
5987 {ELF::NT_ANDROID_TYPE_KUSER, "NT_ANDROID_TYPE_KUSER"},
5988 {ELF::NT_ANDROID_TYPE_MEMTAG,
5989 "NT_ANDROID_TYPE_MEMTAG (Android memory tagging information)"},
5992 const NoteType CoreNoteTypes[] = {
5993 {ELF::NT_PRSTATUS, "NT_PRSTATUS (prstatus structure)"},
5994 {ELF::NT_FPREGSET, "NT_FPREGSET (floating point registers)"},
5995 {ELF::NT_PRPSINFO, "NT_PRPSINFO (prpsinfo structure)"},
5996 {ELF::NT_TASKSTRUCT, "NT_TASKSTRUCT (task structure)"},
5997 {ELF::NT_AUXV, "NT_AUXV (auxiliary vector)"},
5998 {ELF::NT_PSTATUS, "NT_PSTATUS (pstatus structure)"},
5999 {ELF::NT_FPREGS, "NT_FPREGS (floating point registers)"},
6000 {ELF::NT_PSINFO, "NT_PSINFO (psinfo structure)"},
6001 {ELF::NT_LWPSTATUS, "NT_LWPSTATUS (lwpstatus_t structure)"},
6002 {ELF::NT_LWPSINFO, "NT_LWPSINFO (lwpsinfo_t structure)"},
6003 {ELF::NT_WIN32PSTATUS, "NT_WIN32PSTATUS (win32_pstatus structure)"},
6005 {ELF::NT_PPC_VMX, "NT_PPC_VMX (ppc Altivec registers)"},
6006 {ELF::NT_PPC_VSX, "NT_PPC_VSX (ppc VSX registers)"},
6007 {ELF::NT_PPC_TAR, "NT_PPC_TAR (ppc TAR register)"},
6008 {ELF::NT_PPC_PPR, "NT_PPC_PPR (ppc PPR register)"},
6009 {ELF::NT_PPC_DSCR, "NT_PPC_DSCR (ppc DSCR register)"},
6010 {ELF::NT_PPC_EBB, "NT_PPC_EBB (ppc EBB registers)"},
6011 {ELF::NT_PPC_PMU, "NT_PPC_PMU (ppc PMU registers)"},
6012 {ELF::NT_PPC_TM_CGPR, "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"},
6013 {ELF::NT_PPC_TM_CFPR,
6014 "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"},
6015 {ELF::NT_PPC_TM_CVMX,
6016 "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"},
6017 {ELF::NT_PPC_TM_CVSX, "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"},
6018 {ELF::NT_PPC_TM_SPR, "NT_PPC_TM_SPR (ppc TM special purpose registers)"},
6019 {ELF::NT_PPC_TM_CTAR, "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"},
6020 {ELF::NT_PPC_TM_CPPR, "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"},
6021 {ELF::NT_PPC_TM_CDSCR, "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"},
6023 {ELF::NT_386_TLS, "NT_386_TLS (x86 TLS information)"},
6024 {ELF::NT_386_IOPERM, "NT_386_IOPERM (x86 I/O permissions)"},
6025 {ELF::NT_X86_XSTATE, "NT_X86_XSTATE (x86 XSAVE extended state)"},
6027 {ELF::NT_S390_HIGH_GPRS, "NT_S390_HIGH_GPRS (s390 upper register halves)"},
6028 {ELF::NT_S390_TIMER, "NT_S390_TIMER (s390 timer register)"},
6029 {ELF::NT_S390_TODCMP, "NT_S390_TODCMP (s390 TOD comparator register)"},
6030 {ELF::NT_S390_TODPREG, "NT_S390_TODPREG (s390 TOD programmable register)"},
6031 {ELF::NT_S390_CTRS, "NT_S390_CTRS (s390 control registers)"},
6032 {ELF::NT_S390_PREFIX, "NT_S390_PREFIX (s390 prefix register)"},
6033 {ELF::NT_S390_LAST_BREAK,
6034 "NT_S390_LAST_BREAK (s390 last breaking event address)"},
6035 {ELF::NT_S390_SYSTEM_CALL,
6036 "NT_S390_SYSTEM_CALL (s390 system call restart data)"},
6037 {ELF::NT_S390_TDB, "NT_S390_TDB (s390 transaction diagnostic block)"},
6038 {ELF::NT_S390_VXRS_LOW,
6039 "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"},
6040 {ELF::NT_S390_VXRS_HIGH, "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"},
6041 {ELF::NT_S390_GS_CB, "NT_S390_GS_CB (s390 guarded-storage registers)"},
6042 {ELF::NT_S390_GS_BC,
6043 "NT_S390_GS_BC (s390 guarded-storage broadcast control)"},
6045 {ELF::NT_ARM_VFP, "NT_ARM_VFP (arm VFP registers)"},
6046 {ELF::NT_ARM_TLS, "NT_ARM_TLS (AArch TLS registers)"},
6047 {ELF::NT_ARM_HW_BREAK,
6048 "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"},
6049 {ELF::NT_ARM_HW_WATCH,
6050 "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"},
6051 {ELF::NT_ARM_SVE, "NT_ARM_SVE (AArch64 SVE registers)"},
6052 {ELF::NT_ARM_PAC_MASK,
6053 "NT_ARM_PAC_MASK (AArch64 Pointer Authentication code masks)"},
6054 {ELF::NT_ARM_TAGGED_ADDR_CTRL,
6055 "NT_ARM_TAGGED_ADDR_CTRL (AArch64 Tagged Address Control)"},
6056 {ELF::NT_ARM_SSVE, "NT_ARM_SSVE (AArch64 Streaming SVE registers)"},
6057 {ELF::NT_ARM_ZA, "NT_ARM_ZA (AArch64 SME ZA registers)"},
6058 {ELF::NT_ARM_ZT, "NT_ARM_ZT (AArch64 SME ZT registers)"},
6059 {ELF::NT_ARM_FPMR, "NT_ARM_FPMR (AArch64 Floating Point Mode Register)"},
6061 {ELF::NT_FILE, "NT_FILE (mapped files)"},
6062 {ELF::NT_PRXFPREG, "NT_PRXFPREG (user_xfpregs structure)"},
6063 {ELF::NT_SIGINFO, "NT_SIGINFO (siginfo_t data)"},
6066 template <class ELFT>
6067 StringRef getNoteTypeName(const typename ELFT::Note &Note, unsigned ELFType) {
6068 uint32_t Type = Note.getType();
6069 auto FindNote = [&](ArrayRef<NoteType> V) -> StringRef {
6070 for (const NoteType &N : V)
6071 if (N.ID == Type)
6072 return N.Name;
6073 return "";
6076 StringRef Name = Note.getName();
6077 if (Name == "GNU")
6078 return FindNote(GNUNoteTypes);
6079 if (Name == "FreeBSD") {
6080 if (ELFType == ELF::ET_CORE) {
6081 // FreeBSD also places the generic core notes in the FreeBSD namespace.
6082 StringRef Result = FindNote(FreeBSDCoreNoteTypes);
6083 if (!Result.empty())
6084 return Result;
6085 return FindNote(CoreNoteTypes);
6086 } else {
6087 return FindNote(FreeBSDNoteTypes);
6090 if (ELFType == ELF::ET_CORE && Name.starts_with("NetBSD-CORE")) {
6091 StringRef Result = FindNote(NetBSDCoreNoteTypes);
6092 if (!Result.empty())
6093 return Result;
6094 return FindNote(CoreNoteTypes);
6096 if (ELFType == ELF::ET_CORE && Name.starts_with("OpenBSD")) {
6097 // OpenBSD also places the generic core notes in the OpenBSD namespace.
6098 StringRef Result = FindNote(OpenBSDCoreNoteTypes);
6099 if (!Result.empty())
6100 return Result;
6101 return FindNote(CoreNoteTypes);
6103 if (Name == "AMD")
6104 return FindNote(AMDNoteTypes);
6105 if (Name == "AMDGPU")
6106 return FindNote(AMDGPUNoteTypes);
6107 if (Name == "LLVMOMPOFFLOAD")
6108 return FindNote(LLVMOMPOFFLOADNoteTypes);
6109 if (Name == "Android")
6110 return FindNote(AndroidNoteTypes);
6112 if (ELFType == ELF::ET_CORE)
6113 return FindNote(CoreNoteTypes);
6114 return FindNote(GenericNoteTypes);
6117 template <class ELFT>
6118 static void processNotesHelper(
6119 const ELFDumper<ELFT> &Dumper,
6120 llvm::function_ref<void(std::optional<StringRef>, typename ELFT::Off,
6121 typename ELFT::Addr, size_t)>
6122 StartNotesFn,
6123 llvm::function_ref<Error(const typename ELFT::Note &, bool)> ProcessNoteFn,
6124 llvm::function_ref<void()> FinishNotesFn) {
6125 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
6126 bool IsCoreFile = Obj.getHeader().e_type == ELF::ET_CORE;
6128 ArrayRef<typename ELFT::Shdr> Sections = cantFail(Obj.sections());
6129 if (!IsCoreFile && !Sections.empty()) {
6130 for (const typename ELFT::Shdr &S : Sections) {
6131 if (S.sh_type != SHT_NOTE)
6132 continue;
6133 StartNotesFn(expectedToStdOptional(Obj.getSectionName(S)), S.sh_offset,
6134 S.sh_size, S.sh_addralign);
6135 Error Err = Error::success();
6136 size_t I = 0;
6137 for (const typename ELFT::Note Note : Obj.notes(S, Err)) {
6138 if (Error E = ProcessNoteFn(Note, IsCoreFile))
6139 Dumper.reportUniqueWarning(
6140 "unable to read note with index " + Twine(I) + " from the " +
6141 describe(Obj, S) + ": " + toString(std::move(E)));
6142 ++I;
6144 if (Err)
6145 Dumper.reportUniqueWarning("unable to read notes from the " +
6146 describe(Obj, S) + ": " +
6147 toString(std::move(Err)));
6148 FinishNotesFn();
6150 return;
6153 Expected<ArrayRef<typename ELFT::Phdr>> PhdrsOrErr = Obj.program_headers();
6154 if (!PhdrsOrErr) {
6155 Dumper.reportUniqueWarning(
6156 "unable to read program headers to locate the PT_NOTE segment: " +
6157 toString(PhdrsOrErr.takeError()));
6158 return;
6161 for (size_t I = 0, E = (*PhdrsOrErr).size(); I != E; ++I) {
6162 const typename ELFT::Phdr &P = (*PhdrsOrErr)[I];
6163 if (P.p_type != PT_NOTE)
6164 continue;
6165 StartNotesFn(/*SecName=*/std::nullopt, P.p_offset, P.p_filesz, P.p_align);
6166 Error Err = Error::success();
6167 size_t Index = 0;
6168 for (const typename ELFT::Note Note : Obj.notes(P, Err)) {
6169 if (Error E = ProcessNoteFn(Note, IsCoreFile))
6170 Dumper.reportUniqueWarning("unable to read note with index " +
6171 Twine(Index) +
6172 " from the PT_NOTE segment with index " +
6173 Twine(I) + ": " + toString(std::move(E)));
6174 ++Index;
6176 if (Err)
6177 Dumper.reportUniqueWarning(
6178 "unable to read notes from the PT_NOTE segment with index " +
6179 Twine(I) + ": " + toString(std::move(Err)));
6180 FinishNotesFn();
6184 template <class ELFT> void GNUELFDumper<ELFT>::printNotes() {
6185 size_t Align = 0;
6186 bool IsFirstHeader = true;
6187 auto PrintHeader = [&](std::optional<StringRef> SecName,
6188 const typename ELFT::Off Offset,
6189 const typename ELFT::Addr Size, size_t Al) {
6190 Align = std::max<size_t>(Al, 4);
6191 // Print a newline between notes sections to match GNU readelf.
6192 if (!IsFirstHeader) {
6193 OS << '\n';
6194 } else {
6195 IsFirstHeader = false;
6198 OS << "Displaying notes found ";
6200 if (SecName)
6201 OS << "in: " << *SecName << "\n";
6202 else
6203 OS << "at file offset " << format_hex(Offset, 10) << " with length "
6204 << format_hex(Size, 10) << ":\n";
6206 OS << " Owner Data size \tDescription\n";
6209 auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
6210 StringRef Name = Note.getName();
6211 ArrayRef<uint8_t> Descriptor = Note.getDesc(Align);
6212 Elf_Word Type = Note.getType();
6214 // Print the note owner/type.
6215 OS << " " << left_justify(Name, 20) << ' '
6216 << format_hex(Descriptor.size(), 10) << '\t';
6218 StringRef NoteType =
6219 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
6220 if (!NoteType.empty())
6221 OS << NoteType << '\n';
6222 else
6223 OS << "Unknown note type: (" << format_hex(Type, 10) << ")\n";
6225 // Print the description, or fallback to printing raw bytes for unknown
6226 // owners/if we fail to pretty-print the contents.
6227 if (Name == "GNU") {
6228 if (printGNUNote<ELFT>(OS, Type, Descriptor))
6229 return Error::success();
6230 } else if (Name == "FreeBSD") {
6231 if (std::optional<FreeBSDNote> N =
6232 getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
6233 OS << " " << N->Type << ": " << N->Value << '\n';
6234 return Error::success();
6236 } else if (Name == "AMD") {
6237 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
6238 if (!N.Type.empty()) {
6239 OS << " " << N.Type << ":\n " << N.Value << '\n';
6240 return Error::success();
6242 } else if (Name == "AMDGPU") {
6243 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
6244 if (!N.Type.empty()) {
6245 OS << " " << N.Type << ":\n " << N.Value << '\n';
6246 return Error::success();
6248 } else if (Name == "LLVMOMPOFFLOAD") {
6249 if (printLLVMOMPOFFLOADNote<ELFT>(OS, Type, Descriptor))
6250 return Error::success();
6251 } else if (Name == "CORE") {
6252 if (Type == ELF::NT_FILE) {
6253 DataExtractor DescExtractor(
6254 Descriptor, ELFT::Endianness == llvm::endianness::little,
6255 sizeof(Elf_Addr));
6256 if (Expected<CoreNote> NoteOrErr = readCoreNote(DescExtractor)) {
6257 printCoreNote<ELFT>(OS, *NoteOrErr);
6258 return Error::success();
6259 } else {
6260 return NoteOrErr.takeError();
6263 } else if (Name == "Android") {
6264 if (printAndroidNote(OS, Type, Descriptor))
6265 return Error::success();
6267 if (!Descriptor.empty()) {
6268 OS << " description data:";
6269 for (uint8_t B : Descriptor)
6270 OS << " " << format("%02x", B);
6271 OS << '\n';
6273 return Error::success();
6276 processNotesHelper(*this, /*StartNotesFn=*/PrintHeader,
6277 /*ProcessNoteFn=*/ProcessNote, /*FinishNotesFn=*/[]() {});
6280 template <class ELFT>
6281 ArrayRef<uint8_t>
6282 ELFDumper<ELFT>::getMemtagGlobalsSectionContents(uint64_t ExpectedAddr) {
6283 for (const typename ELFT::Shdr &Sec : cantFail(Obj.sections())) {
6284 if (Sec.sh_type != SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC)
6285 continue;
6286 if (Sec.sh_addr != ExpectedAddr) {
6287 reportUniqueWarning(
6288 "SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section was unexpectedly at 0x" +
6289 Twine::utohexstr(Sec.sh_addr) +
6290 ", when DT_AARCH64_MEMTAG_GLOBALS says it should be at 0x" +
6291 Twine::utohexstr(ExpectedAddr));
6292 return ArrayRef<uint8_t>();
6294 Expected<ArrayRef<uint8_t>> Contents = Obj.getSectionContents(Sec);
6295 if (auto E = Contents.takeError()) {
6296 reportUniqueWarning(
6297 "couldn't get SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section contents: " +
6298 toString(std::move(E)));
6299 return ArrayRef<uint8_t>();
6301 return Contents.get();
6303 return ArrayRef<uint8_t>();
6306 // Reserve the lower three bits of the first byte of the step distance when
6307 // encoding the memtag descriptors. Found to be the best overall size tradeoff
6308 // when compiling Android T with full MTE globals enabled.
6309 constexpr uint64_t MemtagStepVarintReservedBits = 3;
6310 constexpr uint64_t MemtagGranuleSize = 16;
6312 template <typename ELFT> void ELFDumper<ELFT>::printMemtag() {
6313 if (Obj.getHeader().e_machine != EM_AARCH64) return;
6314 std::vector<std::pair<std::string, std::string>> DynamicEntries;
6315 uint64_t MemtagGlobalsSz = 0;
6316 uint64_t MemtagGlobals = 0;
6317 for (const typename ELFT::Dyn &Entry : dynamic_table()) {
6318 uintX_t Tag = Entry.getTag();
6319 switch (Tag) {
6320 case DT_AARCH64_MEMTAG_GLOBALSSZ:
6321 MemtagGlobalsSz = Entry.getVal();
6322 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6323 getDynamicEntry(Tag, Entry.getVal()));
6324 break;
6325 case DT_AARCH64_MEMTAG_GLOBALS:
6326 MemtagGlobals = Entry.getVal();
6327 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6328 getDynamicEntry(Tag, Entry.getVal()));
6329 break;
6330 case DT_AARCH64_MEMTAG_MODE:
6331 case DT_AARCH64_MEMTAG_HEAP:
6332 case DT_AARCH64_MEMTAG_STACK:
6333 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6334 getDynamicEntry(Tag, Entry.getVal()));
6335 break;
6339 ArrayRef<uint8_t> AndroidNoteDesc;
6340 auto FindAndroidNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
6341 if (Note.getName() == "Android" &&
6342 Note.getType() == ELF::NT_ANDROID_TYPE_MEMTAG)
6343 AndroidNoteDesc = Note.getDesc(4);
6344 return Error::success();
6347 processNotesHelper(
6348 *this,
6349 /*StartNotesFn=*/
6350 [](std::optional<StringRef>, const typename ELFT::Off,
6351 const typename ELFT::Addr, size_t) {},
6352 /*ProcessNoteFn=*/FindAndroidNote, /*FinishNotesFn=*/[]() {});
6354 ArrayRef<uint8_t> Contents = getMemtagGlobalsSectionContents(MemtagGlobals);
6355 if (Contents.size() != MemtagGlobalsSz) {
6356 reportUniqueWarning(
6357 "mismatch between DT_AARCH64_MEMTAG_GLOBALSSZ (0x" +
6358 Twine::utohexstr(MemtagGlobalsSz) +
6359 ") and SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section size (0x" +
6360 Twine::utohexstr(Contents.size()) + ")");
6361 Contents = ArrayRef<uint8_t>();
6364 std::vector<std::pair<uint64_t, uint64_t>> GlobalDescriptors;
6365 uint64_t Address = 0;
6366 // See the AArch64 MemtagABI document for a description of encoding scheme:
6367 // https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#83encoding-of-sht_aarch64_memtag_globals_dynamic
6368 for (size_t I = 0; I < Contents.size();) {
6369 const char *Error = nullptr;
6370 unsigned DecodedBytes = 0;
6371 uint64_t Value = decodeULEB128(Contents.data() + I, &DecodedBytes,
6372 Contents.end(), &Error);
6373 I += DecodedBytes;
6374 if (Error) {
6375 reportUniqueWarning(
6376 "error decoding distance uleb, " + Twine(DecodedBytes) +
6377 " byte(s) into SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC: " + Twine(Error));
6378 GlobalDescriptors.clear();
6379 break;
6381 uint64_t Distance = Value >> MemtagStepVarintReservedBits;
6382 uint64_t GranulesToTag = Value & ((1 << MemtagStepVarintReservedBits) - 1);
6383 if (GranulesToTag == 0) {
6384 GranulesToTag = decodeULEB128(Contents.data() + I, &DecodedBytes,
6385 Contents.end(), &Error) +
6387 I += DecodedBytes;
6388 if (Error) {
6389 reportUniqueWarning(
6390 "error decoding size-only uleb, " + Twine(DecodedBytes) +
6391 " byte(s) into SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC: " + Twine(Error));
6392 GlobalDescriptors.clear();
6393 break;
6396 Address += Distance * MemtagGranuleSize;
6397 GlobalDescriptors.emplace_back(Address, GranulesToTag * MemtagGranuleSize);
6398 Address += GranulesToTag * MemtagGranuleSize;
6401 printMemtag(DynamicEntries, AndroidNoteDesc, GlobalDescriptors);
6404 template <class ELFT> void GNUELFDumper<ELFT>::printELFLinkerOptions() {
6405 OS << "printELFLinkerOptions not implemented!\n";
6408 template <class ELFT>
6409 void ELFDumper<ELFT>::printDependentLibsHelper(
6410 function_ref<void(const Elf_Shdr &)> OnSectionStart,
6411 function_ref<void(StringRef, uint64_t)> OnLibEntry) {
6412 auto Warn = [this](unsigned SecNdx, StringRef Msg) {
6413 this->reportUniqueWarning("SHT_LLVM_DEPENDENT_LIBRARIES section at index " +
6414 Twine(SecNdx) + " is broken: " + Msg);
6417 unsigned I = -1;
6418 for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
6419 ++I;
6420 if (Shdr.sh_type != ELF::SHT_LLVM_DEPENDENT_LIBRARIES)
6421 continue;
6423 OnSectionStart(Shdr);
6425 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Shdr);
6426 if (!ContentsOrErr) {
6427 Warn(I, toString(ContentsOrErr.takeError()));
6428 continue;
6431 ArrayRef<uint8_t> Contents = *ContentsOrErr;
6432 if (!Contents.empty() && Contents.back() != 0) {
6433 Warn(I, "the content is not null-terminated");
6434 continue;
6437 for (const uint8_t *I = Contents.begin(), *E = Contents.end(); I < E;) {
6438 StringRef Lib((const char *)I);
6439 OnLibEntry(Lib, I - Contents.begin());
6440 I += Lib.size() + 1;
6445 template <class ELFT>
6446 void ELFDumper<ELFT>::forEachRelocationDo(
6447 const Elf_Shdr &Sec,
6448 llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
6449 const Elf_Shdr &, const Elf_Shdr *)>
6450 RelRelaFn) {
6451 auto Warn = [&](Error &&E,
6452 const Twine &Prefix = "unable to read relocations from") {
6453 this->reportUniqueWarning(Prefix + " " + describe(Sec) + ": " +
6454 toString(std::move(E)));
6457 // SHT_RELR/SHT_ANDROID_RELR/SHT_AARCH64_AUTH_RELR sections do not have an
6458 // associated symbol table. For them we should not treat the value of the
6459 // sh_link field as an index of a symbol table.
6460 const Elf_Shdr *SymTab;
6461 if (Sec.sh_type != ELF::SHT_RELR && Sec.sh_type != ELF::SHT_ANDROID_RELR &&
6462 !(Obj.getHeader().e_machine == EM_AARCH64 &&
6463 Sec.sh_type == ELF::SHT_AARCH64_AUTH_RELR)) {
6464 Expected<const Elf_Shdr *> SymTabOrErr = Obj.getSection(Sec.sh_link);
6465 if (!SymTabOrErr) {
6466 Warn(SymTabOrErr.takeError(), "unable to locate a symbol table for");
6467 return;
6469 SymTab = *SymTabOrErr;
6472 unsigned RelNdx = 0;
6473 const bool IsMips64EL = this->Obj.isMips64EL();
6474 switch (Sec.sh_type) {
6475 case ELF::SHT_REL:
6476 if (Expected<Elf_Rel_Range> RangeOrErr = Obj.rels(Sec)) {
6477 for (const Elf_Rel &R : *RangeOrErr)
6478 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
6479 } else {
6480 Warn(RangeOrErr.takeError());
6482 break;
6483 case ELF::SHT_RELA:
6484 if (Expected<Elf_Rela_Range> RangeOrErr = Obj.relas(Sec)) {
6485 for (const Elf_Rela &R : *RangeOrErr)
6486 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
6487 } else {
6488 Warn(RangeOrErr.takeError());
6490 break;
6491 case ELF::SHT_AARCH64_AUTH_RELR:
6492 if (Obj.getHeader().e_machine != EM_AARCH64)
6493 break;
6494 [[fallthrough]];
6495 case ELF::SHT_RELR:
6496 case ELF::SHT_ANDROID_RELR: {
6497 Expected<Elf_Relr_Range> RangeOrErr = Obj.relrs(Sec);
6498 if (!RangeOrErr) {
6499 Warn(RangeOrErr.takeError());
6500 break;
6503 for (const Elf_Rel &R : Obj.decode_relrs(*RangeOrErr))
6504 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec,
6505 /*SymTab=*/nullptr);
6506 break;
6508 case ELF::SHT_CREL: {
6509 if (auto RelsOrRelas = Obj.crels(Sec)) {
6510 for (const Elf_Rel &R : RelsOrRelas->first)
6511 RelRelaFn(Relocation<ELFT>(R, false), RelNdx++, Sec, SymTab);
6512 for (const Elf_Rela &R : RelsOrRelas->second)
6513 RelRelaFn(Relocation<ELFT>(R, false), RelNdx++, Sec, SymTab);
6514 } else {
6515 Warn(RelsOrRelas.takeError());
6517 break;
6519 case ELF::SHT_ANDROID_REL:
6520 case ELF::SHT_ANDROID_RELA:
6521 if (Expected<std::vector<Elf_Rela>> RelasOrErr = Obj.android_relas(Sec)) {
6522 for (const Elf_Rela &R : *RelasOrErr)
6523 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
6524 } else {
6525 Warn(RelasOrErr.takeError());
6527 break;
6531 template <class ELFT>
6532 StringRef ELFDumper<ELFT>::getPrintableSectionName(const Elf_Shdr &Sec) const {
6533 StringRef Name = "<?>";
6534 if (Expected<StringRef> SecNameOrErr =
6535 Obj.getSectionName(Sec, this->WarningHandler))
6536 Name = *SecNameOrErr;
6537 else
6538 this->reportUniqueWarning("unable to get the name of " + describe(Sec) +
6539 ": " + toString(SecNameOrErr.takeError()));
6540 return Name;
6543 template <class ELFT> void GNUELFDumper<ELFT>::printDependentLibs() {
6544 bool SectionStarted = false;
6545 struct NameOffset {
6546 StringRef Name;
6547 uint64_t Offset;
6549 std::vector<NameOffset> SecEntries;
6550 NameOffset Current;
6551 auto PrintSection = [&]() {
6552 OS << "Dependent libraries section " << Current.Name << " at offset "
6553 << format_hex(Current.Offset, 1) << " contains " << SecEntries.size()
6554 << " entries:\n";
6555 for (NameOffset Entry : SecEntries)
6556 OS << " [" << format("%6" PRIx64, Entry.Offset) << "] " << Entry.Name
6557 << "\n";
6558 OS << "\n";
6559 SecEntries.clear();
6562 auto OnSectionStart = [&](const Elf_Shdr &Shdr) {
6563 if (SectionStarted)
6564 PrintSection();
6565 SectionStarted = true;
6566 Current.Offset = Shdr.sh_offset;
6567 Current.Name = this->getPrintableSectionName(Shdr);
6569 auto OnLibEntry = [&](StringRef Lib, uint64_t Offset) {
6570 SecEntries.push_back(NameOffset{Lib, Offset});
6573 this->printDependentLibsHelper(OnSectionStart, OnLibEntry);
6574 if (SectionStarted)
6575 PrintSection();
6578 template <class ELFT>
6579 SmallVector<uint32_t> ELFDumper<ELFT>::getSymbolIndexesForFunctionAddress(
6580 uint64_t SymValue, std::optional<const Elf_Shdr *> FunctionSec) {
6581 SmallVector<uint32_t> SymbolIndexes;
6582 if (!this->AddressToIndexMap) {
6583 // Populate the address to index map upon the first invocation of this
6584 // function.
6585 this->AddressToIndexMap.emplace();
6586 if (this->DotSymtabSec) {
6587 if (Expected<Elf_Sym_Range> SymsOrError =
6588 Obj.symbols(this->DotSymtabSec)) {
6589 uint32_t Index = (uint32_t)-1;
6590 for (const Elf_Sym &Sym : *SymsOrError) {
6591 ++Index;
6593 if (Sym.st_shndx == ELF::SHN_UNDEF || Sym.getType() != ELF::STT_FUNC)
6594 continue;
6596 Expected<uint64_t> SymAddrOrErr =
6597 ObjF.toSymbolRef(this->DotSymtabSec, Index).getAddress();
6598 if (!SymAddrOrErr) {
6599 std::string Name = this->getStaticSymbolName(Index);
6600 reportUniqueWarning("unable to get address of symbol '" + Name +
6601 "': " + toString(SymAddrOrErr.takeError()));
6602 return SymbolIndexes;
6605 (*this->AddressToIndexMap)[*SymAddrOrErr].push_back(Index);
6607 } else {
6608 reportUniqueWarning("unable to read the symbol table: " +
6609 toString(SymsOrError.takeError()));
6614 auto Symbols = this->AddressToIndexMap->find(SymValue);
6615 if (Symbols == this->AddressToIndexMap->end())
6616 return SymbolIndexes;
6618 for (uint32_t Index : Symbols->second) {
6619 // Check if the symbol is in the right section. FunctionSec == None
6620 // means "any section".
6621 if (FunctionSec) {
6622 const Elf_Sym &Sym = *cantFail(Obj.getSymbol(this->DotSymtabSec, Index));
6623 if (Expected<const Elf_Shdr *> SecOrErr =
6624 Obj.getSection(Sym, this->DotSymtabSec,
6625 this->getShndxTable(this->DotSymtabSec))) {
6626 if (*FunctionSec != *SecOrErr)
6627 continue;
6628 } else {
6629 std::string Name = this->getStaticSymbolName(Index);
6630 // Note: it is impossible to trigger this error currently, it is
6631 // untested.
6632 reportUniqueWarning("unable to get section of symbol '" + Name +
6633 "': " + toString(SecOrErr.takeError()));
6634 return SymbolIndexes;
6638 SymbolIndexes.push_back(Index);
6641 return SymbolIndexes;
6644 template <class ELFT>
6645 bool ELFDumper<ELFT>::printFunctionStackSize(
6646 uint64_t SymValue, std::optional<const Elf_Shdr *> FunctionSec,
6647 const Elf_Shdr &StackSizeSec, DataExtractor Data, uint64_t *Offset) {
6648 SmallVector<uint32_t> FuncSymIndexes =
6649 this->getSymbolIndexesForFunctionAddress(SymValue, FunctionSec);
6650 if (FuncSymIndexes.empty())
6651 reportUniqueWarning(
6652 "could not identify function symbol for stack size entry in " +
6653 describe(StackSizeSec));
6655 // Extract the size. The expectation is that Offset is pointing to the right
6656 // place, i.e. past the function address.
6657 Error Err = Error::success();
6658 uint64_t StackSize = Data.getULEB128(Offset, &Err);
6659 if (Err) {
6660 reportUniqueWarning("could not extract a valid stack size from " +
6661 describe(StackSizeSec) + ": " +
6662 toString(std::move(Err)));
6663 return false;
6666 if (FuncSymIndexes.empty()) {
6667 printStackSizeEntry(StackSize, {"?"});
6668 } else {
6669 SmallVector<std::string> FuncSymNames;
6670 for (uint32_t Index : FuncSymIndexes)
6671 FuncSymNames.push_back(this->getStaticSymbolName(Index));
6672 printStackSizeEntry(StackSize, FuncSymNames);
6675 return true;
6678 template <class ELFT>
6679 void GNUELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
6680 ArrayRef<std::string> FuncNames) {
6681 OS.PadToColumn(2);
6682 OS << format_decimal(Size, 11);
6683 OS.PadToColumn(18);
6685 OS << join(FuncNames.begin(), FuncNames.end(), ", ") << "\n";
6688 template <class ELFT>
6689 void ELFDumper<ELFT>::printStackSize(const Relocation<ELFT> &R,
6690 const Elf_Shdr &RelocSec, unsigned Ndx,
6691 const Elf_Shdr *SymTab,
6692 const Elf_Shdr *FunctionSec,
6693 const Elf_Shdr &StackSizeSec,
6694 const RelocationResolver &Resolver,
6695 DataExtractor Data) {
6696 // This function ignores potentially erroneous input, unless it is directly
6697 // related to stack size reporting.
6698 const Elf_Sym *Sym = nullptr;
6699 Expected<RelSymbol<ELFT>> TargetOrErr = this->getRelocationTarget(R, SymTab);
6700 if (!TargetOrErr)
6701 reportUniqueWarning("unable to get the target of relocation with index " +
6702 Twine(Ndx) + " in " + describe(RelocSec) + ": " +
6703 toString(TargetOrErr.takeError()));
6704 else
6705 Sym = TargetOrErr->Sym;
6707 uint64_t RelocSymValue = 0;
6708 if (Sym) {
6709 Expected<const Elf_Shdr *> SectionOrErr =
6710 this->Obj.getSection(*Sym, SymTab, this->getShndxTable(SymTab));
6711 if (!SectionOrErr) {
6712 reportUniqueWarning(
6713 "cannot identify the section for relocation symbol '" +
6714 (*TargetOrErr).Name + "': " + toString(SectionOrErr.takeError()));
6715 } else if (*SectionOrErr != FunctionSec) {
6716 reportUniqueWarning("relocation symbol '" + (*TargetOrErr).Name +
6717 "' is not in the expected section");
6718 // Pretend that the symbol is in the correct section and report its
6719 // stack size anyway.
6720 FunctionSec = *SectionOrErr;
6723 RelocSymValue = Sym->st_value;
6726 uint64_t Offset = R.Offset;
6727 if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
6728 reportUniqueWarning("found invalid relocation offset (0x" +
6729 Twine::utohexstr(Offset) + ") into " +
6730 describe(StackSizeSec) +
6731 " while trying to extract a stack size entry");
6732 return;
6735 uint64_t SymValue = Resolver(R.Type, Offset, RelocSymValue,
6736 Data.getAddress(&Offset), R.Addend.value_or(0));
6737 this->printFunctionStackSize(SymValue, FunctionSec, StackSizeSec, Data,
6738 &Offset);
6741 template <class ELFT>
6742 void ELFDumper<ELFT>::printNonRelocatableStackSizes(
6743 std::function<void()> PrintHeader) {
6744 // This function ignores potentially erroneous input, unless it is directly
6745 // related to stack size reporting.
6746 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
6747 if (this->getPrintableSectionName(Sec) != ".stack_sizes")
6748 continue;
6749 PrintHeader();
6750 ArrayRef<uint8_t> Contents =
6751 unwrapOrError(this->FileName, Obj.getSectionContents(Sec));
6752 DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
6753 uint64_t Offset = 0;
6754 while (Offset < Contents.size()) {
6755 // The function address is followed by a ULEB representing the stack
6756 // size. Check for an extra byte before we try to process the entry.
6757 if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
6758 reportUniqueWarning(
6759 describe(Sec) +
6760 " ended while trying to extract a stack size entry");
6761 break;
6763 uint64_t SymValue = Data.getAddress(&Offset);
6764 if (!printFunctionStackSize(SymValue, /*FunctionSec=*/std::nullopt, Sec,
6765 Data, &Offset))
6766 break;
6771 template <class ELFT>
6772 void ELFDumper<ELFT>::printRelocatableStackSizes(
6773 std::function<void()> PrintHeader) {
6774 // Build a map between stack size sections and their corresponding relocation
6775 // sections.
6776 auto IsMatch = [&](const Elf_Shdr &Sec) -> bool {
6777 StringRef SectionName;
6778 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec))
6779 SectionName = *NameOrErr;
6780 else
6781 consumeError(NameOrErr.takeError());
6783 return SectionName == ".stack_sizes";
6786 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>>
6787 StackSizeRelocMapOrErr = Obj.getSectionAndRelocations(IsMatch);
6788 if (!StackSizeRelocMapOrErr) {
6789 reportUniqueWarning("unable to get stack size map section(s): " +
6790 toString(StackSizeRelocMapOrErr.takeError()));
6791 return;
6794 for (const auto &StackSizeMapEntry : *StackSizeRelocMapOrErr) {
6795 PrintHeader();
6796 const Elf_Shdr *StackSizesELFSec = StackSizeMapEntry.first;
6797 const Elf_Shdr *RelocSec = StackSizeMapEntry.second;
6799 // Warn about stack size sections without a relocation section.
6800 if (!RelocSec) {
6801 reportWarning(createError(".stack_sizes (" + describe(*StackSizesELFSec) +
6802 ") does not have a corresponding "
6803 "relocation section"),
6804 FileName);
6805 continue;
6808 // A .stack_sizes section header's sh_link field is supposed to point
6809 // to the section that contains the functions whose stack sizes are
6810 // described in it.
6811 const Elf_Shdr *FunctionSec = unwrapOrError(
6812 this->FileName, Obj.getSection(StackSizesELFSec->sh_link));
6814 SupportsRelocation IsSupportedFn;
6815 RelocationResolver Resolver;
6816 std::tie(IsSupportedFn, Resolver) = getRelocationResolver(this->ObjF);
6817 ArrayRef<uint8_t> Contents =
6818 unwrapOrError(this->FileName, Obj.getSectionContents(*StackSizesELFSec));
6819 DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
6821 forEachRelocationDo(
6822 *RelocSec, [&](const Relocation<ELFT> &R, unsigned Ndx,
6823 const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
6824 if (!IsSupportedFn || !IsSupportedFn(R.Type)) {
6825 reportUniqueWarning(
6826 describe(*RelocSec) +
6827 " contains an unsupported relocation with index " + Twine(Ndx) +
6828 ": " + Obj.getRelocationTypeName(R.Type));
6829 return;
6832 this->printStackSize(R, *RelocSec, Ndx, SymTab, FunctionSec,
6833 *StackSizesELFSec, Resolver, Data);
6838 template <class ELFT>
6839 void GNUELFDumper<ELFT>::printStackSizes() {
6840 bool HeaderHasBeenPrinted = false;
6841 auto PrintHeader = [&]() {
6842 if (HeaderHasBeenPrinted)
6843 return;
6844 OS << "\nStack Sizes:\n";
6845 OS.PadToColumn(9);
6846 OS << "Size";
6847 OS.PadToColumn(18);
6848 OS << "Functions\n";
6849 HeaderHasBeenPrinted = true;
6852 // For non-relocatable objects, look directly for sections whose name starts
6853 // with .stack_sizes and process the contents.
6854 if (this->Obj.getHeader().e_type == ELF::ET_REL)
6855 this->printRelocatableStackSizes(PrintHeader);
6856 else
6857 this->printNonRelocatableStackSizes(PrintHeader);
6860 template <class ELFT>
6861 void GNUELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
6862 size_t Bias = ELFT::Is64Bits ? 8 : 0;
6863 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
6864 OS.PadToColumn(2);
6865 OS << format_hex_no_prefix(Parser.getGotAddress(E), 8 + Bias);
6866 OS.PadToColumn(11 + Bias);
6867 OS << format_decimal(Parser.getGotOffset(E), 6) << "(gp)";
6868 OS.PadToColumn(22 + Bias);
6869 OS << format_hex_no_prefix(*E, 8 + Bias);
6870 OS.PadToColumn(31 + 2 * Bias);
6871 OS << Purpose << "\n";
6874 OS << (Parser.IsStatic ? "Static GOT:\n" : "Primary GOT:\n");
6875 OS << " Canonical gp value: "
6876 << format_hex_no_prefix(Parser.getGp(), 8 + Bias) << "\n\n";
6878 OS << " Reserved entries:\n";
6879 if (ELFT::Is64Bits)
6880 OS << " Address Access Initial Purpose\n";
6881 else
6882 OS << " Address Access Initial Purpose\n";
6883 PrintEntry(Parser.getGotLazyResolver(), "Lazy resolver");
6884 if (Parser.getGotModulePointer())
6885 PrintEntry(Parser.getGotModulePointer(), "Module pointer (GNU extension)");
6887 if (!Parser.getLocalEntries().empty()) {
6888 OS << "\n";
6889 OS << " Local entries:\n";
6890 if (ELFT::Is64Bits)
6891 OS << " Address Access Initial\n";
6892 else
6893 OS << " Address Access Initial\n";
6894 for (auto &E : Parser.getLocalEntries())
6895 PrintEntry(&E, "");
6898 if (Parser.IsStatic)
6899 return;
6901 if (!Parser.getGlobalEntries().empty()) {
6902 OS << "\n";
6903 OS << " Global entries:\n";
6904 if (ELFT::Is64Bits)
6905 OS << " Address Access Initial Sym.Val."
6906 << " Type Ndx Name\n";
6907 else
6908 OS << " Address Access Initial Sym.Val. Type Ndx Name\n";
6910 DataRegion<Elf_Word> ShndxTable(
6911 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6912 for (auto &E : Parser.getGlobalEntries()) {
6913 const Elf_Sym &Sym = *Parser.getGotSym(&E);
6914 const Elf_Sym &FirstSym = this->dynamic_symbols()[0];
6915 std::string SymName = this->getFullSymbolName(
6916 Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
6918 OS.PadToColumn(2);
6919 OS << to_string(format_hex_no_prefix(Parser.getGotAddress(&E), 8 + Bias));
6920 OS.PadToColumn(11 + Bias);
6921 OS << to_string(format_decimal(Parser.getGotOffset(&E), 6)) + "(gp)";
6922 OS.PadToColumn(22 + Bias);
6923 OS << to_string(format_hex_no_prefix(E, 8 + Bias));
6924 OS.PadToColumn(31 + 2 * Bias);
6925 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
6926 OS.PadToColumn(40 + 3 * Bias);
6927 OS << enumToString(Sym.getType(), ArrayRef(ElfSymbolTypes));
6928 OS.PadToColumn(48 + 3 * Bias);
6929 OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
6930 ShndxTable);
6931 OS.PadToColumn(52 + 3 * Bias);
6932 OS << SymName << "\n";
6936 if (!Parser.getOtherEntries().empty())
6937 OS << "\n Number of TLS and multi-GOT entries "
6938 << Parser.getOtherEntries().size() << "\n";
6941 template <class ELFT>
6942 void GNUELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
6943 size_t Bias = ELFT::Is64Bits ? 8 : 0;
6944 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
6945 OS.PadToColumn(2);
6946 OS << format_hex_no_prefix(Parser.getPltAddress(E), 8 + Bias);
6947 OS.PadToColumn(11 + Bias);
6948 OS << format_hex_no_prefix(*E, 8 + Bias);
6949 OS.PadToColumn(20 + 2 * Bias);
6950 OS << Purpose << "\n";
6953 OS << "PLT GOT:\n\n";
6955 OS << " Reserved entries:\n";
6956 OS << " Address Initial Purpose\n";
6957 PrintEntry(Parser.getPltLazyResolver(), "PLT lazy resolver");
6958 if (Parser.getPltModulePointer())
6959 PrintEntry(Parser.getPltModulePointer(), "Module pointer");
6961 if (!Parser.getPltEntries().empty()) {
6962 OS << "\n";
6963 OS << " Entries:\n";
6964 OS << " Address Initial Sym.Val. Type Ndx Name\n";
6965 DataRegion<Elf_Word> ShndxTable(
6966 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6967 for (auto &E : Parser.getPltEntries()) {
6968 const Elf_Sym &Sym = *Parser.getPltSym(&E);
6969 const Elf_Sym &FirstSym = *cantFail(
6970 this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
6971 std::string SymName = this->getFullSymbolName(
6972 Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
6974 OS.PadToColumn(2);
6975 OS << to_string(format_hex_no_prefix(Parser.getPltAddress(&E), 8 + Bias));
6976 OS.PadToColumn(11 + Bias);
6977 OS << to_string(format_hex_no_prefix(E, 8 + Bias));
6978 OS.PadToColumn(20 + 2 * Bias);
6979 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
6980 OS.PadToColumn(29 + 3 * Bias);
6981 OS << enumToString(Sym.getType(), ArrayRef(ElfSymbolTypes));
6982 OS.PadToColumn(37 + 3 * Bias);
6983 OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
6984 ShndxTable);
6985 OS.PadToColumn(41 + 3 * Bias);
6986 OS << SymName << "\n";
6991 template <class ELFT>
6992 Expected<const Elf_Mips_ABIFlags<ELFT> *>
6993 getMipsAbiFlagsSection(const ELFDumper<ELFT> &Dumper) {
6994 const typename ELFT::Shdr *Sec = Dumper.findSectionByName(".MIPS.abiflags");
6995 if (Sec == nullptr)
6996 return nullptr;
6998 constexpr StringRef ErrPrefix = "unable to read the .MIPS.abiflags section: ";
6999 Expected<ArrayRef<uint8_t>> DataOrErr =
7000 Dumper.getElfObject().getELFFile().getSectionContents(*Sec);
7001 if (!DataOrErr)
7002 return createError(ErrPrefix + toString(DataOrErr.takeError()));
7004 if (DataOrErr->size() != sizeof(Elf_Mips_ABIFlags<ELFT>))
7005 return createError(ErrPrefix + "it has a wrong size (" +
7006 Twine(DataOrErr->size()) + ")");
7007 return reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(DataOrErr->data());
7010 template <class ELFT> void GNUELFDumper<ELFT>::printMipsABIFlags() {
7011 const Elf_Mips_ABIFlags<ELFT> *Flags = nullptr;
7012 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
7013 getMipsAbiFlagsSection(*this))
7014 Flags = *SecOrErr;
7015 else
7016 this->reportUniqueWarning(SecOrErr.takeError());
7017 if (!Flags)
7018 return;
7020 OS << "MIPS ABI Flags Version: " << Flags->version << "\n\n";
7021 OS << "ISA: MIPS" << int(Flags->isa_level);
7022 if (Flags->isa_rev > 1)
7023 OS << "r" << int(Flags->isa_rev);
7024 OS << "\n";
7025 OS << "GPR size: " << getMipsRegisterSize(Flags->gpr_size) << "\n";
7026 OS << "CPR1 size: " << getMipsRegisterSize(Flags->cpr1_size) << "\n";
7027 OS << "CPR2 size: " << getMipsRegisterSize(Flags->cpr2_size) << "\n";
7028 OS << "FP ABI: " << enumToString(Flags->fp_abi, ArrayRef(ElfMipsFpABIType))
7029 << "\n";
7030 OS << "ISA Extension: "
7031 << enumToString(Flags->isa_ext, ArrayRef(ElfMipsISAExtType)) << "\n";
7032 if (Flags->ases == 0)
7033 OS << "ASEs: None\n";
7034 else
7035 // FIXME: Print each flag on a separate line.
7036 OS << "ASEs: " << printFlags(Flags->ases, ArrayRef(ElfMipsASEFlags))
7037 << "\n";
7038 OS << "FLAGS 1: " << format_hex_no_prefix(Flags->flags1, 8, false) << "\n";
7039 OS << "FLAGS 2: " << format_hex_no_prefix(Flags->flags2, 8, false) << "\n";
7040 OS << "\n";
7043 template <class ELFT> void LLVMELFDumper<ELFT>::printFileHeaders() {
7044 const Elf_Ehdr &E = this->Obj.getHeader();
7046 DictScope D(W, "ElfHeader");
7048 DictScope D(W, "Ident");
7049 W.printBinary("Magic",
7050 ArrayRef<unsigned char>(E.e_ident).slice(ELF::EI_MAG0, 4));
7051 W.printEnum("Class", E.e_ident[ELF::EI_CLASS], ArrayRef(ElfClass));
7052 W.printEnum("DataEncoding", E.e_ident[ELF::EI_DATA],
7053 ArrayRef(ElfDataEncoding));
7054 W.printNumber("FileVersion", E.e_ident[ELF::EI_VERSION]);
7056 auto OSABI = ArrayRef(ElfOSABI);
7057 if (E.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH &&
7058 E.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) {
7059 switch (E.e_machine) {
7060 case ELF::EM_AMDGPU:
7061 OSABI = ArrayRef(AMDGPUElfOSABI);
7062 break;
7063 case ELF::EM_ARM:
7064 OSABI = ArrayRef(ARMElfOSABI);
7065 break;
7066 case ELF::EM_TI_C6000:
7067 OSABI = ArrayRef(C6000ElfOSABI);
7068 break;
7071 W.printEnum("OS/ABI", E.e_ident[ELF::EI_OSABI], OSABI);
7072 W.printNumber("ABIVersion", E.e_ident[ELF::EI_ABIVERSION]);
7073 W.printBinary("Unused",
7074 ArrayRef<unsigned char>(E.e_ident).slice(ELF::EI_PAD));
7077 std::string TypeStr;
7078 if (const EnumEntry<unsigned> *Ent = getObjectFileEnumEntry(E.e_type)) {
7079 TypeStr = Ent->Name.str();
7080 } else {
7081 if (E.e_type >= ET_LOPROC)
7082 TypeStr = "Processor Specific";
7083 else if (E.e_type >= ET_LOOS)
7084 TypeStr = "OS Specific";
7085 else
7086 TypeStr = "Unknown";
7088 W.printString("Type", TypeStr + " (0x" + utohexstr(E.e_type) + ")");
7090 W.printEnum("Machine", E.e_machine, ArrayRef(ElfMachineType));
7091 W.printNumber("Version", E.e_version);
7092 W.printHex("Entry", E.e_entry);
7093 W.printHex("ProgramHeaderOffset", E.e_phoff);
7094 W.printHex("SectionHeaderOffset", E.e_shoff);
7095 if (E.e_machine == EM_MIPS)
7096 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderMipsFlags),
7097 unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
7098 unsigned(ELF::EF_MIPS_MACH));
7099 else if (E.e_machine == EM_AMDGPU) {
7100 switch (E.e_ident[ELF::EI_ABIVERSION]) {
7101 default:
7102 W.printHex("Flags", E.e_flags);
7103 break;
7104 case 0:
7105 // ELFOSABI_AMDGPU_PAL, ELFOSABI_AMDGPU_MESA3D support *_V3 flags.
7106 [[fallthrough]];
7107 case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
7108 W.printFlags("Flags", E.e_flags,
7109 ArrayRef(ElfHeaderAMDGPUFlagsABIVersion3),
7110 unsigned(ELF::EF_AMDGPU_MACH));
7111 break;
7112 case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
7113 case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
7114 W.printFlags("Flags", E.e_flags,
7115 ArrayRef(ElfHeaderAMDGPUFlagsABIVersion4),
7116 unsigned(ELF::EF_AMDGPU_MACH),
7117 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
7118 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
7119 break;
7120 case ELF::ELFABIVERSION_AMDGPU_HSA_V6: {
7121 std::optional<FlagEntry> VerFlagEntry;
7122 // The string needs to remain alive from the moment we create a
7123 // FlagEntry until printFlags is done.
7124 std::string FlagStr;
7125 if (auto VersionFlag = E.e_flags & ELF::EF_AMDGPU_GENERIC_VERSION) {
7126 unsigned Version =
7127 VersionFlag >> ELF::EF_AMDGPU_GENERIC_VERSION_OFFSET;
7128 FlagStr = "EF_AMDGPU_GENERIC_VERSION_V" + std::to_string(Version);
7129 VerFlagEntry = FlagEntry(FlagStr, VersionFlag);
7131 W.printFlags(
7132 "Flags", E.e_flags, ArrayRef(ElfHeaderAMDGPUFlagsABIVersion4),
7133 unsigned(ELF::EF_AMDGPU_MACH),
7134 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
7135 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4),
7136 VerFlagEntry ? ArrayRef(*VerFlagEntry) : ArrayRef<FlagEntry>());
7137 break;
7140 } else if (E.e_machine == EM_RISCV)
7141 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderRISCVFlags));
7142 else if (E.e_machine == EM_SPARC32PLUS || E.e_machine == EM_SPARCV9)
7143 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderSPARCFlags),
7144 unsigned(ELF::EF_SPARCV9_MM));
7145 else if (E.e_machine == EM_AVR)
7146 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderAVRFlags),
7147 unsigned(ELF::EF_AVR_ARCH_MASK));
7148 else if (E.e_machine == EM_LOONGARCH)
7149 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderLoongArchFlags),
7150 unsigned(ELF::EF_LOONGARCH_ABI_MODIFIER_MASK),
7151 unsigned(ELF::EF_LOONGARCH_OBJABI_MASK));
7152 else if (E.e_machine == EM_XTENSA)
7153 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderXtensaFlags),
7154 unsigned(ELF::EF_XTENSA_MACH));
7155 else if (E.e_machine == EM_CUDA)
7156 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderNVPTXFlags),
7157 unsigned(ELF::EF_CUDA_SM));
7158 else
7159 W.printFlags("Flags", E.e_flags);
7160 W.printNumber("HeaderSize", E.e_ehsize);
7161 W.printNumber("ProgramHeaderEntrySize", E.e_phentsize);
7162 W.printNumber("ProgramHeaderCount", E.e_phnum);
7163 W.printNumber("SectionHeaderEntrySize", E.e_shentsize);
7164 W.printString("SectionHeaderCount",
7165 getSectionHeadersNumString(this->Obj, this->FileName));
7166 W.printString("StringTableSectionIndex",
7167 getSectionHeaderTableIndexString(this->Obj, this->FileName));
7171 template <class ELFT> void LLVMELFDumper<ELFT>::printGroupSections() {
7172 DictScope Lists(W, "Groups");
7173 std::vector<GroupSection> V = this->getGroups();
7174 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
7175 for (const GroupSection &G : V) {
7176 DictScope D(W, "Group");
7177 W.printNumber("Name", G.Name, G.ShName);
7178 W.printNumber("Index", G.Index);
7179 W.printNumber("Link", G.Link);
7180 W.printNumber("Info", G.Info);
7181 W.printHex("Type", getGroupType(G.Type), G.Type);
7182 W.printString("Signature", G.Signature);
7184 ListScope L(W, getGroupSectionHeaderName());
7185 for (const GroupMember &GM : G.Members) {
7186 const GroupSection *MainGroup = Map[GM.Index];
7187 if (MainGroup != &G)
7188 this->reportUniqueWarning(
7189 "section with index " + Twine(GM.Index) +
7190 ", included in the group section with index " +
7191 Twine(MainGroup->Index) +
7192 ", was also found in the group section with index " +
7193 Twine(G.Index));
7194 printSectionGroupMembers(GM.Name, GM.Index);
7198 if (V.empty())
7199 printEmptyGroupMessage();
7202 template <class ELFT>
7203 std::string LLVMELFDumper<ELFT>::getGroupSectionHeaderName() const {
7204 return "Section(s) in group";
7207 template <class ELFT>
7208 void LLVMELFDumper<ELFT>::printSectionGroupMembers(StringRef Name,
7209 uint64_t Idx) const {
7210 W.startLine() << Name << " (" << Idx << ")\n";
7213 template <class ELFT> void LLVMELFDumper<ELFT>::printRelocations() {
7214 ListScope D(W, "Relocations");
7216 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
7217 if (!isRelocationSec<ELFT>(Sec, this->Obj.getHeader()))
7218 continue;
7220 StringRef Name = this->getPrintableSectionName(Sec);
7221 unsigned SecNdx = &Sec - &cantFail(this->Obj.sections()).front();
7222 printRelocationSectionInfo(Sec, Name, SecNdx);
7226 template <class ELFT>
7227 void LLVMELFDumper<ELFT>::printExpandedRelRelaReloc(const Relocation<ELFT> &R,
7228 StringRef SymbolName,
7229 StringRef RelocName) {
7230 DictScope Group(W, "Relocation");
7231 W.printHex("Offset", R.Offset);
7232 W.printNumber("Type", RelocName, R.Type);
7233 W.printNumber("Symbol", !SymbolName.empty() ? SymbolName : "-", R.Symbol);
7234 if (R.Addend)
7235 W.printHex("Addend", (uintX_t)*R.Addend);
7238 template <class ELFT>
7239 void LLVMELFDumper<ELFT>::printDefaultRelRelaReloc(const Relocation<ELFT> &R,
7240 StringRef SymbolName,
7241 StringRef RelocName) {
7242 raw_ostream &OS = W.startLine();
7243 OS << W.hex(R.Offset) << " " << RelocName << " "
7244 << (!SymbolName.empty() ? SymbolName : "-");
7245 if (R.Addend)
7246 OS << " " << W.hex((uintX_t)*R.Addend);
7247 OS << "\n";
7250 template <class ELFT>
7251 void LLVMELFDumper<ELFT>::printRelocationSectionInfo(const Elf_Shdr &Sec,
7252 StringRef Name,
7253 const unsigned SecNdx) {
7254 DictScope D(W, (Twine("Section (") + Twine(SecNdx) + ") " + Name).str());
7255 this->printRelocationsHelper(Sec);
7258 template <class ELFT> void LLVMELFDumper<ELFT>::printEmptyGroupMessage() const {
7259 W.startLine() << "There are no group sections in the file.\n";
7262 template <class ELFT>
7263 void LLVMELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
7264 const RelSymbol<ELFT> &RelSym) {
7265 StringRef SymbolName = RelSym.Name;
7266 if (RelSym.Sym && RelSym.Name.empty())
7267 SymbolName = "<null>";
7268 SmallString<32> RelocName;
7269 this->Obj.getRelocationTypeName(R.Type, RelocName);
7271 if (opts::ExpandRelocs) {
7272 printExpandedRelRelaReloc(R, SymbolName, RelocName);
7273 } else {
7274 printDefaultRelRelaReloc(R, SymbolName, RelocName);
7278 template <class ELFT> void LLVMELFDumper<ELFT>::printSectionHeaders() {
7279 ListScope SectionsD(W, "Sections");
7281 int SectionIndex = -1;
7282 std::vector<EnumEntry<unsigned>> FlagsList =
7283 getSectionFlagsForTarget(this->Obj.getHeader().e_ident[ELF::EI_OSABI],
7284 this->Obj.getHeader().e_machine);
7285 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
7286 DictScope SectionD(W, "Section");
7287 W.printNumber("Index", ++SectionIndex);
7288 W.printNumber("Name", this->getPrintableSectionName(Sec), Sec.sh_name);
7289 W.printHex("Type",
7290 object::getELFSectionTypeName(this->Obj.getHeader().e_machine,
7291 Sec.sh_type),
7292 Sec.sh_type);
7293 W.printFlags("Flags", Sec.sh_flags, ArrayRef(FlagsList));
7294 W.printHex("Address", Sec.sh_addr);
7295 W.printHex("Offset", Sec.sh_offset);
7296 W.printNumber("Size", Sec.sh_size);
7297 W.printNumber("Link", Sec.sh_link);
7298 W.printNumber("Info", Sec.sh_info);
7299 W.printNumber("AddressAlignment", Sec.sh_addralign);
7300 W.printNumber("EntrySize", Sec.sh_entsize);
7302 if (opts::SectionRelocations) {
7303 ListScope D(W, "Relocations");
7304 this->printRelocationsHelper(Sec);
7307 if (opts::SectionSymbols) {
7308 ListScope D(W, "Symbols");
7309 if (this->DotSymtabSec) {
7310 StringRef StrTable = unwrapOrError(
7311 this->FileName,
7312 this->Obj.getStringTableForSymtab(*this->DotSymtabSec));
7313 ArrayRef<Elf_Word> ShndxTable = this->getShndxTable(this->DotSymtabSec);
7315 typename ELFT::SymRange Symbols = unwrapOrError(
7316 this->FileName, this->Obj.symbols(this->DotSymtabSec));
7317 for (const Elf_Sym &Sym : Symbols) {
7318 const Elf_Shdr *SymSec = unwrapOrError(
7319 this->FileName,
7320 this->Obj.getSection(Sym, this->DotSymtabSec, ShndxTable));
7321 if (SymSec == &Sec)
7322 printSymbol(Sym, &Sym - &Symbols[0], ShndxTable, StrTable, false,
7323 /*NonVisibilityBitsUsed=*/false,
7324 /*ExtraSymInfo=*/false);
7329 if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) {
7330 ArrayRef<uint8_t> Data =
7331 unwrapOrError(this->FileName, this->Obj.getSectionContents(Sec));
7332 W.printBinaryBlock(
7333 "SectionData",
7334 StringRef(reinterpret_cast<const char *>(Data.data()), Data.size()));
7339 template <class ELFT>
7340 void LLVMELFDumper<ELFT>::printSymbolSection(
7341 const Elf_Sym &Symbol, unsigned SymIndex,
7342 DataRegion<Elf_Word> ShndxTable) const {
7343 auto GetSectionSpecialType = [&]() -> std::optional<StringRef> {
7344 if (Symbol.isUndefined())
7345 return StringRef("Undefined");
7346 if (Symbol.isProcessorSpecific())
7347 return StringRef("Processor Specific");
7348 if (Symbol.isOSSpecific())
7349 return StringRef("Operating System Specific");
7350 if (Symbol.isAbsolute())
7351 return StringRef("Absolute");
7352 if (Symbol.isCommon())
7353 return StringRef("Common");
7354 if (Symbol.isReserved() && Symbol.st_shndx != SHN_XINDEX)
7355 return StringRef("Reserved");
7356 return std::nullopt;
7359 if (std::optional<StringRef> Type = GetSectionSpecialType()) {
7360 W.printHex("Section", *Type, Symbol.st_shndx);
7361 return;
7364 Expected<unsigned> SectionIndex =
7365 this->getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
7366 if (!SectionIndex) {
7367 assert(Symbol.st_shndx == SHN_XINDEX &&
7368 "getSymbolSectionIndex should only fail due to an invalid "
7369 "SHT_SYMTAB_SHNDX table/reference");
7370 this->reportUniqueWarning(SectionIndex.takeError());
7371 W.printHex("Section", "Reserved", SHN_XINDEX);
7372 return;
7375 Expected<StringRef> SectionName =
7376 this->getSymbolSectionName(Symbol, *SectionIndex);
7377 if (!SectionName) {
7378 // Don't report an invalid section name if the section headers are missing.
7379 // In such situations, all sections will be "invalid".
7380 if (!this->ObjF.sections().empty())
7381 this->reportUniqueWarning(SectionName.takeError());
7382 else
7383 consumeError(SectionName.takeError());
7384 W.printHex("Section", "<?>", *SectionIndex);
7385 } else {
7386 W.printHex("Section", *SectionName, *SectionIndex);
7390 template <class ELFT>
7391 void LLVMELFDumper<ELFT>::printSymbolOtherField(const Elf_Sym &Symbol) const {
7392 std::vector<EnumEntry<unsigned>> SymOtherFlags =
7393 this->getOtherFlagsFromSymbol(this->Obj.getHeader(), Symbol);
7394 W.printFlags("Other", Symbol.st_other, ArrayRef(SymOtherFlags), 0x3u);
7397 template <class ELFT>
7398 void LLVMELFDumper<ELFT>::printZeroSymbolOtherField(
7399 const Elf_Sym &Symbol) const {
7400 assert(Symbol.st_other == 0 && "non-zero Other Field");
7401 // Usually st_other flag is zero. Do not pollute the output
7402 // by flags enumeration in that case.
7403 W.printNumber("Other", 0);
7406 template <class ELFT>
7407 void LLVMELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
7408 DataRegion<Elf_Word> ShndxTable,
7409 std::optional<StringRef> StrTable,
7410 bool IsDynamic,
7411 bool /*NonVisibilityBitsUsed*/,
7412 bool /*ExtraSymInfo*/) const {
7413 std::string FullSymbolName = this->getFullSymbolName(
7414 Symbol, SymIndex, ShndxTable, StrTable, IsDynamic);
7415 unsigned char SymbolType = Symbol.getType();
7417 DictScope D(W, "Symbol");
7418 W.printNumber("Name", FullSymbolName, Symbol.st_name);
7419 W.printHex("Value", Symbol.st_value);
7420 W.printNumber("Size", Symbol.st_size);
7421 W.printEnum("Binding", Symbol.getBinding(), ArrayRef(ElfSymbolBindings));
7422 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
7423 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
7424 W.printEnum("Type", SymbolType, ArrayRef(AMDGPUSymbolTypes));
7425 else
7426 W.printEnum("Type", SymbolType, ArrayRef(ElfSymbolTypes));
7427 if (Symbol.st_other == 0)
7428 printZeroSymbolOtherField(Symbol);
7429 else
7430 printSymbolOtherField(Symbol);
7431 printSymbolSection(Symbol, SymIndex, ShndxTable);
7434 template <class ELFT>
7435 void LLVMELFDumper<ELFT>::printSymbols(bool PrintSymbols,
7436 bool PrintDynamicSymbols,
7437 bool ExtraSymInfo) {
7438 if (PrintSymbols) {
7439 ListScope Group(W, "Symbols");
7440 this->printSymbolsHelper(false, ExtraSymInfo);
7442 if (PrintDynamicSymbols) {
7443 ListScope Group(W, "DynamicSymbols");
7444 this->printSymbolsHelper(true, ExtraSymInfo);
7448 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicTable() {
7449 Elf_Dyn_Range Table = this->dynamic_table();
7450 if (Table.empty())
7451 return;
7453 W.startLine() << "DynamicSection [ (" << Table.size() << " entries)\n";
7455 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table);
7456 // The "Name/Value" column should be indented from the "Type" column by N
7457 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
7458 // space (1) = -3.
7459 W.startLine() << " Tag" << std::string(ELFT::Is64Bits ? 16 : 8, ' ')
7460 << "Type" << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
7462 std::string ValueFmt = "%-" + std::to_string(MaxTagSize) + "s ";
7463 for (auto Entry : Table) {
7464 uintX_t Tag = Entry.getTag();
7465 std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
7466 W.startLine() << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10, true)
7467 << " "
7468 << format(ValueFmt.c_str(),
7469 this->Obj.getDynamicTagAsString(Tag).c_str())
7470 << Value << "\n";
7472 W.startLine() << "]\n";
7475 template <class ELFT>
7476 void JSONELFDumper<ELFT>::printAuxillaryDynamicTableEntryInfo(
7477 const Elf_Dyn &Entry) {
7478 auto FormatFlags = [this, Value = Entry.getVal()](auto Flags) {
7479 ListScope L(this->W, "Flags");
7480 for (const auto &Flag : Flags) {
7481 if (Flag.Value != 0 && (Value & Flag.Value) == Flag.Value)
7482 this->W.printString(Flag.Name);
7485 switch (Entry.getTag()) {
7486 case DT_SONAME:
7487 this->W.printString("Name", this->getDynamicString(Entry.getVal()));
7488 break;
7489 case DT_AUXILIARY:
7490 case DT_FILTER:
7491 case DT_NEEDED:
7492 this->W.printString("Library", this->getDynamicString(Entry.getVal()));
7493 break;
7494 case DT_USED:
7495 this->W.printString("Object", this->getDynamicString(Entry.getVal()));
7496 break;
7497 case DT_RPATH:
7498 case DT_RUNPATH: {
7499 StringRef Value = this->getDynamicString(Entry.getVal());
7500 ListScope L(this->W, "Path");
7501 while (!Value.empty()) {
7502 auto [Front, Back] = Value.split(':');
7503 this->W.printString(Front);
7504 Value = Back;
7506 break;
7508 case DT_FLAGS:
7509 FormatFlags(ArrayRef(ElfDynamicDTFlags));
7510 break;
7511 case DT_FLAGS_1:
7512 FormatFlags(ArrayRef(ElfDynamicDTFlags1));
7513 break;
7514 default:
7515 return;
7519 template <class ELFT> void JSONELFDumper<ELFT>::printDynamicTable() {
7520 Elf_Dyn_Range Table = this->dynamic_table();
7521 ListScope L(this->W, "DynamicSection");
7522 for (const auto &Entry : Table) {
7523 DictScope D(this->W);
7524 uintX_t Tag = Entry.getTag();
7525 this->W.printHex("Tag", Tag);
7526 this->W.printString("Type", this->Obj.getDynamicTagAsString(Tag));
7527 this->W.printHex("Value", Entry.getVal());
7528 this->printAuxillaryDynamicTableEntryInfo(Entry);
7532 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicRelocations() {
7533 W.startLine() << "Dynamic Relocations {\n";
7534 W.indent();
7535 this->printDynamicRelocationsHelper();
7536 W.unindent();
7537 W.startLine() << "}\n";
7540 template <class ELFT>
7541 void LLVMELFDumper<ELFT>::printProgramHeaders(
7542 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
7543 if (PrintProgramHeaders)
7544 printProgramHeaders();
7545 if (PrintSectionMapping == cl::BOU_TRUE)
7546 printSectionMapping();
7549 template <class ELFT> void LLVMELFDumper<ELFT>::printProgramHeaders() {
7550 ListScope L(W, "ProgramHeaders");
7552 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
7553 if (!PhdrsOrErr) {
7554 this->reportUniqueWarning("unable to dump program headers: " +
7555 toString(PhdrsOrErr.takeError()));
7556 return;
7559 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
7560 DictScope P(W, "ProgramHeader");
7561 StringRef Type =
7562 segmentTypeToString(this->Obj.getHeader().e_machine, Phdr.p_type);
7564 W.printHex("Type", Type.empty() ? "Unknown" : Type, Phdr.p_type);
7565 W.printHex("Offset", Phdr.p_offset);
7566 W.printHex("VirtualAddress", Phdr.p_vaddr);
7567 W.printHex("PhysicalAddress", Phdr.p_paddr);
7568 W.printNumber("FileSize", Phdr.p_filesz);
7569 W.printNumber("MemSize", Phdr.p_memsz);
7570 W.printFlags("Flags", Phdr.p_flags, ArrayRef(ElfSegmentFlags));
7571 W.printNumber("Alignment", Phdr.p_align);
7575 template <class ELFT>
7576 void LLVMELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
7577 ListScope SS(W, "VersionSymbols");
7578 if (!Sec)
7579 return;
7581 StringRef StrTable;
7582 ArrayRef<Elf_Sym> Syms;
7583 const Elf_Shdr *SymTabSec;
7584 Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
7585 this->getVersionTable(*Sec, &Syms, &StrTable, &SymTabSec);
7586 if (!VerTableOrErr) {
7587 this->reportUniqueWarning(VerTableOrErr.takeError());
7588 return;
7591 if (StrTable.empty() || Syms.empty() || Syms.size() != VerTableOrErr->size())
7592 return;
7594 ArrayRef<Elf_Word> ShNdxTable = this->getShndxTable(SymTabSec);
7595 for (size_t I = 0, E = Syms.size(); I < E; ++I) {
7596 DictScope S(W, "Symbol");
7597 W.printNumber("Version", (*VerTableOrErr)[I].vs_index & VERSYM_VERSION);
7598 W.printString("Name",
7599 this->getFullSymbolName(Syms[I], I, ShNdxTable, StrTable,
7600 /*IsDynamic=*/true));
7604 const EnumEntry<unsigned> SymVersionFlags[] = {
7605 {"Base", "BASE", VER_FLG_BASE},
7606 {"Weak", "WEAK", VER_FLG_WEAK},
7607 {"Info", "INFO", VER_FLG_INFO}};
7609 template <class ELFT>
7610 void LLVMELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
7611 ListScope SD(W, "VersionDefinitions");
7612 if (!Sec)
7613 return;
7615 Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
7616 if (!V) {
7617 this->reportUniqueWarning(V.takeError());
7618 return;
7621 for (const VerDef &D : *V) {
7622 DictScope Def(W, "Definition");
7623 W.printNumber("Version", D.Version);
7624 W.printFlags("Flags", D.Flags, ArrayRef(SymVersionFlags));
7625 W.printNumber("Index", D.Ndx);
7626 W.printNumber("Hash", D.Hash);
7627 W.printString("Name", D.Name.c_str());
7628 W.printList(
7629 "Predecessors", D.AuxV,
7630 [](raw_ostream &OS, const VerdAux &Aux) { OS << Aux.Name.c_str(); });
7634 template <class ELFT>
7635 void LLVMELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
7636 ListScope SD(W, "VersionRequirements");
7637 if (!Sec)
7638 return;
7640 Expected<std::vector<VerNeed>> V =
7641 this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
7642 if (!V) {
7643 this->reportUniqueWarning(V.takeError());
7644 return;
7647 for (const VerNeed &VN : *V) {
7648 DictScope Entry(W, "Dependency");
7649 W.printNumber("Version", VN.Version);
7650 W.printNumber("Count", VN.Cnt);
7651 W.printString("FileName", VN.File.c_str());
7653 ListScope L(W, "Entries");
7654 for (const VernAux &Aux : VN.AuxV) {
7655 DictScope Entry(W, "Entry");
7656 W.printNumber("Hash", Aux.Hash);
7657 W.printFlags("Flags", Aux.Flags, ArrayRef(SymVersionFlags));
7658 W.printNumber("Index", Aux.Other);
7659 W.printString("Name", Aux.Name.c_str());
7664 template <class ELFT>
7665 void LLVMELFDumper<ELFT>::printHashHistogramStats(size_t NBucket,
7666 size_t MaxChain,
7667 size_t TotalSyms,
7668 ArrayRef<size_t> Count,
7669 bool IsGnu) const {
7670 StringRef HistName = IsGnu ? "GnuHashHistogram" : "HashHistogram";
7671 StringRef BucketName = IsGnu ? "Bucket" : "Chain";
7672 StringRef ListName = IsGnu ? "Buckets" : "Chains";
7673 DictScope Outer(W, HistName);
7674 W.printNumber("TotalBuckets", NBucket);
7675 ListScope Buckets(W, ListName);
7676 size_t CumulativeNonZero = 0;
7677 for (size_t I = 0; I < MaxChain; ++I) {
7678 CumulativeNonZero += Count[I] * I;
7679 DictScope Bucket(W, BucketName);
7680 W.printNumber("Length", I);
7681 W.printNumber("Count", Count[I]);
7682 W.printNumber("Percentage", (float)(Count[I] * 100.0) / NBucket);
7683 W.printNumber("Coverage", (float)(CumulativeNonZero * 100.0) / TotalSyms);
7687 // Returns true if rel/rela section exists, and populates SymbolIndices.
7688 // Otherwise returns false.
7689 template <class ELFT>
7690 static bool getSymbolIndices(const typename ELFT::Shdr *CGRelSection,
7691 const ELFFile<ELFT> &Obj,
7692 const LLVMELFDumper<ELFT> *Dumper,
7693 SmallVector<uint32_t, 128> &SymbolIndices) {
7694 if (!CGRelSection) {
7695 Dumper->reportUniqueWarning(
7696 "relocation section for a call graph section doesn't exist");
7697 return false;
7700 if (CGRelSection->sh_type == SHT_REL) {
7701 typename ELFT::RelRange CGProfileRel;
7702 Expected<typename ELFT::RelRange> CGProfileRelOrError =
7703 Obj.rels(*CGRelSection);
7704 if (!CGProfileRelOrError) {
7705 Dumper->reportUniqueWarning("unable to load relocations for "
7706 "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
7707 toString(CGProfileRelOrError.takeError()));
7708 return false;
7711 CGProfileRel = *CGProfileRelOrError;
7712 for (const typename ELFT::Rel &Rel : CGProfileRel)
7713 SymbolIndices.push_back(Rel.getSymbol(Obj.isMips64EL()));
7714 } else {
7715 // MC unconditionally produces SHT_REL, but GNU strip/objcopy may convert
7716 // the format to SHT_RELA
7717 // (https://sourceware.org/bugzilla/show_bug.cgi?id=28035)
7718 typename ELFT::RelaRange CGProfileRela;
7719 Expected<typename ELFT::RelaRange> CGProfileRelaOrError =
7720 Obj.relas(*CGRelSection);
7721 if (!CGProfileRelaOrError) {
7722 Dumper->reportUniqueWarning("unable to load relocations for "
7723 "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
7724 toString(CGProfileRelaOrError.takeError()));
7725 return false;
7728 CGProfileRela = *CGProfileRelaOrError;
7729 for (const typename ELFT::Rela &Rela : CGProfileRela)
7730 SymbolIndices.push_back(Rela.getSymbol(Obj.isMips64EL()));
7733 return true;
7736 template <class ELFT> void LLVMELFDumper<ELFT>::printCGProfile() {
7737 auto IsMatch = [](const Elf_Shdr &Sec) -> bool {
7738 return Sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE;
7741 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SecToRelocMapOrErr =
7742 this->Obj.getSectionAndRelocations(IsMatch);
7743 if (!SecToRelocMapOrErr) {
7744 this->reportUniqueWarning("unable to get CG Profile section(s): " +
7745 toString(SecToRelocMapOrErr.takeError()));
7746 return;
7749 for (const auto &CGMapEntry : *SecToRelocMapOrErr) {
7750 const Elf_Shdr *CGSection = CGMapEntry.first;
7751 const Elf_Shdr *CGRelSection = CGMapEntry.second;
7753 Expected<ArrayRef<Elf_CGProfile>> CGProfileOrErr =
7754 this->Obj.template getSectionContentsAsArray<Elf_CGProfile>(*CGSection);
7755 if (!CGProfileOrErr) {
7756 this->reportUniqueWarning(
7757 "unable to load the SHT_LLVM_CALL_GRAPH_PROFILE section: " +
7758 toString(CGProfileOrErr.takeError()));
7759 return;
7762 SmallVector<uint32_t, 128> SymbolIndices;
7763 bool UseReloc =
7764 getSymbolIndices<ELFT>(CGRelSection, this->Obj, this, SymbolIndices);
7765 if (UseReloc && SymbolIndices.size() != CGProfileOrErr->size() * 2) {
7766 this->reportUniqueWarning(
7767 "number of from/to pairs does not match number of frequencies");
7768 UseReloc = false;
7771 ListScope L(W, "CGProfile");
7772 for (uint32_t I = 0, Size = CGProfileOrErr->size(); I != Size; ++I) {
7773 const Elf_CGProfile &CGPE = (*CGProfileOrErr)[I];
7774 DictScope D(W, "CGProfileEntry");
7775 if (UseReloc) {
7776 uint32_t From = SymbolIndices[I * 2];
7777 uint32_t To = SymbolIndices[I * 2 + 1];
7778 W.printNumber("From", this->getStaticSymbolName(From), From);
7779 W.printNumber("To", this->getStaticSymbolName(To), To);
7781 W.printNumber("Weight", CGPE.cgp_weight);
7786 template <class ELFT>
7787 void LLVMELFDumper<ELFT>::printBBAddrMaps(bool PrettyPGOAnalysis) {
7788 bool IsRelocatable = this->Obj.getHeader().e_type == ELF::ET_REL;
7789 using Elf_Shdr = typename ELFT::Shdr;
7790 auto IsMatch = [](const Elf_Shdr &Sec) -> bool {
7791 return Sec.sh_type == ELF::SHT_LLVM_BB_ADDR_MAP;
7793 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SecRelocMapOrErr =
7794 this->Obj.getSectionAndRelocations(IsMatch);
7795 if (!SecRelocMapOrErr) {
7796 this->reportUniqueWarning(
7797 "failed to get SHT_LLVM_BB_ADDR_MAP section(s): " +
7798 toString(SecRelocMapOrErr.takeError()));
7799 return;
7801 for (auto const &[Sec, RelocSec] : *SecRelocMapOrErr) {
7802 std::optional<const Elf_Shdr *> FunctionSec;
7803 if (IsRelocatable)
7804 FunctionSec =
7805 unwrapOrError(this->FileName, this->Obj.getSection(Sec->sh_link));
7806 ListScope L(W, "BBAddrMap");
7807 if (IsRelocatable && !RelocSec) {
7808 this->reportUniqueWarning("unable to get relocation section for " +
7809 this->describe(*Sec));
7810 continue;
7812 std::vector<PGOAnalysisMap> PGOAnalyses;
7813 Expected<std::vector<BBAddrMap>> BBAddrMapOrErr =
7814 this->Obj.decodeBBAddrMap(*Sec, RelocSec, &PGOAnalyses);
7815 if (!BBAddrMapOrErr) {
7816 this->reportUniqueWarning("unable to dump " + this->describe(*Sec) +
7817 ": " + toString(BBAddrMapOrErr.takeError()));
7818 continue;
7820 for (const auto &[AM, PAM] : zip_equal(*BBAddrMapOrErr, PGOAnalyses)) {
7821 DictScope D(W, "Function");
7822 W.printHex("At", AM.getFunctionAddress());
7823 SmallVector<uint32_t> FuncSymIndex =
7824 this->getSymbolIndexesForFunctionAddress(AM.getFunctionAddress(),
7825 FunctionSec);
7826 std::string FuncName = "<?>";
7827 if (FuncSymIndex.empty())
7828 this->reportUniqueWarning(
7829 "could not identify function symbol for address (0x" +
7830 Twine::utohexstr(AM.getFunctionAddress()) + ") in " +
7831 this->describe(*Sec));
7832 else
7833 FuncName = this->getStaticSymbolName(FuncSymIndex.front());
7834 W.printString("Name", FuncName);
7836 ListScope BBRL(W, "BB Ranges");
7837 for (const BBAddrMap::BBRangeEntry &BBR : AM.BBRanges) {
7838 DictScope BBRD(W);
7839 W.printHex("Base Address", BBR.BaseAddress);
7840 ListScope BBEL(W, "BB Entries");
7841 for (const BBAddrMap::BBEntry &BBE : BBR.BBEntries) {
7842 DictScope BBED(W);
7843 W.printNumber("ID", BBE.ID);
7844 W.printHex("Offset", BBE.Offset);
7845 W.printHex("Size", BBE.Size);
7846 W.printBoolean("HasReturn", BBE.hasReturn());
7847 W.printBoolean("HasTailCall", BBE.hasTailCall());
7848 W.printBoolean("IsEHPad", BBE.isEHPad());
7849 W.printBoolean("CanFallThrough", BBE.canFallThrough());
7850 W.printBoolean("HasIndirectBranch", BBE.hasIndirectBranch());
7855 if (PAM.FeatEnable.hasPGOAnalysis()) {
7856 DictScope PD(W, "PGO analyses");
7858 if (PAM.FeatEnable.FuncEntryCount)
7859 W.printNumber("FuncEntryCount", PAM.FuncEntryCount);
7861 if (PAM.FeatEnable.hasPGOAnalysisBBData()) {
7862 ListScope L(W, "PGO BB entries");
7863 for (const PGOAnalysisMap::PGOBBEntry &PBBE : PAM.BBEntries) {
7864 DictScope L(W);
7866 if (PAM.FeatEnable.BBFreq) {
7867 if (PrettyPGOAnalysis) {
7868 std::string BlockFreqStr;
7869 raw_string_ostream SS(BlockFreqStr);
7870 printRelativeBlockFreq(SS, PAM.BBEntries.front().BlockFreq,
7871 PBBE.BlockFreq);
7872 W.printString("Frequency", BlockFreqStr);
7873 } else {
7874 W.printNumber("Frequency", PBBE.BlockFreq.getFrequency());
7878 if (PAM.FeatEnable.BrProb) {
7879 ListScope L(W, "Successors");
7880 for (const auto &Succ : PBBE.Successors) {
7881 DictScope L(W);
7882 W.printNumber("ID", Succ.ID);
7883 if (PrettyPGOAnalysis) {
7884 W.printObject("Probability", Succ.Prob);
7885 } else {
7886 W.printHex("Probability", Succ.Prob.getNumerator());
7897 template <class ELFT> void LLVMELFDumper<ELFT>::printAddrsig() {
7898 ListScope L(W, "Addrsig");
7899 if (!this->DotAddrsigSec)
7900 return;
7902 Expected<std::vector<uint64_t>> SymsOrErr =
7903 decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
7904 if (!SymsOrErr) {
7905 this->reportUniqueWarning(SymsOrErr.takeError());
7906 return;
7909 for (uint64_t Sym : *SymsOrErr)
7910 W.printNumber("Sym", this->getStaticSymbolName(Sym), Sym);
7913 template <typename ELFT>
7914 static bool printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
7915 ScopedPrinter &W) {
7916 // Return true if we were able to pretty-print the note, false otherwise.
7917 switch (NoteType) {
7918 default:
7919 return false;
7920 case ELF::NT_GNU_ABI_TAG: {
7921 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
7922 if (!AbiTag.IsValid) {
7923 W.printString("ABI", "<corrupt GNU_ABI_TAG>");
7924 return false;
7925 } else {
7926 W.printString("OS", AbiTag.OSName);
7927 W.printString("ABI", AbiTag.ABI);
7929 break;
7931 case ELF::NT_GNU_BUILD_ID: {
7932 W.printString("Build ID", getGNUBuildId(Desc));
7933 break;
7935 case ELF::NT_GNU_GOLD_VERSION:
7936 W.printString("Version", getDescAsStringRef(Desc));
7937 break;
7938 case ELF::NT_GNU_PROPERTY_TYPE_0:
7939 ListScope D(W, "Property");
7940 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
7941 W.printString(Property);
7942 break;
7944 return true;
7947 static bool printAndroidNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
7948 ScopedPrinter &W) {
7949 // Return true if we were able to pretty-print the note, false otherwise.
7950 AndroidNoteProperties Props = getAndroidNoteProperties(NoteType, Desc);
7951 if (Props.empty())
7952 return false;
7953 for (const auto &KV : Props)
7954 W.printString(KV.first, KV.second);
7955 return true;
7958 template <class ELFT>
7959 void LLVMELFDumper<ELFT>::printMemtag(
7960 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
7961 const ArrayRef<uint8_t> AndroidNoteDesc,
7962 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) {
7964 ListScope L(W, "Memtag Dynamic Entries:");
7965 if (DynamicEntries.empty())
7966 W.printString("< none found >");
7967 for (const auto &DynamicEntryKV : DynamicEntries)
7968 W.printString(DynamicEntryKV.first, DynamicEntryKV.second);
7971 if (!AndroidNoteDesc.empty()) {
7972 ListScope L(W, "Memtag Android Note:");
7973 printAndroidNoteLLVMStyle(ELF::NT_ANDROID_TYPE_MEMTAG, AndroidNoteDesc, W);
7976 if (Descriptors.empty())
7977 return;
7980 ListScope L(W, "Memtag Global Descriptors:");
7981 for (const auto &[Addr, BytesToTag] : Descriptors) {
7982 W.printHex("0x" + utohexstr(Addr), BytesToTag);
7987 template <typename ELFT>
7988 static bool printLLVMOMPOFFLOADNoteLLVMStyle(uint32_t NoteType,
7989 ArrayRef<uint8_t> Desc,
7990 ScopedPrinter &W) {
7991 switch (NoteType) {
7992 default:
7993 return false;
7994 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
7995 W.printString("Version", getDescAsStringRef(Desc));
7996 break;
7997 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
7998 W.printString("Producer", getDescAsStringRef(Desc));
7999 break;
8000 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
8001 W.printString("Producer version", getDescAsStringRef(Desc));
8002 break;
8004 return true;
8007 static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) {
8008 W.printNumber("Page Size", Note.PageSize);
8009 ListScope D(W, "Mappings");
8010 for (const CoreFileMapping &Mapping : Note.Mappings) {
8011 DictScope D(W);
8012 W.printHex("Start", Mapping.Start);
8013 W.printHex("End", Mapping.End);
8014 W.printHex("Offset", Mapping.Offset);
8015 W.printString("Filename", Mapping.Filename);
8019 template <class ELFT> void LLVMELFDumper<ELFT>::printNotes() {
8020 ListScope L(W, "NoteSections");
8022 std::unique_ptr<DictScope> NoteSectionScope;
8023 std::unique_ptr<ListScope> NotesScope;
8024 size_t Align = 0;
8025 auto StartNotes = [&](std::optional<StringRef> SecName,
8026 const typename ELFT::Off Offset,
8027 const typename ELFT::Addr Size, size_t Al) {
8028 Align = std::max<size_t>(Al, 4);
8029 NoteSectionScope = std::make_unique<DictScope>(W, "NoteSection");
8030 W.printString("Name", SecName ? *SecName : "<?>");
8031 W.printHex("Offset", Offset);
8032 W.printHex("Size", Size);
8033 NotesScope = std::make_unique<ListScope>(W, "Notes");
8036 auto EndNotes = [&] {
8037 NotesScope.reset();
8038 NoteSectionScope.reset();
8041 auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
8042 DictScope D2(W);
8043 StringRef Name = Note.getName();
8044 ArrayRef<uint8_t> Descriptor = Note.getDesc(Align);
8045 Elf_Word Type = Note.getType();
8047 // Print the note owner/type.
8048 W.printString("Owner", Name);
8049 W.printHex("Data size", Descriptor.size());
8051 StringRef NoteType =
8052 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
8053 if (!NoteType.empty())
8054 W.printString("Type", NoteType);
8055 else
8056 W.printString("Type",
8057 "Unknown (" + to_string(format_hex(Type, 10)) + ")");
8059 // Print the description, or fallback to printing raw bytes for unknown
8060 // owners/if we fail to pretty-print the contents.
8061 if (Name == "GNU") {
8062 if (printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W))
8063 return Error::success();
8064 } else if (Name == "FreeBSD") {
8065 if (std::optional<FreeBSDNote> N =
8066 getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
8067 W.printString(N->Type, N->Value);
8068 return Error::success();
8070 } else if (Name == "AMD") {
8071 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
8072 if (!N.Type.empty()) {
8073 W.printString(N.Type, N.Value);
8074 return Error::success();
8076 } else if (Name == "AMDGPU") {
8077 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
8078 if (!N.Type.empty()) {
8079 W.printString(N.Type, N.Value);
8080 return Error::success();
8082 } else if (Name == "LLVMOMPOFFLOAD") {
8083 if (printLLVMOMPOFFLOADNoteLLVMStyle<ELFT>(Type, Descriptor, W))
8084 return Error::success();
8085 } else if (Name == "CORE") {
8086 if (Type == ELF::NT_FILE) {
8087 DataExtractor DescExtractor(
8088 Descriptor, ELFT::Endianness == llvm::endianness::little,
8089 sizeof(Elf_Addr));
8090 if (Expected<CoreNote> N = readCoreNote(DescExtractor)) {
8091 printCoreNoteLLVMStyle(*N, W);
8092 return Error::success();
8093 } else {
8094 return N.takeError();
8097 } else if (Name == "Android") {
8098 if (printAndroidNoteLLVMStyle(Type, Descriptor, W))
8099 return Error::success();
8101 if (!Descriptor.empty()) {
8102 W.printBinaryBlock("Description data", Descriptor);
8104 return Error::success();
8107 processNotesHelper(*this, /*StartNotesFn=*/StartNotes,
8108 /*ProcessNoteFn=*/ProcessNote, /*FinishNotesFn=*/EndNotes);
8111 template <class ELFT> void LLVMELFDumper<ELFT>::printELFLinkerOptions() {
8112 ListScope L(W, "LinkerOptions");
8114 unsigned I = -1;
8115 for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) {
8116 ++I;
8117 if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS)
8118 continue;
8120 Expected<ArrayRef<uint8_t>> ContentsOrErr =
8121 this->Obj.getSectionContents(Shdr);
8122 if (!ContentsOrErr) {
8123 this->reportUniqueWarning("unable to read the content of the "
8124 "SHT_LLVM_LINKER_OPTIONS section: " +
8125 toString(ContentsOrErr.takeError()));
8126 continue;
8128 if (ContentsOrErr->empty())
8129 continue;
8131 if (ContentsOrErr->back() != 0) {
8132 this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " +
8133 Twine(I) +
8134 " is broken: the "
8135 "content is not null-terminated");
8136 continue;
8139 SmallVector<StringRef, 16> Strings;
8140 toStringRef(ContentsOrErr->drop_back()).split(Strings, '\0');
8141 if (Strings.size() % 2 != 0) {
8142 this->reportUniqueWarning(
8143 "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) +
8144 " is broken: an incomplete "
8145 "key-value pair was found. The last possible key was: \"" +
8146 Strings.back() + "\"");
8147 continue;
8150 for (size_t I = 0; I < Strings.size(); I += 2)
8151 W.printString(Strings[I], Strings[I + 1]);
8155 template <class ELFT> void LLVMELFDumper<ELFT>::printDependentLibs() {
8156 ListScope L(W, "DependentLibs");
8157 this->printDependentLibsHelper(
8158 [](const Elf_Shdr &) {},
8159 [this](StringRef Lib, uint64_t) { W.printString(Lib); });
8162 template <class ELFT> void LLVMELFDumper<ELFT>::printStackSizes() {
8163 ListScope L(W, "StackSizes");
8164 if (this->Obj.getHeader().e_type == ELF::ET_REL)
8165 this->printRelocatableStackSizes([]() {});
8166 else
8167 this->printNonRelocatableStackSizes([]() {});
8170 template <class ELFT>
8171 void LLVMELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
8172 ArrayRef<std::string> FuncNames) {
8173 DictScope D(W, "Entry");
8174 W.printList("Functions", FuncNames);
8175 W.printHex("Size", Size);
8178 template <class ELFT>
8179 void LLVMELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
8180 auto PrintEntry = [&](const Elf_Addr *E) {
8181 W.printHex("Address", Parser.getGotAddress(E));
8182 W.printNumber("Access", Parser.getGotOffset(E));
8183 W.printHex("Initial", *E);
8186 DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT");
8188 W.printHex("Canonical gp value", Parser.getGp());
8190 ListScope RS(W, "Reserved entries");
8192 DictScope D(W, "Entry");
8193 PrintEntry(Parser.getGotLazyResolver());
8194 W.printString("Purpose", StringRef("Lazy resolver"));
8197 if (Parser.getGotModulePointer()) {
8198 DictScope D(W, "Entry");
8199 PrintEntry(Parser.getGotModulePointer());
8200 W.printString("Purpose", StringRef("Module pointer (GNU extension)"));
8204 ListScope LS(W, "Local entries");
8205 for (auto &E : Parser.getLocalEntries()) {
8206 DictScope D(W, "Entry");
8207 PrintEntry(&E);
8211 if (Parser.IsStatic)
8212 return;
8215 ListScope GS(W, "Global entries");
8216 for (auto &E : Parser.getGlobalEntries()) {
8217 DictScope D(W, "Entry");
8219 PrintEntry(&E);
8221 const Elf_Sym &Sym = *Parser.getGotSym(&E);
8222 W.printHex("Value", Sym.st_value);
8223 W.printEnum("Type", Sym.getType(), ArrayRef(ElfSymbolTypes));
8225 const unsigned SymIndex = &Sym - this->dynamic_symbols().begin();
8226 DataRegion<Elf_Word> ShndxTable(
8227 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
8228 printSymbolSection(Sym, SymIndex, ShndxTable);
8230 std::string SymName = this->getFullSymbolName(
8231 Sym, SymIndex, ShndxTable, this->DynamicStringTable, true);
8232 W.printNumber("Name", SymName, Sym.st_name);
8236 W.printNumber("Number of TLS and multi-GOT entries",
8237 uint64_t(Parser.getOtherEntries().size()));
8240 template <class ELFT>
8241 void LLVMELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
8242 auto PrintEntry = [&](const Elf_Addr *E) {
8243 W.printHex("Address", Parser.getPltAddress(E));
8244 W.printHex("Initial", *E);
8247 DictScope GS(W, "PLT GOT");
8250 ListScope RS(W, "Reserved entries");
8252 DictScope D(W, "Entry");
8253 PrintEntry(Parser.getPltLazyResolver());
8254 W.printString("Purpose", StringRef("PLT lazy resolver"));
8257 if (auto E = Parser.getPltModulePointer()) {
8258 DictScope D(W, "Entry");
8259 PrintEntry(E);
8260 W.printString("Purpose", StringRef("Module pointer"));
8264 ListScope LS(W, "Entries");
8265 DataRegion<Elf_Word> ShndxTable(
8266 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
8267 for (auto &E : Parser.getPltEntries()) {
8268 DictScope D(W, "Entry");
8269 PrintEntry(&E);
8271 const Elf_Sym &Sym = *Parser.getPltSym(&E);
8272 W.printHex("Value", Sym.st_value);
8273 W.printEnum("Type", Sym.getType(), ArrayRef(ElfSymbolTypes));
8274 printSymbolSection(Sym, &Sym - this->dynamic_symbols().begin(),
8275 ShndxTable);
8277 const Elf_Sym *FirstSym = cantFail(
8278 this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
8279 std::string SymName = this->getFullSymbolName(
8280 Sym, &Sym - FirstSym, ShndxTable, Parser.getPltStrTable(), true);
8281 W.printNumber("Name", SymName, Sym.st_name);
8286 template <class ELFT> void LLVMELFDumper<ELFT>::printMipsABIFlags() {
8287 const Elf_Mips_ABIFlags<ELFT> *Flags;
8288 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
8289 getMipsAbiFlagsSection(*this)) {
8290 Flags = *SecOrErr;
8291 if (!Flags) {
8292 W.startLine() << "There is no .MIPS.abiflags section in the file.\n";
8293 return;
8295 } else {
8296 this->reportUniqueWarning(SecOrErr.takeError());
8297 return;
8300 raw_ostream &OS = W.getOStream();
8301 DictScope GS(W, "MIPS ABI Flags");
8303 W.printNumber("Version", Flags->version);
8304 W.startLine() << "ISA: ";
8305 if (Flags->isa_rev <= 1)
8306 OS << format("MIPS%u", Flags->isa_level);
8307 else
8308 OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev);
8309 OS << "\n";
8310 W.printEnum("ISA Extension", Flags->isa_ext, ArrayRef(ElfMipsISAExtType));
8311 W.printFlags("ASEs", Flags->ases, ArrayRef(ElfMipsASEFlags));
8312 W.printEnum("FP ABI", Flags->fp_abi, ArrayRef(ElfMipsFpABIType));
8313 W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size));
8314 W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size));
8315 W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size));
8316 W.printFlags("Flags 1", Flags->flags1, ArrayRef(ElfMipsFlags1));
8317 W.printHex("Flags 2", Flags->flags2);
8320 template <class ELFT>
8321 void JSONELFDumper<ELFT>::printFileSummary(StringRef FileStr, ObjectFile &Obj,
8322 ArrayRef<std::string> InputFilenames,
8323 const Archive *A) {
8324 FileScope = std::make_unique<DictScope>(this->W);
8325 DictScope D(this->W, "FileSummary");
8326 this->W.printString("File", FileStr);
8327 this->W.printString("Format", Obj.getFileFormatName());
8328 this->W.printString("Arch", Triple::getArchTypeName(Obj.getArch()));
8329 this->W.printString(
8330 "AddressSize",
8331 std::string(formatv("{0}bit", 8 * Obj.getBytesInAddress())));
8332 this->printLoadName();
8335 template <class ELFT>
8336 void JSONELFDumper<ELFT>::printZeroSymbolOtherField(
8337 const Elf_Sym &Symbol) const {
8338 // We want the JSON format to be uniform, since it is machine readable, so
8339 // always print the `Other` field the same way.
8340 this->printSymbolOtherField(Symbol);
8343 template <class ELFT>
8344 void JSONELFDumper<ELFT>::printDefaultRelRelaReloc(const Relocation<ELFT> &R,
8345 StringRef SymbolName,
8346 StringRef RelocName) {
8347 this->printExpandedRelRelaReloc(R, SymbolName, RelocName);
8350 template <class ELFT>
8351 void JSONELFDumper<ELFT>::printRelocationSectionInfo(const Elf_Shdr &Sec,
8352 StringRef Name,
8353 const unsigned SecNdx) {
8354 DictScope Group(this->W);
8355 this->W.printNumber("SectionIndex", SecNdx);
8356 ListScope D(this->W, "Relocs");
8357 this->printRelocationsHelper(Sec);
8360 template <class ELFT>
8361 std::string JSONELFDumper<ELFT>::getGroupSectionHeaderName() const {
8362 return "GroupSections";
8365 template <class ELFT>
8366 void JSONELFDumper<ELFT>::printSectionGroupMembers(StringRef Name,
8367 uint64_t Idx) const {
8368 DictScope Grp(this->W);
8369 this->W.printString("Name", Name);
8370 this->W.printNumber("Index", Idx);
8373 template <class ELFT> void JSONELFDumper<ELFT>::printEmptyGroupMessage() const {
8374 // JSON output does not need to print anything for empty groups