[NFC][Py Reformat] Reformat python files in llvm
[llvm-project.git] / llvm / tools / llvm-readobj / ELFDumper.cpp
blobb2b835d92ff8adb343574cd05d8ba3097e037fa3
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/PointerIntPair.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/BinaryFormat/AMDGPUMetadataVerifier.h"
32 #include "llvm/BinaryFormat/ELF.h"
33 #include "llvm/BinaryFormat/MsgPackDocument.h"
34 #include "llvm/Demangle/Demangle.h"
35 #include "llvm/Object/Archive.h"
36 #include "llvm/Object/ELF.h"
37 #include "llvm/Object/ELFObjectFile.h"
38 #include "llvm/Object/ELFTypes.h"
39 #include "llvm/Object/Error.h"
40 #include "llvm/Object/ObjectFile.h"
41 #include "llvm/Object/RelocationResolver.h"
42 #include "llvm/Object/StackMapParser.h"
43 #include "llvm/Support/AMDGPUMetadata.h"
44 #include "llvm/Support/ARMAttributeParser.h"
45 #include "llvm/Support/ARMBuildAttributes.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/Endian.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/Format.h"
51 #include "llvm/Support/FormatVariadic.h"
52 #include "llvm/Support/FormattedStream.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/raw_ostream.h"
62 #include <algorithm>
63 #include <cinttypes>
64 #include <cstddef>
65 #include <cstdint>
66 #include <cstdlib>
67 #include <iterator>
68 #include <memory>
69 #include <optional>
70 #include <string>
71 #include <system_error>
72 #include <vector>
74 using namespace llvm;
75 using namespace llvm::object;
76 using namespace ELF;
78 #define LLVM_READOBJ_ENUM_CASE(ns, enum) \
79 case ns::enum: \
80 return #enum;
82 #define ENUM_ENT(enum, altName) \
83 { #enum, altName, ELF::enum }
85 #define ENUM_ENT_1(enum) \
86 { #enum, #enum, ELF::enum }
88 namespace {
90 template <class ELFT> struct RelSymbol {
91 RelSymbol(const typename ELFT::Sym *S, StringRef N)
92 : Sym(S), Name(N.str()) {}
93 const typename ELFT::Sym *Sym;
94 std::string Name;
97 /// Represents a contiguous uniform range in the file. We cannot just create a
98 /// range directly because when creating one of these from the .dynamic table
99 /// the size, entity size and virtual address are different entries in arbitrary
100 /// order (DT_REL, DT_RELSZ, DT_RELENT for example).
101 struct DynRegionInfo {
102 DynRegionInfo(const Binary &Owner, const ObjDumper &D)
103 : Obj(&Owner), Dumper(&D) {}
104 DynRegionInfo(const Binary &Owner, const ObjDumper &D, const uint8_t *A,
105 uint64_t S, uint64_t ES)
106 : Addr(A), Size(S), EntSize(ES), Obj(&Owner), Dumper(&D) {}
108 /// Address in current address space.
109 const uint8_t *Addr = nullptr;
110 /// Size in bytes of the region.
111 uint64_t Size = 0;
112 /// Size of each entity in the region.
113 uint64_t EntSize = 0;
115 /// Owner object. Used for error reporting.
116 const Binary *Obj;
117 /// Dumper used for error reporting.
118 const ObjDumper *Dumper;
119 /// Error prefix. Used for error reporting to provide more information.
120 std::string Context;
121 /// Region size name. Used for error reporting.
122 StringRef SizePrintName = "size";
123 /// Entry size name. Used for error reporting. If this field is empty, errors
124 /// will not mention the entry size.
125 StringRef EntSizePrintName = "entry size";
127 template <typename Type> ArrayRef<Type> getAsArrayRef() const {
128 const Type *Start = reinterpret_cast<const Type *>(Addr);
129 if (!Start)
130 return {Start, Start};
132 const uint64_t Offset =
133 Addr - (const uint8_t *)Obj->getMemoryBufferRef().getBufferStart();
134 const uint64_t ObjSize = Obj->getMemoryBufferRef().getBufferSize();
136 if (Size > ObjSize - Offset) {
137 Dumper->reportUniqueWarning(
138 "unable to read data at 0x" + Twine::utohexstr(Offset) +
139 " of size 0x" + Twine::utohexstr(Size) + " (" + SizePrintName +
140 "): it goes past the end of the file of size 0x" +
141 Twine::utohexstr(ObjSize));
142 return {Start, Start};
145 if (EntSize == sizeof(Type) && (Size % EntSize == 0))
146 return {Start, Start + (Size / EntSize)};
148 std::string Msg;
149 if (!Context.empty())
150 Msg += Context + " has ";
152 Msg += ("invalid " + SizePrintName + " (0x" + Twine::utohexstr(Size) + ")")
153 .str();
154 if (!EntSizePrintName.empty())
155 Msg +=
156 (" or " + EntSizePrintName + " (0x" + Twine::utohexstr(EntSize) + ")")
157 .str();
159 Dumper->reportUniqueWarning(Msg);
160 return {Start, Start};
164 struct GroupMember {
165 StringRef Name;
166 uint64_t Index;
169 struct GroupSection {
170 StringRef Name;
171 std::string Signature;
172 uint64_t ShName;
173 uint64_t Index;
174 uint32_t Link;
175 uint32_t Info;
176 uint32_t Type;
177 std::vector<GroupMember> Members;
180 namespace {
182 struct NoteType {
183 uint32_t ID;
184 StringRef Name;
187 } // namespace
189 template <class ELFT> class Relocation {
190 public:
191 Relocation(const typename ELFT::Rel &R, bool IsMips64EL)
192 : Type(R.getType(IsMips64EL)), Symbol(R.getSymbol(IsMips64EL)),
193 Offset(R.r_offset), Info(R.r_info) {}
195 Relocation(const typename ELFT::Rela &R, bool IsMips64EL)
196 : Relocation((const typename ELFT::Rel &)R, IsMips64EL) {
197 Addend = R.r_addend;
200 uint32_t Type;
201 uint32_t Symbol;
202 typename ELFT::uint Offset;
203 typename ELFT::uint Info;
204 std::optional<int64_t> Addend;
207 template <class ELFT> class MipsGOTParser;
209 template <typename ELFT> class ELFDumper : public ObjDumper {
210 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
212 public:
213 ELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer);
215 void printUnwindInfo() override;
216 void printNeededLibraries() override;
217 void printHashTable() override;
218 void printGnuHashTable() override;
219 void printLoadName() override;
220 void printVersionInfo() override;
221 void printArchSpecificInfo() override;
222 void printStackMap() const override;
223 void printMemtag() override;
224 ArrayRef<uint8_t> getMemtagGlobalsSectionContents(uint64_t ExpectedAddr);
226 // Hash histogram shows statistics of how efficient the hash was for the
227 // dynamic symbol table. The table shows the number of hash buckets for
228 // different lengths of chains as an absolute number and percentage of the
229 // total buckets, and the cumulative coverage of symbols for each set of
230 // buckets.
231 void printHashHistograms() override;
233 const object::ELFObjectFile<ELFT> &getElfObject() const { return ObjF; };
235 std::string describe(const Elf_Shdr &Sec) const;
237 unsigned getHashTableEntSize() const {
238 // EM_S390 and ELF::EM_ALPHA platforms use 8-bytes entries in SHT_HASH
239 // sections. This violates the ELF specification.
240 if (Obj.getHeader().e_machine == ELF::EM_S390 ||
241 Obj.getHeader().e_machine == ELF::EM_ALPHA)
242 return 8;
243 return 4;
246 std::vector<EnumEntry<unsigned>>
247 getOtherFlagsFromSymbol(const Elf_Ehdr &Header, const Elf_Sym &Symbol) const;
249 Elf_Dyn_Range dynamic_table() const {
250 // A valid .dynamic section contains an array of entries terminated
251 // with a DT_NULL entry. However, sometimes the section content may
252 // continue past the DT_NULL entry, so to dump the section correctly,
253 // we first find the end of the entries by iterating over them.
254 Elf_Dyn_Range Table = DynamicTable.template getAsArrayRef<Elf_Dyn>();
256 size_t Size = 0;
257 while (Size < Table.size())
258 if (Table[Size++].getTag() == DT_NULL)
259 break;
261 return Table.slice(0, Size);
264 Elf_Sym_Range dynamic_symbols() const {
265 if (!DynSymRegion)
266 return Elf_Sym_Range();
267 return DynSymRegion->template getAsArrayRef<Elf_Sym>();
270 const Elf_Shdr *findSectionByName(StringRef Name) const;
272 StringRef getDynamicStringTable() const { return DynamicStringTable; }
274 protected:
275 virtual void printVersionSymbolSection(const Elf_Shdr *Sec) = 0;
276 virtual void printVersionDefinitionSection(const Elf_Shdr *Sec) = 0;
277 virtual void printVersionDependencySection(const Elf_Shdr *Sec) = 0;
279 void
280 printDependentLibsHelper(function_ref<void(const Elf_Shdr &)> OnSectionStart,
281 function_ref<void(StringRef, uint64_t)> OnLibEntry);
283 virtual void printRelRelaReloc(const Relocation<ELFT> &R,
284 const RelSymbol<ELFT> &RelSym) = 0;
285 virtual void printRelrReloc(const Elf_Relr &R) = 0;
286 virtual void printDynamicRelocHeader(unsigned Type, StringRef Name,
287 const DynRegionInfo &Reg) {}
288 void printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
289 const Elf_Shdr &Sec, const Elf_Shdr *SymTab);
290 void printDynamicReloc(const Relocation<ELFT> &R);
291 void printDynamicRelocationsHelper();
292 void printRelocationsHelper(const Elf_Shdr &Sec);
293 void forEachRelocationDo(
294 const Elf_Shdr &Sec, bool RawRelr,
295 llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
296 const Elf_Shdr &, const Elf_Shdr *)>
297 RelRelaFn,
298 llvm::function_ref<void(const Elf_Relr &)> RelrFn);
300 virtual void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
301 bool NonVisibilityBitsUsed) const {};
302 virtual void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
303 DataRegion<Elf_Word> ShndxTable,
304 std::optional<StringRef> StrTable, bool IsDynamic,
305 bool NonVisibilityBitsUsed) const = 0;
307 virtual void printMipsABIFlags() = 0;
308 virtual void printMipsGOT(const MipsGOTParser<ELFT> &Parser) = 0;
309 virtual void printMipsPLT(const MipsGOTParser<ELFT> &Parser) = 0;
311 virtual void printMemtag(
312 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
313 const ArrayRef<uint8_t> AndroidNoteDesc,
314 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) = 0;
316 virtual void printHashHistogram(const Elf_Hash &HashTable) const;
317 virtual void printGnuHashHistogram(const Elf_GnuHash &GnuHashTable) const;
318 virtual void printHashHistogramStats(size_t NBucket, size_t MaxChain,
319 size_t TotalSyms, ArrayRef<size_t> Count,
320 bool IsGnu) const = 0;
322 Expected<ArrayRef<Elf_Versym>>
323 getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
324 StringRef *StrTab, const Elf_Shdr **SymTabSec) const;
325 StringRef getPrintableSectionName(const Elf_Shdr &Sec) const;
327 std::vector<GroupSection> getGroups();
329 // Returns the function symbol index for the given address. Matches the
330 // symbol's section with FunctionSec when specified.
331 // Returns std::nullopt if no function symbol can be found for the address or
332 // in case it is not defined in the specified section.
333 SmallVector<uint32_t> getSymbolIndexesForFunctionAddress(
334 uint64_t SymValue, std::optional<const Elf_Shdr *> FunctionSec);
335 bool printFunctionStackSize(uint64_t SymValue,
336 std::optional<const Elf_Shdr *> FunctionSec,
337 const Elf_Shdr &StackSizeSec, DataExtractor Data,
338 uint64_t *Offset);
339 void printStackSize(const Relocation<ELFT> &R, const Elf_Shdr &RelocSec,
340 unsigned Ndx, const Elf_Shdr *SymTab,
341 const Elf_Shdr *FunctionSec, const Elf_Shdr &StackSizeSec,
342 const RelocationResolver &Resolver, DataExtractor Data);
343 virtual void printStackSizeEntry(uint64_t Size,
344 ArrayRef<std::string> FuncNames) = 0;
346 void printRelocatableStackSizes(std::function<void()> PrintHeader);
347 void printNonRelocatableStackSizes(std::function<void()> PrintHeader);
349 const object::ELFObjectFile<ELFT> &ObjF;
350 const ELFFile<ELFT> &Obj;
351 StringRef FileName;
353 Expected<DynRegionInfo> createDRI(uint64_t Offset, uint64_t Size,
354 uint64_t EntSize) {
355 if (Offset + Size < Offset || Offset + Size > Obj.getBufSize())
356 return createError("offset (0x" + Twine::utohexstr(Offset) +
357 ") + size (0x" + Twine::utohexstr(Size) +
358 ") is greater than the file size (0x" +
359 Twine::utohexstr(Obj.getBufSize()) + ")");
360 return DynRegionInfo(ObjF, *this, Obj.base() + Offset, Size, EntSize);
363 void printAttributes(unsigned, std::unique_ptr<ELFAttributeParser>,
364 support::endianness);
365 void printMipsReginfo();
366 void printMipsOptions();
368 std::pair<const Elf_Phdr *, const Elf_Shdr *> findDynamic();
369 void loadDynamicTable();
370 void parseDynamicTable();
372 Expected<StringRef> getSymbolVersion(const Elf_Sym &Sym,
373 bool &IsDefault) const;
374 Expected<SmallVector<std::optional<VersionEntry>, 0> *> getVersionMap() const;
376 DynRegionInfo DynRelRegion;
377 DynRegionInfo DynRelaRegion;
378 DynRegionInfo DynRelrRegion;
379 DynRegionInfo DynPLTRelRegion;
380 std::optional<DynRegionInfo> DynSymRegion;
381 DynRegionInfo DynSymTabShndxRegion;
382 DynRegionInfo DynamicTable;
383 StringRef DynamicStringTable;
384 const Elf_Hash *HashTable = nullptr;
385 const Elf_GnuHash *GnuHashTable = nullptr;
386 const Elf_Shdr *DotSymtabSec = nullptr;
387 const Elf_Shdr *DotDynsymSec = nullptr;
388 const Elf_Shdr *DotAddrsigSec = nullptr;
389 DenseMap<const Elf_Shdr *, ArrayRef<Elf_Word>> ShndxTables;
390 std::optional<uint64_t> SONameOffset;
391 std::optional<DenseMap<uint64_t, std::vector<uint32_t>>> AddressToIndexMap;
393 const Elf_Shdr *SymbolVersionSection = nullptr; // .gnu.version
394 const Elf_Shdr *SymbolVersionNeedSection = nullptr; // .gnu.version_r
395 const Elf_Shdr *SymbolVersionDefSection = nullptr; // .gnu.version_d
397 std::string getFullSymbolName(const Elf_Sym &Symbol, unsigned SymIndex,
398 DataRegion<Elf_Word> ShndxTable,
399 std::optional<StringRef> StrTable,
400 bool IsDynamic) const;
401 Expected<unsigned>
402 getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
403 DataRegion<Elf_Word> ShndxTable) const;
404 Expected<StringRef> getSymbolSectionName(const Elf_Sym &Symbol,
405 unsigned SectionIndex) const;
406 std::string getStaticSymbolName(uint32_t Index) const;
407 StringRef getDynamicString(uint64_t Value) const;
409 void printSymbolsHelper(bool IsDynamic) const;
410 std::string getDynamicEntry(uint64_t Type, uint64_t Value) const;
412 Expected<RelSymbol<ELFT>> getRelocationTarget(const Relocation<ELFT> &R,
413 const Elf_Shdr *SymTab) const;
415 ArrayRef<Elf_Word> getShndxTable(const Elf_Shdr *Symtab) const;
417 private:
418 mutable SmallVector<std::optional<VersionEntry>, 0> VersionMap;
421 template <class ELFT>
422 std::string ELFDumper<ELFT>::describe(const Elf_Shdr &Sec) const {
423 return ::describe(Obj, Sec);
426 namespace {
428 template <class ELFT> struct SymtabLink {
429 typename ELFT::SymRange Symbols;
430 StringRef StringTable;
431 const typename ELFT::Shdr *SymTab;
434 // Returns the linked symbol table, symbols and associated string table for a
435 // given section.
436 template <class ELFT>
437 Expected<SymtabLink<ELFT>> getLinkAsSymtab(const ELFFile<ELFT> &Obj,
438 const typename ELFT::Shdr &Sec,
439 unsigned ExpectedType) {
440 Expected<const typename ELFT::Shdr *> SymtabOrErr =
441 Obj.getSection(Sec.sh_link);
442 if (!SymtabOrErr)
443 return createError("invalid section linked to " + describe(Obj, Sec) +
444 ": " + toString(SymtabOrErr.takeError()));
446 if ((*SymtabOrErr)->sh_type != ExpectedType)
447 return createError(
448 "invalid section linked to " + describe(Obj, Sec) + ": expected " +
449 object::getELFSectionTypeName(Obj.getHeader().e_machine, ExpectedType) +
450 ", but got " +
451 object::getELFSectionTypeName(Obj.getHeader().e_machine,
452 (*SymtabOrErr)->sh_type));
454 Expected<StringRef> StrTabOrErr = Obj.getLinkAsStrtab(**SymtabOrErr);
455 if (!StrTabOrErr)
456 return createError(
457 "can't get a string table for the symbol table linked to " +
458 describe(Obj, Sec) + ": " + toString(StrTabOrErr.takeError()));
460 Expected<typename ELFT::SymRange> SymsOrErr = Obj.symbols(*SymtabOrErr);
461 if (!SymsOrErr)
462 return createError("unable to read symbols from the " + describe(Obj, Sec) +
463 ": " + toString(SymsOrErr.takeError()));
465 return SymtabLink<ELFT>{*SymsOrErr, *StrTabOrErr, *SymtabOrErr};
468 } // namespace
470 template <class ELFT>
471 Expected<ArrayRef<typename ELFT::Versym>>
472 ELFDumper<ELFT>::getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
473 StringRef *StrTab,
474 const Elf_Shdr **SymTabSec) const {
475 assert((!SymTab && !StrTab && !SymTabSec) || (SymTab && StrTab && SymTabSec));
476 if (reinterpret_cast<uintptr_t>(Obj.base() + Sec.sh_offset) %
477 sizeof(uint16_t) !=
479 return createError("the " + describe(Sec) + " is misaligned");
481 Expected<ArrayRef<Elf_Versym>> VersionsOrErr =
482 Obj.template getSectionContentsAsArray<Elf_Versym>(Sec);
483 if (!VersionsOrErr)
484 return createError("cannot read content of " + describe(Sec) + ": " +
485 toString(VersionsOrErr.takeError()));
487 Expected<SymtabLink<ELFT>> SymTabOrErr =
488 getLinkAsSymtab(Obj, Sec, SHT_DYNSYM);
489 if (!SymTabOrErr) {
490 reportUniqueWarning(SymTabOrErr.takeError());
491 return *VersionsOrErr;
494 if (SymTabOrErr->Symbols.size() != VersionsOrErr->size())
495 reportUniqueWarning(describe(Sec) + ": the number of entries (" +
496 Twine(VersionsOrErr->size()) +
497 ") does not match the number of symbols (" +
498 Twine(SymTabOrErr->Symbols.size()) +
499 ") in the symbol table with index " +
500 Twine(Sec.sh_link));
502 if (SymTab) {
503 *SymTab = SymTabOrErr->Symbols;
504 *StrTab = SymTabOrErr->StringTable;
505 *SymTabSec = SymTabOrErr->SymTab;
507 return *VersionsOrErr;
510 template <class ELFT>
511 void ELFDumper<ELFT>::printSymbolsHelper(bool IsDynamic) const {
512 std::optional<StringRef> StrTable;
513 size_t Entries = 0;
514 Elf_Sym_Range Syms(nullptr, nullptr);
515 const Elf_Shdr *SymtabSec = IsDynamic ? DotDynsymSec : DotSymtabSec;
517 if (IsDynamic) {
518 StrTable = DynamicStringTable;
519 Syms = dynamic_symbols();
520 Entries = Syms.size();
521 } else if (DotSymtabSec) {
522 if (Expected<StringRef> StrTableOrErr =
523 Obj.getStringTableForSymtab(*DotSymtabSec))
524 StrTable = *StrTableOrErr;
525 else
526 reportUniqueWarning(
527 "unable to get the string table for the SHT_SYMTAB section: " +
528 toString(StrTableOrErr.takeError()));
530 if (Expected<Elf_Sym_Range> SymsOrErr = Obj.symbols(DotSymtabSec))
531 Syms = *SymsOrErr;
532 else
533 reportUniqueWarning(
534 "unable to read symbols from the SHT_SYMTAB section: " +
535 toString(SymsOrErr.takeError()));
536 Entries = DotSymtabSec->getEntityCount();
538 if (Syms.empty())
539 return;
541 // The st_other field has 2 logical parts. The first two bits hold the symbol
542 // visibility (STV_*) and the remainder hold other platform-specific values.
543 bool NonVisibilityBitsUsed =
544 llvm::any_of(Syms, [](const Elf_Sym &S) { return S.st_other & ~0x3; });
546 DataRegion<Elf_Word> ShndxTable =
547 IsDynamic ? DataRegion<Elf_Word>(
548 (const Elf_Word *)this->DynSymTabShndxRegion.Addr,
549 this->getElfObject().getELFFile().end())
550 : DataRegion<Elf_Word>(this->getShndxTable(SymtabSec));
552 printSymtabMessage(SymtabSec, Entries, NonVisibilityBitsUsed);
553 for (const Elf_Sym &Sym : Syms)
554 printSymbol(Sym, &Sym - Syms.begin(), ShndxTable, StrTable, IsDynamic,
555 NonVisibilityBitsUsed);
558 template <typename ELFT> class GNUELFDumper : public ELFDumper<ELFT> {
559 formatted_raw_ostream &OS;
561 public:
562 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
564 GNUELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
565 : ELFDumper<ELFT>(ObjF, Writer),
566 OS(static_cast<formatted_raw_ostream &>(Writer.getOStream())) {
567 assert(&this->W.getOStream() == &llvm::fouts());
570 void printFileSummary(StringRef FileStr, ObjectFile &Obj,
571 ArrayRef<std::string> InputFilenames,
572 const Archive *A) override;
573 void printFileHeaders() override;
574 void printGroupSections() override;
575 void printRelocations() override;
576 void printSectionHeaders() override;
577 void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols) override;
578 void printHashSymbols() override;
579 void printSectionDetails() override;
580 void printDependentLibs() override;
581 void printDynamicTable() override;
582 void printDynamicRelocations() override;
583 void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
584 bool NonVisibilityBitsUsed) const override;
585 void printProgramHeaders(bool PrintProgramHeaders,
586 cl::boolOrDefault PrintSectionMapping) override;
587 void printVersionSymbolSection(const Elf_Shdr *Sec) override;
588 void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
589 void printVersionDependencySection(const Elf_Shdr *Sec) override;
590 void printCGProfile() override;
591 void printBBAddrMaps() override;
592 void printAddrsig() override;
593 void printNotes() override;
594 void printELFLinkerOptions() override;
595 void printStackSizes() override;
596 void printMemtag(
597 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
598 const ArrayRef<uint8_t> AndroidNoteDesc,
599 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) override;
600 void printHashHistogramStats(size_t NBucket, size_t MaxChain,
601 size_t TotalSyms, ArrayRef<size_t> Count,
602 bool IsGnu) const override;
604 private:
605 void printHashTableSymbols(const Elf_Hash &HashTable);
606 void printGnuHashTableSymbols(const Elf_GnuHash &GnuHashTable);
608 struct Field {
609 std::string Str;
610 unsigned Column;
612 Field(StringRef S, unsigned Col) : Str(std::string(S)), Column(Col) {}
613 Field(unsigned Col) : Column(Col) {}
616 template <typename T, typename TEnum>
617 std::string printFlags(T Value, ArrayRef<EnumEntry<TEnum>> EnumValues,
618 TEnum EnumMask1 = {}, TEnum EnumMask2 = {},
619 TEnum EnumMask3 = {}) const {
620 std::string Str;
621 for (const EnumEntry<TEnum> &Flag : EnumValues) {
622 if (Flag.Value == 0)
623 continue;
625 TEnum EnumMask{};
626 if (Flag.Value & EnumMask1)
627 EnumMask = EnumMask1;
628 else if (Flag.Value & EnumMask2)
629 EnumMask = EnumMask2;
630 else if (Flag.Value & EnumMask3)
631 EnumMask = EnumMask3;
632 bool IsEnum = (Flag.Value & EnumMask) != 0;
633 if ((!IsEnum && (Value & Flag.Value) == Flag.Value) ||
634 (IsEnum && (Value & EnumMask) == Flag.Value)) {
635 if (!Str.empty())
636 Str += ", ";
637 Str += Flag.AltName;
640 return Str;
643 formatted_raw_ostream &printField(struct Field F) const {
644 if (F.Column != 0)
645 OS.PadToColumn(F.Column);
646 OS << F.Str;
647 OS.flush();
648 return OS;
650 void printHashedSymbol(const Elf_Sym *Sym, unsigned SymIndex,
651 DataRegion<Elf_Word> ShndxTable, StringRef StrTable,
652 uint32_t Bucket);
653 void printRelrReloc(const Elf_Relr &R) override;
654 void printRelRelaReloc(const Relocation<ELFT> &R,
655 const RelSymbol<ELFT> &RelSym) override;
656 void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
657 DataRegion<Elf_Word> ShndxTable,
658 std::optional<StringRef> StrTable, bool IsDynamic,
659 bool NonVisibilityBitsUsed) const override;
660 void printDynamicRelocHeader(unsigned Type, StringRef Name,
661 const DynRegionInfo &Reg) override;
663 std::string getSymbolSectionNdx(const Elf_Sym &Symbol, unsigned SymIndex,
664 DataRegion<Elf_Word> ShndxTable) const;
665 void printProgramHeaders() override;
666 void printSectionMapping() override;
667 void printGNUVersionSectionProlog(const typename ELFT::Shdr &Sec,
668 const Twine &Label, unsigned EntriesNum);
670 void printStackSizeEntry(uint64_t Size,
671 ArrayRef<std::string> FuncNames) override;
673 void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
674 void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
675 void printMipsABIFlags() override;
678 template <typename ELFT> class LLVMELFDumper : public ELFDumper<ELFT> {
679 public:
680 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
682 LLVMELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
683 : ELFDumper<ELFT>(ObjF, Writer), W(Writer) {}
685 void printFileHeaders() override;
686 void printGroupSections() override;
687 void printRelocations() override;
688 void printSectionHeaders() override;
689 void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols) override;
690 void printDependentLibs() override;
691 void printDynamicTable() override;
692 void printDynamicRelocations() override;
693 void printProgramHeaders(bool PrintProgramHeaders,
694 cl::boolOrDefault PrintSectionMapping) override;
695 void printVersionSymbolSection(const Elf_Shdr *Sec) override;
696 void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
697 void printVersionDependencySection(const Elf_Shdr *Sec) override;
698 void printCGProfile() override;
699 void printBBAddrMaps() override;
700 void printAddrsig() override;
701 void printNotes() override;
702 void printELFLinkerOptions() override;
703 void printStackSizes() override;
704 void printMemtag(
705 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
706 const ArrayRef<uint8_t> AndroidNoteDesc,
707 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) override;
708 void printSymbolSection(const Elf_Sym &Symbol, unsigned SymIndex,
709 DataRegion<Elf_Word> ShndxTable) const;
710 void printHashHistogramStats(size_t NBucket, size_t MaxChain,
711 size_t TotalSyms, ArrayRef<size_t> Count,
712 bool IsGnu) const override;
714 private:
715 void printRelrReloc(const Elf_Relr &R) override;
716 void printRelRelaReloc(const Relocation<ELFT> &R,
717 const RelSymbol<ELFT> &RelSym) override;
719 void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
720 DataRegion<Elf_Word> ShndxTable,
721 std::optional<StringRef> StrTable, bool IsDynamic,
722 bool /*NonVisibilityBitsUsed*/) const override;
723 void printProgramHeaders() override;
724 void printSectionMapping() override {}
725 void printStackSizeEntry(uint64_t Size,
726 ArrayRef<std::string> FuncNames) override;
728 void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
729 void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
730 void printMipsABIFlags() override;
731 virtual void printZeroSymbolOtherField(const Elf_Sym &Symbol) const;
733 protected:
734 virtual std::string getGroupSectionHeaderName() const;
735 void printSymbolOtherField(const Elf_Sym &Symbol) const;
736 virtual void printExpandedRelRelaReloc(const Relocation<ELFT> &R,
737 StringRef SymbolName,
738 StringRef RelocName);
739 virtual void printDefaultRelRelaReloc(const Relocation<ELFT> &R,
740 StringRef SymbolName,
741 StringRef RelocName);
742 virtual void printRelocationSectionInfo(const Elf_Shdr &Sec, StringRef Name,
743 const unsigned SecNdx);
744 virtual void printSectionGroupMembers(StringRef Name, uint64_t Idx) const;
745 virtual void printEmptyGroupMessage() const;
747 ScopedPrinter &W;
750 // JSONELFDumper shares most of the same implementation as LLVMELFDumper except
751 // it uses a JSONScopedPrinter.
752 template <typename ELFT> class JSONELFDumper : public LLVMELFDumper<ELFT> {
753 public:
754 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
756 JSONELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
757 : LLVMELFDumper<ELFT>(ObjF, Writer) {}
759 std::string getGroupSectionHeaderName() const override;
761 void printFileSummary(StringRef FileStr, ObjectFile &Obj,
762 ArrayRef<std::string> InputFilenames,
763 const Archive *A) override;
764 virtual void printZeroSymbolOtherField(const Elf_Sym &Symbol) const override;
766 void printDefaultRelRelaReloc(const Relocation<ELFT> &R,
767 StringRef SymbolName,
768 StringRef RelocName) override;
770 void printRelocationSectionInfo(const Elf_Shdr &Sec, StringRef Name,
771 const unsigned SecNdx) override;
773 void printSectionGroupMembers(StringRef Name, uint64_t Idx) const override;
775 void printEmptyGroupMessage() const override;
777 private:
778 std::unique_ptr<DictScope> FileScope;
781 } // end anonymous namespace
783 namespace llvm {
785 template <class ELFT>
786 static std::unique_ptr<ObjDumper>
787 createELFDumper(const ELFObjectFile<ELFT> &Obj, ScopedPrinter &Writer) {
788 if (opts::Output == opts::GNU)
789 return std::make_unique<GNUELFDumper<ELFT>>(Obj, Writer);
790 else if (opts::Output == opts::JSON)
791 return std::make_unique<JSONELFDumper<ELFT>>(Obj, Writer);
792 return std::make_unique<LLVMELFDumper<ELFT>>(Obj, Writer);
795 std::unique_ptr<ObjDumper> createELFDumper(const object::ELFObjectFileBase &Obj,
796 ScopedPrinter &Writer) {
797 // Little-endian 32-bit
798 if (const ELF32LEObjectFile *ELFObj = dyn_cast<ELF32LEObjectFile>(&Obj))
799 return createELFDumper(*ELFObj, Writer);
801 // Big-endian 32-bit
802 if (const ELF32BEObjectFile *ELFObj = dyn_cast<ELF32BEObjectFile>(&Obj))
803 return createELFDumper(*ELFObj, Writer);
805 // Little-endian 64-bit
806 if (const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(&Obj))
807 return createELFDumper(*ELFObj, Writer);
809 // Big-endian 64-bit
810 return createELFDumper(*cast<ELF64BEObjectFile>(&Obj), Writer);
813 } // end namespace llvm
815 template <class ELFT>
816 Expected<SmallVector<std::optional<VersionEntry>, 0> *>
817 ELFDumper<ELFT>::getVersionMap() const {
818 // If the VersionMap has already been loaded or if there is no dynamic symtab
819 // or version table, there is nothing to do.
820 if (!VersionMap.empty() || !DynSymRegion || !SymbolVersionSection)
821 return &VersionMap;
823 Expected<SmallVector<std::optional<VersionEntry>, 0>> MapOrErr =
824 Obj.loadVersionMap(SymbolVersionNeedSection, SymbolVersionDefSection);
825 if (MapOrErr)
826 VersionMap = *MapOrErr;
827 else
828 return MapOrErr.takeError();
830 return &VersionMap;
833 template <typename ELFT>
834 Expected<StringRef> ELFDumper<ELFT>::getSymbolVersion(const Elf_Sym &Sym,
835 bool &IsDefault) const {
836 // This is a dynamic symbol. Look in the GNU symbol version table.
837 if (!SymbolVersionSection) {
838 // No version table.
839 IsDefault = false;
840 return "";
843 assert(DynSymRegion && "DynSymRegion has not been initialised");
844 // Determine the position in the symbol table of this entry.
845 size_t EntryIndex = (reinterpret_cast<uintptr_t>(&Sym) -
846 reinterpret_cast<uintptr_t>(DynSymRegion->Addr)) /
847 sizeof(Elf_Sym);
849 // Get the corresponding version index entry.
850 Expected<const Elf_Versym *> EntryOrErr =
851 Obj.template getEntry<Elf_Versym>(*SymbolVersionSection, EntryIndex);
852 if (!EntryOrErr)
853 return EntryOrErr.takeError();
855 unsigned Version = (*EntryOrErr)->vs_index;
856 if (Version == VER_NDX_LOCAL || Version == VER_NDX_GLOBAL) {
857 IsDefault = false;
858 return "";
861 Expected<SmallVector<std::optional<VersionEntry>, 0> *> MapOrErr =
862 getVersionMap();
863 if (!MapOrErr)
864 return MapOrErr.takeError();
866 return Obj.getSymbolVersionByIndex(Version, IsDefault, **MapOrErr,
867 Sym.st_shndx == ELF::SHN_UNDEF);
870 template <typename ELFT>
871 Expected<RelSymbol<ELFT>>
872 ELFDumper<ELFT>::getRelocationTarget(const Relocation<ELFT> &R,
873 const Elf_Shdr *SymTab) const {
874 if (R.Symbol == 0)
875 return RelSymbol<ELFT>(nullptr, "");
877 Expected<const Elf_Sym *> SymOrErr =
878 Obj.template getEntry<Elf_Sym>(*SymTab, R.Symbol);
879 if (!SymOrErr)
880 return createError("unable to read an entry with index " + Twine(R.Symbol) +
881 " from " + describe(*SymTab) + ": " +
882 toString(SymOrErr.takeError()));
883 const Elf_Sym *Sym = *SymOrErr;
884 if (!Sym)
885 return RelSymbol<ELFT>(nullptr, "");
887 Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(*SymTab);
888 if (!StrTableOrErr)
889 return StrTableOrErr.takeError();
891 const Elf_Sym *FirstSym =
892 cantFail(Obj.template getEntry<Elf_Sym>(*SymTab, 0));
893 std::string SymbolName =
894 getFullSymbolName(*Sym, Sym - FirstSym, getShndxTable(SymTab),
895 *StrTableOrErr, SymTab->sh_type == SHT_DYNSYM);
896 return RelSymbol<ELFT>(Sym, SymbolName);
899 template <typename ELFT>
900 ArrayRef<typename ELFT::Word>
901 ELFDumper<ELFT>::getShndxTable(const Elf_Shdr *Symtab) const {
902 if (Symtab) {
903 auto It = ShndxTables.find(Symtab);
904 if (It != ShndxTables.end())
905 return It->second;
907 return {};
910 static std::string maybeDemangle(StringRef Name) {
911 return opts::Demangle ? demangle(std::string(Name)) : Name.str();
914 template <typename ELFT>
915 std::string ELFDumper<ELFT>::getStaticSymbolName(uint32_t Index) const {
916 auto Warn = [&](Error E) -> std::string {
917 reportUniqueWarning("unable to read the name of symbol with index " +
918 Twine(Index) + ": " + toString(std::move(E)));
919 return "<?>";
922 Expected<const typename ELFT::Sym *> SymOrErr =
923 Obj.getSymbol(DotSymtabSec, Index);
924 if (!SymOrErr)
925 return Warn(SymOrErr.takeError());
927 Expected<StringRef> StrTabOrErr = Obj.getStringTableForSymtab(*DotSymtabSec);
928 if (!StrTabOrErr)
929 return Warn(StrTabOrErr.takeError());
931 Expected<StringRef> NameOrErr = (*SymOrErr)->getName(*StrTabOrErr);
932 if (!NameOrErr)
933 return Warn(NameOrErr.takeError());
934 return maybeDemangle(*NameOrErr);
937 template <typename ELFT>
938 std::string ELFDumper<ELFT>::getFullSymbolName(
939 const Elf_Sym &Symbol, unsigned SymIndex, DataRegion<Elf_Word> ShndxTable,
940 std::optional<StringRef> StrTable, bool IsDynamic) const {
941 if (!StrTable)
942 return "<?>";
944 std::string SymbolName;
945 if (Expected<StringRef> NameOrErr = Symbol.getName(*StrTable)) {
946 SymbolName = maybeDemangle(*NameOrErr);
947 } else {
948 reportUniqueWarning(NameOrErr.takeError());
949 return "<?>";
952 if (SymbolName.empty() && Symbol.getType() == ELF::STT_SECTION) {
953 Expected<unsigned> SectionIndex =
954 getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
955 if (!SectionIndex) {
956 reportUniqueWarning(SectionIndex.takeError());
957 return "<?>";
959 Expected<StringRef> NameOrErr = getSymbolSectionName(Symbol, *SectionIndex);
960 if (!NameOrErr) {
961 reportUniqueWarning(NameOrErr.takeError());
962 return ("<section " + Twine(*SectionIndex) + ">").str();
964 return std::string(*NameOrErr);
967 if (!IsDynamic)
968 return SymbolName;
970 bool IsDefault;
971 Expected<StringRef> VersionOrErr = getSymbolVersion(Symbol, IsDefault);
972 if (!VersionOrErr) {
973 reportUniqueWarning(VersionOrErr.takeError());
974 return SymbolName + "@<corrupt>";
977 if (!VersionOrErr->empty()) {
978 SymbolName += (IsDefault ? "@@" : "@");
979 SymbolName += *VersionOrErr;
981 return SymbolName;
984 template <typename ELFT>
985 Expected<unsigned>
986 ELFDumper<ELFT>::getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
987 DataRegion<Elf_Word> ShndxTable) const {
988 unsigned Ndx = Symbol.st_shndx;
989 if (Ndx == SHN_XINDEX)
990 return object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex,
991 ShndxTable);
992 if (Ndx != SHN_UNDEF && Ndx < SHN_LORESERVE)
993 return Ndx;
995 auto CreateErr = [&](const Twine &Name,
996 std::optional<unsigned> Offset = std::nullopt) {
997 std::string Desc;
998 if (Offset)
999 Desc = (Name + "+0x" + Twine::utohexstr(*Offset)).str();
1000 else
1001 Desc = Name.str();
1002 return createError(
1003 "unable to get section index for symbol with st_shndx = 0x" +
1004 Twine::utohexstr(Ndx) + " (" + Desc + ")");
1007 if (Ndx >= ELF::SHN_LOPROC && Ndx <= ELF::SHN_HIPROC)
1008 return CreateErr("SHN_LOPROC", Ndx - ELF::SHN_LOPROC);
1009 if (Ndx >= ELF::SHN_LOOS && Ndx <= ELF::SHN_HIOS)
1010 return CreateErr("SHN_LOOS", Ndx - ELF::SHN_LOOS);
1011 if (Ndx == ELF::SHN_UNDEF)
1012 return CreateErr("SHN_UNDEF");
1013 if (Ndx == ELF::SHN_ABS)
1014 return CreateErr("SHN_ABS");
1015 if (Ndx == ELF::SHN_COMMON)
1016 return CreateErr("SHN_COMMON");
1017 return CreateErr("SHN_LORESERVE", Ndx - SHN_LORESERVE);
1020 template <typename ELFT>
1021 Expected<StringRef>
1022 ELFDumper<ELFT>::getSymbolSectionName(const Elf_Sym &Symbol,
1023 unsigned SectionIndex) const {
1024 Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(SectionIndex);
1025 if (!SecOrErr)
1026 return SecOrErr.takeError();
1027 return Obj.getSectionName(**SecOrErr);
1030 template <class ELFO>
1031 static const typename ELFO::Elf_Shdr *
1032 findNotEmptySectionByAddress(const ELFO &Obj, StringRef FileName,
1033 uint64_t Addr) {
1034 for (const typename ELFO::Elf_Shdr &Shdr : cantFail(Obj.sections()))
1035 if (Shdr.sh_addr == Addr && Shdr.sh_size > 0)
1036 return &Shdr;
1037 return nullptr;
1040 const EnumEntry<unsigned> ElfClass[] = {
1041 {"None", "none", ELF::ELFCLASSNONE},
1042 {"32-bit", "ELF32", ELF::ELFCLASS32},
1043 {"64-bit", "ELF64", ELF::ELFCLASS64},
1046 const EnumEntry<unsigned> ElfDataEncoding[] = {
1047 {"None", "none", ELF::ELFDATANONE},
1048 {"LittleEndian", "2's complement, little endian", ELF::ELFDATA2LSB},
1049 {"BigEndian", "2's complement, big endian", ELF::ELFDATA2MSB},
1052 const EnumEntry<unsigned> ElfObjectFileType[] = {
1053 {"None", "NONE (none)", ELF::ET_NONE},
1054 {"Relocatable", "REL (Relocatable file)", ELF::ET_REL},
1055 {"Executable", "EXEC (Executable file)", ELF::ET_EXEC},
1056 {"SharedObject", "DYN (Shared object file)", ELF::ET_DYN},
1057 {"Core", "CORE (Core file)", ELF::ET_CORE},
1060 const EnumEntry<unsigned> ElfOSABI[] = {
1061 {"SystemV", "UNIX - System V", ELF::ELFOSABI_NONE},
1062 {"HPUX", "UNIX - HP-UX", ELF::ELFOSABI_HPUX},
1063 {"NetBSD", "UNIX - NetBSD", ELF::ELFOSABI_NETBSD},
1064 {"GNU/Linux", "UNIX - GNU", ELF::ELFOSABI_LINUX},
1065 {"GNU/Hurd", "GNU/Hurd", ELF::ELFOSABI_HURD},
1066 {"Solaris", "UNIX - Solaris", ELF::ELFOSABI_SOLARIS},
1067 {"AIX", "UNIX - AIX", ELF::ELFOSABI_AIX},
1068 {"IRIX", "UNIX - IRIX", ELF::ELFOSABI_IRIX},
1069 {"FreeBSD", "UNIX - FreeBSD", ELF::ELFOSABI_FREEBSD},
1070 {"TRU64", "UNIX - TRU64", ELF::ELFOSABI_TRU64},
1071 {"Modesto", "Novell - Modesto", ELF::ELFOSABI_MODESTO},
1072 {"OpenBSD", "UNIX - OpenBSD", ELF::ELFOSABI_OPENBSD},
1073 {"OpenVMS", "VMS - OpenVMS", ELF::ELFOSABI_OPENVMS},
1074 {"NSK", "HP - Non-Stop Kernel", ELF::ELFOSABI_NSK},
1075 {"AROS", "AROS", ELF::ELFOSABI_AROS},
1076 {"FenixOS", "FenixOS", ELF::ELFOSABI_FENIXOS},
1077 {"CloudABI", "CloudABI", ELF::ELFOSABI_CLOUDABI},
1078 {"Standalone", "Standalone App", ELF::ELFOSABI_STANDALONE}
1081 const EnumEntry<unsigned> AMDGPUElfOSABI[] = {
1082 {"AMDGPU_HSA", "AMDGPU - HSA", ELF::ELFOSABI_AMDGPU_HSA},
1083 {"AMDGPU_PAL", "AMDGPU - PAL", ELF::ELFOSABI_AMDGPU_PAL},
1084 {"AMDGPU_MESA3D", "AMDGPU - MESA3D", ELF::ELFOSABI_AMDGPU_MESA3D}
1087 const EnumEntry<unsigned> ARMElfOSABI[] = {
1088 {"ARM", "ARM", ELF::ELFOSABI_ARM}
1091 const EnumEntry<unsigned> C6000ElfOSABI[] = {
1092 {"C6000_ELFABI", "Bare-metal C6000", ELF::ELFOSABI_C6000_ELFABI},
1093 {"C6000_LINUX", "Linux C6000", ELF::ELFOSABI_C6000_LINUX}
1096 const EnumEntry<unsigned> ElfMachineType[] = {
1097 ENUM_ENT(EM_NONE, "None"),
1098 ENUM_ENT(EM_M32, "WE32100"),
1099 ENUM_ENT(EM_SPARC, "Sparc"),
1100 ENUM_ENT(EM_386, "Intel 80386"),
1101 ENUM_ENT(EM_68K, "MC68000"),
1102 ENUM_ENT(EM_88K, "MC88000"),
1103 ENUM_ENT(EM_IAMCU, "EM_IAMCU"),
1104 ENUM_ENT(EM_860, "Intel 80860"),
1105 ENUM_ENT(EM_MIPS, "MIPS R3000"),
1106 ENUM_ENT(EM_S370, "IBM System/370"),
1107 ENUM_ENT(EM_MIPS_RS3_LE, "MIPS R3000 little-endian"),
1108 ENUM_ENT(EM_PARISC, "HPPA"),
1109 ENUM_ENT(EM_VPP500, "Fujitsu VPP500"),
1110 ENUM_ENT(EM_SPARC32PLUS, "Sparc v8+"),
1111 ENUM_ENT(EM_960, "Intel 80960"),
1112 ENUM_ENT(EM_PPC, "PowerPC"),
1113 ENUM_ENT(EM_PPC64, "PowerPC64"),
1114 ENUM_ENT(EM_S390, "IBM S/390"),
1115 ENUM_ENT(EM_SPU, "SPU"),
1116 ENUM_ENT(EM_V800, "NEC V800 series"),
1117 ENUM_ENT(EM_FR20, "Fujistsu FR20"),
1118 ENUM_ENT(EM_RH32, "TRW RH-32"),
1119 ENUM_ENT(EM_RCE, "Motorola RCE"),
1120 ENUM_ENT(EM_ARM, "ARM"),
1121 ENUM_ENT(EM_ALPHA, "EM_ALPHA"),
1122 ENUM_ENT(EM_SH, "Hitachi SH"),
1123 ENUM_ENT(EM_SPARCV9, "Sparc v9"),
1124 ENUM_ENT(EM_TRICORE, "Siemens Tricore"),
1125 ENUM_ENT(EM_ARC, "ARC"),
1126 ENUM_ENT(EM_H8_300, "Hitachi H8/300"),
1127 ENUM_ENT(EM_H8_300H, "Hitachi H8/300H"),
1128 ENUM_ENT(EM_H8S, "Hitachi H8S"),
1129 ENUM_ENT(EM_H8_500, "Hitachi H8/500"),
1130 ENUM_ENT(EM_IA_64, "Intel IA-64"),
1131 ENUM_ENT(EM_MIPS_X, "Stanford MIPS-X"),
1132 ENUM_ENT(EM_COLDFIRE, "Motorola Coldfire"),
1133 ENUM_ENT(EM_68HC12, "Motorola MC68HC12 Microcontroller"),
1134 ENUM_ENT(EM_MMA, "Fujitsu Multimedia Accelerator"),
1135 ENUM_ENT(EM_PCP, "Siemens PCP"),
1136 ENUM_ENT(EM_NCPU, "Sony nCPU embedded RISC processor"),
1137 ENUM_ENT(EM_NDR1, "Denso NDR1 microprocesspr"),
1138 ENUM_ENT(EM_STARCORE, "Motorola Star*Core processor"),
1139 ENUM_ENT(EM_ME16, "Toyota ME16 processor"),
1140 ENUM_ENT(EM_ST100, "STMicroelectronics ST100 processor"),
1141 ENUM_ENT(EM_TINYJ, "Advanced Logic Corp. TinyJ embedded processor"),
1142 ENUM_ENT(EM_X86_64, "Advanced Micro Devices X86-64"),
1143 ENUM_ENT(EM_PDSP, "Sony DSP processor"),
1144 ENUM_ENT(EM_PDP10, "Digital Equipment Corp. PDP-10"),
1145 ENUM_ENT(EM_PDP11, "Digital Equipment Corp. PDP-11"),
1146 ENUM_ENT(EM_FX66, "Siemens FX66 microcontroller"),
1147 ENUM_ENT(EM_ST9PLUS, "STMicroelectronics ST9+ 8/16 bit microcontroller"),
1148 ENUM_ENT(EM_ST7, "STMicroelectronics ST7 8-bit microcontroller"),
1149 ENUM_ENT(EM_68HC16, "Motorola MC68HC16 Microcontroller"),
1150 ENUM_ENT(EM_68HC11, "Motorola MC68HC11 Microcontroller"),
1151 ENUM_ENT(EM_68HC08, "Motorola MC68HC08 Microcontroller"),
1152 ENUM_ENT(EM_68HC05, "Motorola MC68HC05 Microcontroller"),
1153 ENUM_ENT(EM_SVX, "Silicon Graphics SVx"),
1154 ENUM_ENT(EM_ST19, "STMicroelectronics ST19 8-bit microcontroller"),
1155 ENUM_ENT(EM_VAX, "Digital VAX"),
1156 ENUM_ENT(EM_CRIS, "Axis Communications 32-bit embedded processor"),
1157 ENUM_ENT(EM_JAVELIN, "Infineon Technologies 32-bit embedded cpu"),
1158 ENUM_ENT(EM_FIREPATH, "Element 14 64-bit DSP processor"),
1159 ENUM_ENT(EM_ZSP, "LSI Logic's 16-bit DSP processor"),
1160 ENUM_ENT(EM_MMIX, "Donald Knuth's educational 64-bit processor"),
1161 ENUM_ENT(EM_HUANY, "Harvard Universitys's machine-independent object format"),
1162 ENUM_ENT(EM_PRISM, "Vitesse Prism"),
1163 ENUM_ENT(EM_AVR, "Atmel AVR 8-bit microcontroller"),
1164 ENUM_ENT(EM_FR30, "Fujitsu FR30"),
1165 ENUM_ENT(EM_D10V, "Mitsubishi D10V"),
1166 ENUM_ENT(EM_D30V, "Mitsubishi D30V"),
1167 ENUM_ENT(EM_V850, "NEC v850"),
1168 ENUM_ENT(EM_M32R, "Renesas M32R (formerly Mitsubishi M32r)"),
1169 ENUM_ENT(EM_MN10300, "Matsushita MN10300"),
1170 ENUM_ENT(EM_MN10200, "Matsushita MN10200"),
1171 ENUM_ENT(EM_PJ, "picoJava"),
1172 ENUM_ENT(EM_OPENRISC, "OpenRISC 32-bit embedded processor"),
1173 ENUM_ENT(EM_ARC_COMPACT, "EM_ARC_COMPACT"),
1174 ENUM_ENT(EM_XTENSA, "Tensilica Xtensa Processor"),
1175 ENUM_ENT(EM_VIDEOCORE, "Alphamosaic VideoCore processor"),
1176 ENUM_ENT(EM_TMM_GPP, "Thompson Multimedia General Purpose Processor"),
1177 ENUM_ENT(EM_NS32K, "National Semiconductor 32000 series"),
1178 ENUM_ENT(EM_TPC, "Tenor Network TPC processor"),
1179 ENUM_ENT(EM_SNP1K, "EM_SNP1K"),
1180 ENUM_ENT(EM_ST200, "STMicroelectronics ST200 microcontroller"),
1181 ENUM_ENT(EM_IP2K, "Ubicom IP2xxx 8-bit microcontrollers"),
1182 ENUM_ENT(EM_MAX, "MAX Processor"),
1183 ENUM_ENT(EM_CR, "National Semiconductor CompactRISC"),
1184 ENUM_ENT(EM_F2MC16, "Fujitsu F2MC16"),
1185 ENUM_ENT(EM_MSP430, "Texas Instruments msp430 microcontroller"),
1186 ENUM_ENT(EM_BLACKFIN, "Analog Devices Blackfin"),
1187 ENUM_ENT(EM_SE_C33, "S1C33 Family of Seiko Epson processors"),
1188 ENUM_ENT(EM_SEP, "Sharp embedded microprocessor"),
1189 ENUM_ENT(EM_ARCA, "Arca RISC microprocessor"),
1190 ENUM_ENT(EM_UNICORE, "Unicore"),
1191 ENUM_ENT(EM_EXCESS, "eXcess 16/32/64-bit configurable embedded CPU"),
1192 ENUM_ENT(EM_DXP, "Icera Semiconductor Inc. Deep Execution Processor"),
1193 ENUM_ENT(EM_ALTERA_NIOS2, "Altera Nios"),
1194 ENUM_ENT(EM_CRX, "National Semiconductor CRX microprocessor"),
1195 ENUM_ENT(EM_XGATE, "Motorola XGATE embedded processor"),
1196 ENUM_ENT(EM_C166, "Infineon Technologies xc16x"),
1197 ENUM_ENT(EM_M16C, "Renesas M16C"),
1198 ENUM_ENT(EM_DSPIC30F, "Microchip Technology dsPIC30F Digital Signal Controller"),
1199 ENUM_ENT(EM_CE, "Freescale Communication Engine RISC core"),
1200 ENUM_ENT(EM_M32C, "Renesas M32C"),
1201 ENUM_ENT(EM_TSK3000, "Altium TSK3000 core"),
1202 ENUM_ENT(EM_RS08, "Freescale RS08 embedded processor"),
1203 ENUM_ENT(EM_SHARC, "EM_SHARC"),
1204 ENUM_ENT(EM_ECOG2, "Cyan Technology eCOG2 microprocessor"),
1205 ENUM_ENT(EM_SCORE7, "SUNPLUS S+Core"),
1206 ENUM_ENT(EM_DSP24, "New Japan Radio (NJR) 24-bit DSP Processor"),
1207 ENUM_ENT(EM_VIDEOCORE3, "Broadcom VideoCore III processor"),
1208 ENUM_ENT(EM_LATTICEMICO32, "Lattice Mico32"),
1209 ENUM_ENT(EM_SE_C17, "Seiko Epson C17 family"),
1210 ENUM_ENT(EM_TI_C6000, "Texas Instruments TMS320C6000 DSP family"),
1211 ENUM_ENT(EM_TI_C2000, "Texas Instruments TMS320C2000 DSP family"),
1212 ENUM_ENT(EM_TI_C5500, "Texas Instruments TMS320C55x DSP family"),
1213 ENUM_ENT(EM_MMDSP_PLUS, "STMicroelectronics 64bit VLIW Data Signal Processor"),
1214 ENUM_ENT(EM_CYPRESS_M8C, "Cypress M8C microprocessor"),
1215 ENUM_ENT(EM_R32C, "Renesas R32C series microprocessors"),
1216 ENUM_ENT(EM_TRIMEDIA, "NXP Semiconductors TriMedia architecture family"),
1217 ENUM_ENT(EM_HEXAGON, "Qualcomm Hexagon"),
1218 ENUM_ENT(EM_8051, "Intel 8051 and variants"),
1219 ENUM_ENT(EM_STXP7X, "STMicroelectronics STxP7x family"),
1220 ENUM_ENT(EM_NDS32, "Andes Technology compact code size embedded RISC processor family"),
1221 ENUM_ENT(EM_ECOG1, "Cyan Technology eCOG1 microprocessor"),
1222 // FIXME: Following EM_ECOG1X definitions is dead code since EM_ECOG1X has
1223 // an identical number to EM_ECOG1.
1224 ENUM_ENT(EM_ECOG1X, "Cyan Technology eCOG1X family"),
1225 ENUM_ENT(EM_MAXQ30, "Dallas Semiconductor MAXQ30 Core microcontrollers"),
1226 ENUM_ENT(EM_XIMO16, "New Japan Radio (NJR) 16-bit DSP Processor"),
1227 ENUM_ENT(EM_MANIK, "M2000 Reconfigurable RISC Microprocessor"),
1228 ENUM_ENT(EM_CRAYNV2, "Cray Inc. NV2 vector architecture"),
1229 ENUM_ENT(EM_RX, "Renesas RX"),
1230 ENUM_ENT(EM_METAG, "Imagination Technologies Meta processor architecture"),
1231 ENUM_ENT(EM_MCST_ELBRUS, "MCST Elbrus general purpose hardware architecture"),
1232 ENUM_ENT(EM_ECOG16, "Cyan Technology eCOG16 family"),
1233 ENUM_ENT(EM_CR16, "National Semiconductor CompactRISC 16-bit processor"),
1234 ENUM_ENT(EM_ETPU, "Freescale Extended Time Processing Unit"),
1235 ENUM_ENT(EM_SLE9X, "Infineon Technologies SLE9X core"),
1236 ENUM_ENT(EM_L10M, "EM_L10M"),
1237 ENUM_ENT(EM_K10M, "EM_K10M"),
1238 ENUM_ENT(EM_AARCH64, "AArch64"),
1239 ENUM_ENT(EM_AVR32, "Atmel Corporation 32-bit microprocessor family"),
1240 ENUM_ENT(EM_STM8, "STMicroeletronics STM8 8-bit microcontroller"),
1241 ENUM_ENT(EM_TILE64, "Tilera TILE64 multicore architecture family"),
1242 ENUM_ENT(EM_TILEPRO, "Tilera TILEPro multicore architecture family"),
1243 ENUM_ENT(EM_MICROBLAZE, "Xilinx MicroBlaze 32-bit RISC soft processor core"),
1244 ENUM_ENT(EM_CUDA, "NVIDIA CUDA architecture"),
1245 ENUM_ENT(EM_TILEGX, "Tilera TILE-Gx multicore architecture family"),
1246 ENUM_ENT(EM_CLOUDSHIELD, "EM_CLOUDSHIELD"),
1247 ENUM_ENT(EM_COREA_1ST, "EM_COREA_1ST"),
1248 ENUM_ENT(EM_COREA_2ND, "EM_COREA_2ND"),
1249 ENUM_ENT(EM_ARC_COMPACT2, "EM_ARC_COMPACT2"),
1250 ENUM_ENT(EM_OPEN8, "EM_OPEN8"),
1251 ENUM_ENT(EM_RL78, "Renesas RL78"),
1252 ENUM_ENT(EM_VIDEOCORE5, "Broadcom VideoCore V processor"),
1253 ENUM_ENT(EM_78KOR, "EM_78KOR"),
1254 ENUM_ENT(EM_56800EX, "EM_56800EX"),
1255 ENUM_ENT(EM_AMDGPU, "EM_AMDGPU"),
1256 ENUM_ENT(EM_RISCV, "RISC-V"),
1257 ENUM_ENT(EM_LANAI, "EM_LANAI"),
1258 ENUM_ENT(EM_BPF, "EM_BPF"),
1259 ENUM_ENT(EM_VE, "NEC SX-Aurora Vector Engine"),
1260 ENUM_ENT(EM_LOONGARCH, "LoongArch"),
1263 const EnumEntry<unsigned> ElfSymbolBindings[] = {
1264 {"Local", "LOCAL", ELF::STB_LOCAL},
1265 {"Global", "GLOBAL", ELF::STB_GLOBAL},
1266 {"Weak", "WEAK", ELF::STB_WEAK},
1267 {"Unique", "UNIQUE", ELF::STB_GNU_UNIQUE}};
1269 const EnumEntry<unsigned> ElfSymbolVisibilities[] = {
1270 {"DEFAULT", "DEFAULT", ELF::STV_DEFAULT},
1271 {"INTERNAL", "INTERNAL", ELF::STV_INTERNAL},
1272 {"HIDDEN", "HIDDEN", ELF::STV_HIDDEN},
1273 {"PROTECTED", "PROTECTED", ELF::STV_PROTECTED}};
1275 const EnumEntry<unsigned> AMDGPUSymbolTypes[] = {
1276 { "AMDGPU_HSA_KERNEL", ELF::STT_AMDGPU_HSA_KERNEL }
1279 static const char *getGroupType(uint32_t Flag) {
1280 if (Flag & ELF::GRP_COMDAT)
1281 return "COMDAT";
1282 else
1283 return "(unknown)";
1286 const EnumEntry<unsigned> ElfSectionFlags[] = {
1287 ENUM_ENT(SHF_WRITE, "W"),
1288 ENUM_ENT(SHF_ALLOC, "A"),
1289 ENUM_ENT(SHF_EXECINSTR, "X"),
1290 ENUM_ENT(SHF_MERGE, "M"),
1291 ENUM_ENT(SHF_STRINGS, "S"),
1292 ENUM_ENT(SHF_INFO_LINK, "I"),
1293 ENUM_ENT(SHF_LINK_ORDER, "L"),
1294 ENUM_ENT(SHF_OS_NONCONFORMING, "O"),
1295 ENUM_ENT(SHF_GROUP, "G"),
1296 ENUM_ENT(SHF_TLS, "T"),
1297 ENUM_ENT(SHF_COMPRESSED, "C"),
1298 ENUM_ENT(SHF_EXCLUDE, "E"),
1301 const EnumEntry<unsigned> ElfGNUSectionFlags[] = {
1302 ENUM_ENT(SHF_GNU_RETAIN, "R")
1305 const EnumEntry<unsigned> ElfSolarisSectionFlags[] = {
1306 ENUM_ENT(SHF_SUNW_NODISCARD, "R")
1309 const EnumEntry<unsigned> ElfXCoreSectionFlags[] = {
1310 ENUM_ENT(XCORE_SHF_CP_SECTION, ""),
1311 ENUM_ENT(XCORE_SHF_DP_SECTION, "")
1314 const EnumEntry<unsigned> ElfARMSectionFlags[] = {
1315 ENUM_ENT(SHF_ARM_PURECODE, "y")
1318 const EnumEntry<unsigned> ElfHexagonSectionFlags[] = {
1319 ENUM_ENT(SHF_HEX_GPREL, "")
1322 const EnumEntry<unsigned> ElfMipsSectionFlags[] = {
1323 ENUM_ENT(SHF_MIPS_NODUPES, ""),
1324 ENUM_ENT(SHF_MIPS_NAMES, ""),
1325 ENUM_ENT(SHF_MIPS_LOCAL, ""),
1326 ENUM_ENT(SHF_MIPS_NOSTRIP, ""),
1327 ENUM_ENT(SHF_MIPS_GPREL, ""),
1328 ENUM_ENT(SHF_MIPS_MERGE, ""),
1329 ENUM_ENT(SHF_MIPS_ADDR, ""),
1330 ENUM_ENT(SHF_MIPS_STRING, "")
1333 const EnumEntry<unsigned> ElfX86_64SectionFlags[] = {
1334 ENUM_ENT(SHF_X86_64_LARGE, "l")
1337 static std::vector<EnumEntry<unsigned>>
1338 getSectionFlagsForTarget(unsigned EOSAbi, unsigned EMachine) {
1339 std::vector<EnumEntry<unsigned>> Ret(std::begin(ElfSectionFlags),
1340 std::end(ElfSectionFlags));
1341 switch (EOSAbi) {
1342 case ELFOSABI_SOLARIS:
1343 Ret.insert(Ret.end(), std::begin(ElfSolarisSectionFlags),
1344 std::end(ElfSolarisSectionFlags));
1345 break;
1346 default:
1347 Ret.insert(Ret.end(), std::begin(ElfGNUSectionFlags),
1348 std::end(ElfGNUSectionFlags));
1349 break;
1351 switch (EMachine) {
1352 case EM_ARM:
1353 Ret.insert(Ret.end(), std::begin(ElfARMSectionFlags),
1354 std::end(ElfARMSectionFlags));
1355 break;
1356 case EM_HEXAGON:
1357 Ret.insert(Ret.end(), std::begin(ElfHexagonSectionFlags),
1358 std::end(ElfHexagonSectionFlags));
1359 break;
1360 case EM_MIPS:
1361 Ret.insert(Ret.end(), std::begin(ElfMipsSectionFlags),
1362 std::end(ElfMipsSectionFlags));
1363 break;
1364 case EM_X86_64:
1365 Ret.insert(Ret.end(), std::begin(ElfX86_64SectionFlags),
1366 std::end(ElfX86_64SectionFlags));
1367 break;
1368 case EM_XCORE:
1369 Ret.insert(Ret.end(), std::begin(ElfXCoreSectionFlags),
1370 std::end(ElfXCoreSectionFlags));
1371 break;
1372 default:
1373 break;
1375 return Ret;
1378 static std::string getGNUFlags(unsigned EOSAbi, unsigned EMachine,
1379 uint64_t Flags) {
1380 // Here we are trying to build the flags string in the same way as GNU does.
1381 // It is not that straightforward. Imagine we have sh_flags == 0x90000000.
1382 // SHF_EXCLUDE ("E") has a value of 0x80000000 and SHF_MASKPROC is 0xf0000000.
1383 // GNU readelf will not print "E" or "Ep" in this case, but will print just
1384 // "p". It only will print "E" when no other processor flag is set.
1385 std::string Str;
1386 bool HasUnknownFlag = false;
1387 bool HasOSFlag = false;
1388 bool HasProcFlag = false;
1389 std::vector<EnumEntry<unsigned>> FlagsList =
1390 getSectionFlagsForTarget(EOSAbi, EMachine);
1391 while (Flags) {
1392 // Take the least significant bit as a flag.
1393 uint64_t Flag = Flags & -Flags;
1394 Flags -= Flag;
1396 // Find the flag in the known flags list.
1397 auto I = llvm::find_if(FlagsList, [=](const EnumEntry<unsigned> &E) {
1398 // Flags with empty names are not printed in GNU style output.
1399 return E.Value == Flag && !E.AltName.empty();
1401 if (I != FlagsList.end()) {
1402 Str += I->AltName;
1403 continue;
1406 // If we did not find a matching regular flag, then we deal with an OS
1407 // specific flag, processor specific flag or an unknown flag.
1408 if (Flag & ELF::SHF_MASKOS) {
1409 HasOSFlag = true;
1410 Flags &= ~ELF::SHF_MASKOS;
1411 } else if (Flag & ELF::SHF_MASKPROC) {
1412 HasProcFlag = true;
1413 // Mask off all the processor-specific bits. This removes the SHF_EXCLUDE
1414 // bit if set so that it doesn't also get printed.
1415 Flags &= ~ELF::SHF_MASKPROC;
1416 } else {
1417 HasUnknownFlag = true;
1421 // "o", "p" and "x" are printed last.
1422 if (HasOSFlag)
1423 Str += "o";
1424 if (HasProcFlag)
1425 Str += "p";
1426 if (HasUnknownFlag)
1427 Str += "x";
1428 return Str;
1431 static StringRef segmentTypeToString(unsigned Arch, unsigned Type) {
1432 // Check potentially overlapped processor-specific program header type.
1433 switch (Arch) {
1434 case ELF::EM_ARM:
1435 switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_ARM_EXIDX); }
1436 break;
1437 case ELF::EM_MIPS:
1438 case ELF::EM_MIPS_RS3_LE:
1439 switch (Type) {
1440 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_REGINFO);
1441 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_RTPROC);
1442 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_OPTIONS);
1443 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_ABIFLAGS);
1445 break;
1446 case ELF::EM_RISCV:
1447 switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_RISCV_ATTRIBUTES); }
1450 switch (Type) {
1451 LLVM_READOBJ_ENUM_CASE(ELF, PT_NULL);
1452 LLVM_READOBJ_ENUM_CASE(ELF, PT_LOAD);
1453 LLVM_READOBJ_ENUM_CASE(ELF, PT_DYNAMIC);
1454 LLVM_READOBJ_ENUM_CASE(ELF, PT_INTERP);
1455 LLVM_READOBJ_ENUM_CASE(ELF, PT_NOTE);
1456 LLVM_READOBJ_ENUM_CASE(ELF, PT_SHLIB);
1457 LLVM_READOBJ_ENUM_CASE(ELF, PT_PHDR);
1458 LLVM_READOBJ_ENUM_CASE(ELF, PT_TLS);
1460 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_EH_FRAME);
1461 LLVM_READOBJ_ENUM_CASE(ELF, PT_SUNW_UNWIND);
1463 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_STACK);
1464 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_RELRO);
1465 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_PROPERTY);
1467 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_MUTABLE);
1468 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_RANDOMIZE);
1469 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_WXNEEDED);
1470 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_BOOTDATA);
1471 default:
1472 return "";
1476 static std::string getGNUPtType(unsigned Arch, unsigned Type) {
1477 StringRef Seg = segmentTypeToString(Arch, Type);
1478 if (Seg.empty())
1479 return std::string("<unknown>: ") + to_string(format_hex(Type, 1));
1481 // E.g. "PT_ARM_EXIDX" -> "EXIDX".
1482 if (Seg.consume_front("PT_ARM_"))
1483 return Seg.str();
1485 // E.g. "PT_MIPS_REGINFO" -> "REGINFO".
1486 if (Seg.consume_front("PT_MIPS_"))
1487 return Seg.str();
1489 // E.g. "PT_RISCV_ATTRIBUTES"
1490 if (Seg.consume_front("PT_RISCV_"))
1491 return Seg.str();
1493 // E.g. "PT_LOAD" -> "LOAD".
1494 assert(Seg.startswith("PT_"));
1495 return Seg.drop_front(3).str();
1498 const EnumEntry<unsigned> ElfSegmentFlags[] = {
1499 LLVM_READOBJ_ENUM_ENT(ELF, PF_X),
1500 LLVM_READOBJ_ENUM_ENT(ELF, PF_W),
1501 LLVM_READOBJ_ENUM_ENT(ELF, PF_R)
1504 const EnumEntry<unsigned> ElfHeaderMipsFlags[] = {
1505 ENUM_ENT(EF_MIPS_NOREORDER, "noreorder"),
1506 ENUM_ENT(EF_MIPS_PIC, "pic"),
1507 ENUM_ENT(EF_MIPS_CPIC, "cpic"),
1508 ENUM_ENT(EF_MIPS_ABI2, "abi2"),
1509 ENUM_ENT(EF_MIPS_32BITMODE, "32bitmode"),
1510 ENUM_ENT(EF_MIPS_FP64, "fp64"),
1511 ENUM_ENT(EF_MIPS_NAN2008, "nan2008"),
1512 ENUM_ENT(EF_MIPS_ABI_O32, "o32"),
1513 ENUM_ENT(EF_MIPS_ABI_O64, "o64"),
1514 ENUM_ENT(EF_MIPS_ABI_EABI32, "eabi32"),
1515 ENUM_ENT(EF_MIPS_ABI_EABI64, "eabi64"),
1516 ENUM_ENT(EF_MIPS_MACH_3900, "3900"),
1517 ENUM_ENT(EF_MIPS_MACH_4010, "4010"),
1518 ENUM_ENT(EF_MIPS_MACH_4100, "4100"),
1519 ENUM_ENT(EF_MIPS_MACH_4650, "4650"),
1520 ENUM_ENT(EF_MIPS_MACH_4120, "4120"),
1521 ENUM_ENT(EF_MIPS_MACH_4111, "4111"),
1522 ENUM_ENT(EF_MIPS_MACH_SB1, "sb1"),
1523 ENUM_ENT(EF_MIPS_MACH_OCTEON, "octeon"),
1524 ENUM_ENT(EF_MIPS_MACH_XLR, "xlr"),
1525 ENUM_ENT(EF_MIPS_MACH_OCTEON2, "octeon2"),
1526 ENUM_ENT(EF_MIPS_MACH_OCTEON3, "octeon3"),
1527 ENUM_ENT(EF_MIPS_MACH_5400, "5400"),
1528 ENUM_ENT(EF_MIPS_MACH_5900, "5900"),
1529 ENUM_ENT(EF_MIPS_MACH_5500, "5500"),
1530 ENUM_ENT(EF_MIPS_MACH_9000, "9000"),
1531 ENUM_ENT(EF_MIPS_MACH_LS2E, "loongson-2e"),
1532 ENUM_ENT(EF_MIPS_MACH_LS2F, "loongson-2f"),
1533 ENUM_ENT(EF_MIPS_MACH_LS3A, "loongson-3a"),
1534 ENUM_ENT(EF_MIPS_MICROMIPS, "micromips"),
1535 ENUM_ENT(EF_MIPS_ARCH_ASE_M16, "mips16"),
1536 ENUM_ENT(EF_MIPS_ARCH_ASE_MDMX, "mdmx"),
1537 ENUM_ENT(EF_MIPS_ARCH_1, "mips1"),
1538 ENUM_ENT(EF_MIPS_ARCH_2, "mips2"),
1539 ENUM_ENT(EF_MIPS_ARCH_3, "mips3"),
1540 ENUM_ENT(EF_MIPS_ARCH_4, "mips4"),
1541 ENUM_ENT(EF_MIPS_ARCH_5, "mips5"),
1542 ENUM_ENT(EF_MIPS_ARCH_32, "mips32"),
1543 ENUM_ENT(EF_MIPS_ARCH_64, "mips64"),
1544 ENUM_ENT(EF_MIPS_ARCH_32R2, "mips32r2"),
1545 ENUM_ENT(EF_MIPS_ARCH_64R2, "mips64r2"),
1546 ENUM_ENT(EF_MIPS_ARCH_32R6, "mips32r6"),
1547 ENUM_ENT(EF_MIPS_ARCH_64R6, "mips64r6")
1550 const EnumEntry<unsigned> ElfHeaderAMDGPUFlagsABIVersion3[] = {
1551 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_NONE),
1552 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R600),
1553 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R630),
1554 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RS880),
1555 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV670),
1556 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV710),
1557 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV730),
1558 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV770),
1559 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CEDAR),
1560 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CYPRESS),
1561 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_JUNIPER),
1562 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_REDWOOD),
1563 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_SUMO),
1564 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_BARTS),
1565 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAICOS),
1566 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAYMAN),
1567 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_TURKS),
1568 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX600),
1569 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX601),
1570 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX602),
1571 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX700),
1572 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX701),
1573 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX702),
1574 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX703),
1575 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX704),
1576 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX705),
1577 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX801),
1578 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX802),
1579 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX803),
1580 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX805),
1581 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX810),
1582 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX900),
1583 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX902),
1584 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX904),
1585 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX906),
1586 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX908),
1587 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX909),
1588 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX90A),
1589 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX90C),
1590 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX940),
1591 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX941),
1592 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX942),
1593 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1010),
1594 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1011),
1595 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1012),
1596 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1013),
1597 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1030),
1598 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1031),
1599 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1032),
1600 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1033),
1601 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1034),
1602 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1035),
1603 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1036),
1604 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1100),
1605 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1101),
1606 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1102),
1607 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1103),
1608 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_V3),
1609 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_SRAMECC_V3)
1612 const EnumEntry<unsigned> ElfHeaderAMDGPUFlagsABIVersion4[] = {
1613 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_NONE),
1614 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R600),
1615 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R630),
1616 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RS880),
1617 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV670),
1618 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV710),
1619 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV730),
1620 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV770),
1621 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CEDAR),
1622 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CYPRESS),
1623 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_JUNIPER),
1624 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_REDWOOD),
1625 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_SUMO),
1626 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_BARTS),
1627 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAICOS),
1628 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAYMAN),
1629 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_TURKS),
1630 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX600),
1631 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX601),
1632 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX602),
1633 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX700),
1634 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX701),
1635 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX702),
1636 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX703),
1637 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX704),
1638 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX705),
1639 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX801),
1640 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX802),
1641 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX803),
1642 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX805),
1643 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX810),
1644 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX900),
1645 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX902),
1646 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX904),
1647 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX906),
1648 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX908),
1649 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX909),
1650 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX90A),
1651 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX90C),
1652 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX940),
1653 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX941),
1654 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX942),
1655 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1010),
1656 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1011),
1657 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1012),
1658 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1013),
1659 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1030),
1660 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1031),
1661 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1032),
1662 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1033),
1663 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1034),
1664 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1035),
1665 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1036),
1666 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1100),
1667 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1101),
1668 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1102),
1669 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1103),
1670 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_ANY_V4),
1671 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_OFF_V4),
1672 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_XNACK_ON_V4),
1673 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_SRAMECC_ANY_V4),
1674 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_SRAMECC_OFF_V4),
1675 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_FEATURE_SRAMECC_ON_V4)
1678 const EnumEntry<unsigned> ElfHeaderRISCVFlags[] = {
1679 ENUM_ENT(EF_RISCV_RVC, "RVC"),
1680 ENUM_ENT(EF_RISCV_FLOAT_ABI_SINGLE, "single-float ABI"),
1681 ENUM_ENT(EF_RISCV_FLOAT_ABI_DOUBLE, "double-float ABI"),
1682 ENUM_ENT(EF_RISCV_FLOAT_ABI_QUAD, "quad-float ABI"),
1683 ENUM_ENT(EF_RISCV_RVE, "RVE"),
1684 ENUM_ENT(EF_RISCV_TSO, "TSO"),
1687 const EnumEntry<unsigned> ElfHeaderAVRFlags[] = {
1688 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR1),
1689 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR2),
1690 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR25),
1691 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR3),
1692 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR31),
1693 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR35),
1694 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR4),
1695 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR5),
1696 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR51),
1697 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVR6),
1698 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_AVRTINY),
1699 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA1),
1700 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA2),
1701 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA3),
1702 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA4),
1703 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA5),
1704 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA6),
1705 LLVM_READOBJ_ENUM_ENT(ELF, EF_AVR_ARCH_XMEGA7),
1706 ENUM_ENT(EF_AVR_LINKRELAX_PREPARED, "relaxable"),
1709 const EnumEntry<unsigned> ElfHeaderLoongArchFlags[] = {
1710 ENUM_ENT(EF_LOONGARCH_ABI_SOFT_FLOAT, "SOFT-FLOAT"),
1711 ENUM_ENT(EF_LOONGARCH_ABI_SINGLE_FLOAT, "SINGLE-FLOAT"),
1712 ENUM_ENT(EF_LOONGARCH_ABI_DOUBLE_FLOAT, "DOUBLE-FLOAT"),
1713 ENUM_ENT(EF_LOONGARCH_OBJABI_V0, "OBJ-v0"),
1714 ENUM_ENT(EF_LOONGARCH_OBJABI_V1, "OBJ-v1"),
1717 static const EnumEntry<unsigned> ElfHeaderXtensaFlags[] = {
1718 LLVM_READOBJ_ENUM_ENT(ELF, EF_XTENSA_MACH_NONE),
1719 LLVM_READOBJ_ENUM_ENT(ELF, EF_XTENSA_XT_INSN),
1720 LLVM_READOBJ_ENUM_ENT(ELF, EF_XTENSA_XT_LIT)
1723 const EnumEntry<unsigned> ElfSymOtherFlags[] = {
1724 LLVM_READOBJ_ENUM_ENT(ELF, STV_INTERNAL),
1725 LLVM_READOBJ_ENUM_ENT(ELF, STV_HIDDEN),
1726 LLVM_READOBJ_ENUM_ENT(ELF, STV_PROTECTED)
1729 const EnumEntry<unsigned> ElfMipsSymOtherFlags[] = {
1730 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL),
1731 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT),
1732 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PIC),
1733 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MICROMIPS)
1736 const EnumEntry<unsigned> ElfAArch64SymOtherFlags[] = {
1737 LLVM_READOBJ_ENUM_ENT(ELF, STO_AARCH64_VARIANT_PCS)
1740 const EnumEntry<unsigned> ElfMips16SymOtherFlags[] = {
1741 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL),
1742 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT),
1743 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MIPS16)
1746 const EnumEntry<unsigned> ElfRISCVSymOtherFlags[] = {
1747 LLVM_READOBJ_ENUM_ENT(ELF, STO_RISCV_VARIANT_CC)};
1749 static const char *getElfMipsOptionsOdkType(unsigned Odk) {
1750 switch (Odk) {
1751 LLVM_READOBJ_ENUM_CASE(ELF, ODK_NULL);
1752 LLVM_READOBJ_ENUM_CASE(ELF, ODK_REGINFO);
1753 LLVM_READOBJ_ENUM_CASE(ELF, ODK_EXCEPTIONS);
1754 LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAD);
1755 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWPATCH);
1756 LLVM_READOBJ_ENUM_CASE(ELF, ODK_FILL);
1757 LLVM_READOBJ_ENUM_CASE(ELF, ODK_TAGS);
1758 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWAND);
1759 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWOR);
1760 LLVM_READOBJ_ENUM_CASE(ELF, ODK_GP_GROUP);
1761 LLVM_READOBJ_ENUM_CASE(ELF, ODK_IDENT);
1762 LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAGESIZE);
1763 default:
1764 return "Unknown";
1768 template <typename ELFT>
1769 std::pair<const typename ELFT::Phdr *, const typename ELFT::Shdr *>
1770 ELFDumper<ELFT>::findDynamic() {
1771 // Try to locate the PT_DYNAMIC header.
1772 const Elf_Phdr *DynamicPhdr = nullptr;
1773 if (Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = Obj.program_headers()) {
1774 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
1775 if (Phdr.p_type != ELF::PT_DYNAMIC)
1776 continue;
1777 DynamicPhdr = &Phdr;
1778 break;
1780 } else {
1781 reportUniqueWarning(
1782 "unable to read program headers to locate the PT_DYNAMIC segment: " +
1783 toString(PhdrsOrErr.takeError()));
1786 // Try to locate the .dynamic section in the sections header table.
1787 const Elf_Shdr *DynamicSec = nullptr;
1788 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
1789 if (Sec.sh_type != ELF::SHT_DYNAMIC)
1790 continue;
1791 DynamicSec = &Sec;
1792 break;
1795 if (DynamicPhdr && ((DynamicPhdr->p_offset + DynamicPhdr->p_filesz >
1796 ObjF.getMemoryBufferRef().getBufferSize()) ||
1797 (DynamicPhdr->p_offset + DynamicPhdr->p_filesz <
1798 DynamicPhdr->p_offset))) {
1799 reportUniqueWarning(
1800 "PT_DYNAMIC segment offset (0x" +
1801 Twine::utohexstr(DynamicPhdr->p_offset) + ") + file size (0x" +
1802 Twine::utohexstr(DynamicPhdr->p_filesz) +
1803 ") exceeds the size of the file (0x" +
1804 Twine::utohexstr(ObjF.getMemoryBufferRef().getBufferSize()) + ")");
1805 // Don't use the broken dynamic header.
1806 DynamicPhdr = nullptr;
1809 if (DynamicPhdr && DynamicSec) {
1810 if (DynamicSec->sh_addr + DynamicSec->sh_size >
1811 DynamicPhdr->p_vaddr + DynamicPhdr->p_memsz ||
1812 DynamicSec->sh_addr < DynamicPhdr->p_vaddr)
1813 reportUniqueWarning(describe(*DynamicSec) +
1814 " is not contained within the "
1815 "PT_DYNAMIC segment");
1817 if (DynamicSec->sh_addr != DynamicPhdr->p_vaddr)
1818 reportUniqueWarning(describe(*DynamicSec) + " is not at the start of "
1819 "PT_DYNAMIC segment");
1822 return std::make_pair(DynamicPhdr, DynamicSec);
1825 template <typename ELFT>
1826 void ELFDumper<ELFT>::loadDynamicTable() {
1827 const Elf_Phdr *DynamicPhdr;
1828 const Elf_Shdr *DynamicSec;
1829 std::tie(DynamicPhdr, DynamicSec) = findDynamic();
1830 if (!DynamicPhdr && !DynamicSec)
1831 return;
1833 DynRegionInfo FromPhdr(ObjF, *this);
1834 bool IsPhdrTableValid = false;
1835 if (DynamicPhdr) {
1836 // Use cantFail(), because p_offset/p_filesz fields of a PT_DYNAMIC are
1837 // validated in findDynamic() and so createDRI() is not expected to fail.
1838 FromPhdr = cantFail(createDRI(DynamicPhdr->p_offset, DynamicPhdr->p_filesz,
1839 sizeof(Elf_Dyn)));
1840 FromPhdr.SizePrintName = "PT_DYNAMIC size";
1841 FromPhdr.EntSizePrintName = "";
1842 IsPhdrTableValid = !FromPhdr.template getAsArrayRef<Elf_Dyn>().empty();
1845 // Locate the dynamic table described in a section header.
1846 // Ignore sh_entsize and use the expected value for entry size explicitly.
1847 // This allows us to dump dynamic sections with a broken sh_entsize
1848 // field.
1849 DynRegionInfo FromSec(ObjF, *this);
1850 bool IsSecTableValid = false;
1851 if (DynamicSec) {
1852 Expected<DynRegionInfo> RegOrErr =
1853 createDRI(DynamicSec->sh_offset, DynamicSec->sh_size, sizeof(Elf_Dyn));
1854 if (RegOrErr) {
1855 FromSec = *RegOrErr;
1856 FromSec.Context = describe(*DynamicSec);
1857 FromSec.EntSizePrintName = "";
1858 IsSecTableValid = !FromSec.template getAsArrayRef<Elf_Dyn>().empty();
1859 } else {
1860 reportUniqueWarning("unable to read the dynamic table from " +
1861 describe(*DynamicSec) + ": " +
1862 toString(RegOrErr.takeError()));
1866 // When we only have information from one of the SHT_DYNAMIC section header or
1867 // PT_DYNAMIC program header, just use that.
1868 if (!DynamicPhdr || !DynamicSec) {
1869 if ((DynamicPhdr && IsPhdrTableValid) || (DynamicSec && IsSecTableValid)) {
1870 DynamicTable = DynamicPhdr ? FromPhdr : FromSec;
1871 parseDynamicTable();
1872 } else {
1873 reportUniqueWarning("no valid dynamic table was found");
1875 return;
1878 // At this point we have tables found from the section header and from the
1879 // dynamic segment. Usually they match, but we have to do sanity checks to
1880 // verify that.
1882 if (FromPhdr.Addr != FromSec.Addr)
1883 reportUniqueWarning("SHT_DYNAMIC section header and PT_DYNAMIC "
1884 "program header disagree about "
1885 "the location of the dynamic table");
1887 if (!IsPhdrTableValid && !IsSecTableValid) {
1888 reportUniqueWarning("no valid dynamic table was found");
1889 return;
1892 // Information in the PT_DYNAMIC program header has priority over the
1893 // information in a section header.
1894 if (IsPhdrTableValid) {
1895 if (!IsSecTableValid)
1896 reportUniqueWarning(
1897 "SHT_DYNAMIC dynamic table is invalid: PT_DYNAMIC will be used");
1898 DynamicTable = FromPhdr;
1899 } else {
1900 reportUniqueWarning(
1901 "PT_DYNAMIC dynamic table is invalid: SHT_DYNAMIC will be used");
1902 DynamicTable = FromSec;
1905 parseDynamicTable();
1908 template <typename ELFT>
1909 ELFDumper<ELFT>::ELFDumper(const object::ELFObjectFile<ELFT> &O,
1910 ScopedPrinter &Writer)
1911 : ObjDumper(Writer, O.getFileName()), ObjF(O), Obj(O.getELFFile()),
1912 FileName(O.getFileName()), DynRelRegion(O, *this),
1913 DynRelaRegion(O, *this), DynRelrRegion(O, *this),
1914 DynPLTRelRegion(O, *this), DynSymTabShndxRegion(O, *this),
1915 DynamicTable(O, *this) {
1916 if (!O.IsContentValid())
1917 return;
1919 typename ELFT::ShdrRange Sections = cantFail(Obj.sections());
1920 for (const Elf_Shdr &Sec : Sections) {
1921 switch (Sec.sh_type) {
1922 case ELF::SHT_SYMTAB:
1923 if (!DotSymtabSec)
1924 DotSymtabSec = &Sec;
1925 break;
1926 case ELF::SHT_DYNSYM:
1927 if (!DotDynsymSec)
1928 DotDynsymSec = &Sec;
1930 if (!DynSymRegion) {
1931 Expected<DynRegionInfo> RegOrErr =
1932 createDRI(Sec.sh_offset, Sec.sh_size, Sec.sh_entsize);
1933 if (RegOrErr) {
1934 DynSymRegion = *RegOrErr;
1935 DynSymRegion->Context = describe(Sec);
1937 if (Expected<StringRef> E = Obj.getStringTableForSymtab(Sec))
1938 DynamicStringTable = *E;
1939 else
1940 reportUniqueWarning("unable to get the string table for the " +
1941 describe(Sec) + ": " + toString(E.takeError()));
1942 } else {
1943 reportUniqueWarning("unable to read dynamic symbols from " +
1944 describe(Sec) + ": " +
1945 toString(RegOrErr.takeError()));
1948 break;
1949 case ELF::SHT_SYMTAB_SHNDX: {
1950 uint32_t SymtabNdx = Sec.sh_link;
1951 if (SymtabNdx >= Sections.size()) {
1952 reportUniqueWarning(
1953 "unable to get the associated symbol table for " + describe(Sec) +
1954 ": sh_link (" + Twine(SymtabNdx) +
1955 ") is greater than or equal to the total number of sections (" +
1956 Twine(Sections.size()) + ")");
1957 continue;
1960 if (Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
1961 Obj.getSHNDXTable(Sec)) {
1962 if (!ShndxTables.insert({&Sections[SymtabNdx], *ShndxTableOrErr})
1963 .second)
1964 reportUniqueWarning(
1965 "multiple SHT_SYMTAB_SHNDX sections are linked to " +
1966 describe(Sec));
1967 } else {
1968 reportUniqueWarning(ShndxTableOrErr.takeError());
1970 break;
1972 case ELF::SHT_GNU_versym:
1973 if (!SymbolVersionSection)
1974 SymbolVersionSection = &Sec;
1975 break;
1976 case ELF::SHT_GNU_verdef:
1977 if (!SymbolVersionDefSection)
1978 SymbolVersionDefSection = &Sec;
1979 break;
1980 case ELF::SHT_GNU_verneed:
1981 if (!SymbolVersionNeedSection)
1982 SymbolVersionNeedSection = &Sec;
1983 break;
1984 case ELF::SHT_LLVM_ADDRSIG:
1985 if (!DotAddrsigSec)
1986 DotAddrsigSec = &Sec;
1987 break;
1991 loadDynamicTable();
1994 template <typename ELFT> void ELFDumper<ELFT>::parseDynamicTable() {
1995 auto toMappedAddr = [&](uint64_t Tag, uint64_t VAddr) -> const uint8_t * {
1996 auto MappedAddrOrError = Obj.toMappedAddr(VAddr, [&](const Twine &Msg) {
1997 this->reportUniqueWarning(Msg);
1998 return Error::success();
2000 if (!MappedAddrOrError) {
2001 this->reportUniqueWarning("unable to parse DT_" +
2002 Obj.getDynamicTagAsString(Tag) + ": " +
2003 llvm::toString(MappedAddrOrError.takeError()));
2004 return nullptr;
2006 return MappedAddrOrError.get();
2009 const char *StringTableBegin = nullptr;
2010 uint64_t StringTableSize = 0;
2011 std::optional<DynRegionInfo> DynSymFromTable;
2012 for (const Elf_Dyn &Dyn : dynamic_table()) {
2013 switch (Dyn.d_tag) {
2014 case ELF::DT_HASH:
2015 HashTable = reinterpret_cast<const Elf_Hash *>(
2016 toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
2017 break;
2018 case ELF::DT_GNU_HASH:
2019 GnuHashTable = reinterpret_cast<const Elf_GnuHash *>(
2020 toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
2021 break;
2022 case ELF::DT_STRTAB:
2023 StringTableBegin = reinterpret_cast<const char *>(
2024 toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
2025 break;
2026 case ELF::DT_STRSZ:
2027 StringTableSize = Dyn.getVal();
2028 break;
2029 case ELF::DT_SYMTAB: {
2030 // If we can't map the DT_SYMTAB value to an address (e.g. when there are
2031 // no program headers), we ignore its value.
2032 if (const uint8_t *VA = toMappedAddr(Dyn.getTag(), Dyn.getPtr())) {
2033 DynSymFromTable.emplace(ObjF, *this);
2034 DynSymFromTable->Addr = VA;
2035 DynSymFromTable->EntSize = sizeof(Elf_Sym);
2036 DynSymFromTable->EntSizePrintName = "";
2038 break;
2040 case ELF::DT_SYMENT: {
2041 uint64_t Val = Dyn.getVal();
2042 if (Val != sizeof(Elf_Sym))
2043 this->reportUniqueWarning("DT_SYMENT value of 0x" +
2044 Twine::utohexstr(Val) +
2045 " is not the size of a symbol (0x" +
2046 Twine::utohexstr(sizeof(Elf_Sym)) + ")");
2047 break;
2049 case ELF::DT_RELA:
2050 DynRelaRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2051 break;
2052 case ELF::DT_RELASZ:
2053 DynRelaRegion.Size = Dyn.getVal();
2054 DynRelaRegion.SizePrintName = "DT_RELASZ value";
2055 break;
2056 case ELF::DT_RELAENT:
2057 DynRelaRegion.EntSize = Dyn.getVal();
2058 DynRelaRegion.EntSizePrintName = "DT_RELAENT value";
2059 break;
2060 case ELF::DT_SONAME:
2061 SONameOffset = Dyn.getVal();
2062 break;
2063 case ELF::DT_REL:
2064 DynRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2065 break;
2066 case ELF::DT_RELSZ:
2067 DynRelRegion.Size = Dyn.getVal();
2068 DynRelRegion.SizePrintName = "DT_RELSZ value";
2069 break;
2070 case ELF::DT_RELENT:
2071 DynRelRegion.EntSize = Dyn.getVal();
2072 DynRelRegion.EntSizePrintName = "DT_RELENT value";
2073 break;
2074 case ELF::DT_RELR:
2075 case ELF::DT_ANDROID_RELR:
2076 DynRelrRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2077 break;
2078 case ELF::DT_RELRSZ:
2079 case ELF::DT_ANDROID_RELRSZ:
2080 DynRelrRegion.Size = Dyn.getVal();
2081 DynRelrRegion.SizePrintName = Dyn.d_tag == ELF::DT_RELRSZ
2082 ? "DT_RELRSZ value"
2083 : "DT_ANDROID_RELRSZ value";
2084 break;
2085 case ELF::DT_RELRENT:
2086 case ELF::DT_ANDROID_RELRENT:
2087 DynRelrRegion.EntSize = Dyn.getVal();
2088 DynRelrRegion.EntSizePrintName = Dyn.d_tag == ELF::DT_RELRENT
2089 ? "DT_RELRENT value"
2090 : "DT_ANDROID_RELRENT value";
2091 break;
2092 case ELF::DT_PLTREL:
2093 if (Dyn.getVal() == DT_REL)
2094 DynPLTRelRegion.EntSize = sizeof(Elf_Rel);
2095 else if (Dyn.getVal() == DT_RELA)
2096 DynPLTRelRegion.EntSize = sizeof(Elf_Rela);
2097 else
2098 reportUniqueWarning(Twine("unknown DT_PLTREL value of ") +
2099 Twine((uint64_t)Dyn.getVal()));
2100 DynPLTRelRegion.EntSizePrintName = "PLTREL entry size";
2101 break;
2102 case ELF::DT_JMPREL:
2103 DynPLTRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2104 break;
2105 case ELF::DT_PLTRELSZ:
2106 DynPLTRelRegion.Size = Dyn.getVal();
2107 DynPLTRelRegion.SizePrintName = "DT_PLTRELSZ value";
2108 break;
2109 case ELF::DT_SYMTAB_SHNDX:
2110 DynSymTabShndxRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2111 DynSymTabShndxRegion.EntSize = sizeof(Elf_Word);
2112 break;
2116 if (StringTableBegin) {
2117 const uint64_t FileSize = Obj.getBufSize();
2118 const uint64_t Offset = (const uint8_t *)StringTableBegin - Obj.base();
2119 if (StringTableSize > FileSize - Offset)
2120 reportUniqueWarning(
2121 "the dynamic string table at 0x" + Twine::utohexstr(Offset) +
2122 " goes past the end of the file (0x" + Twine::utohexstr(FileSize) +
2123 ") with DT_STRSZ = 0x" + Twine::utohexstr(StringTableSize));
2124 else
2125 DynamicStringTable = StringRef(StringTableBegin, StringTableSize);
2128 const bool IsHashTableSupported = getHashTableEntSize() == 4;
2129 if (DynSymRegion) {
2130 // Often we find the information about the dynamic symbol table
2131 // location in the SHT_DYNSYM section header. However, the value in
2132 // DT_SYMTAB has priority, because it is used by dynamic loaders to
2133 // locate .dynsym at runtime. The location we find in the section header
2134 // and the location we find here should match.
2135 if (DynSymFromTable && DynSymFromTable->Addr != DynSymRegion->Addr)
2136 reportUniqueWarning(
2137 createError("SHT_DYNSYM section header and DT_SYMTAB disagree about "
2138 "the location of the dynamic symbol table"));
2140 // According to the ELF gABI: "The number of symbol table entries should
2141 // equal nchain". Check to see if the DT_HASH hash table nchain value
2142 // conflicts with the number of symbols in the dynamic symbol table
2143 // according to the section header.
2144 if (HashTable && IsHashTableSupported) {
2145 if (DynSymRegion->EntSize == 0)
2146 reportUniqueWarning("SHT_DYNSYM section has sh_entsize == 0");
2147 else if (HashTable->nchain != DynSymRegion->Size / DynSymRegion->EntSize)
2148 reportUniqueWarning(
2149 "hash table nchain (" + Twine(HashTable->nchain) +
2150 ") differs from symbol count derived from SHT_DYNSYM section "
2151 "header (" +
2152 Twine(DynSymRegion->Size / DynSymRegion->EntSize) + ")");
2156 // Delay the creation of the actual dynamic symbol table until now, so that
2157 // checks can always be made against the section header-based properties,
2158 // without worrying about tag order.
2159 if (DynSymFromTable) {
2160 if (!DynSymRegion) {
2161 DynSymRegion = DynSymFromTable;
2162 } else {
2163 DynSymRegion->Addr = DynSymFromTable->Addr;
2164 DynSymRegion->EntSize = DynSymFromTable->EntSize;
2165 DynSymRegion->EntSizePrintName = DynSymFromTable->EntSizePrintName;
2169 // Derive the dynamic symbol table size from the DT_HASH hash table, if
2170 // present.
2171 if (HashTable && IsHashTableSupported && DynSymRegion) {
2172 const uint64_t FileSize = Obj.getBufSize();
2173 const uint64_t DerivedSize =
2174 (uint64_t)HashTable->nchain * DynSymRegion->EntSize;
2175 const uint64_t Offset = (const uint8_t *)DynSymRegion->Addr - Obj.base();
2176 if (DerivedSize > FileSize - Offset)
2177 reportUniqueWarning(
2178 "the size (0x" + Twine::utohexstr(DerivedSize) +
2179 ") of the dynamic symbol table at 0x" + Twine::utohexstr(Offset) +
2180 ", derived from the hash table, goes past the end of the file (0x" +
2181 Twine::utohexstr(FileSize) + ") and will be ignored");
2182 else
2183 DynSymRegion->Size = HashTable->nchain * DynSymRegion->EntSize;
2187 template <typename ELFT> void ELFDumper<ELFT>::printVersionInfo() {
2188 // Dump version symbol section.
2189 printVersionSymbolSection(SymbolVersionSection);
2191 // Dump version definition section.
2192 printVersionDefinitionSection(SymbolVersionDefSection);
2194 // Dump version dependency section.
2195 printVersionDependencySection(SymbolVersionNeedSection);
2198 #define LLVM_READOBJ_DT_FLAG_ENT(prefix, enum) \
2199 { #enum, prefix##_##enum }
2201 const EnumEntry<unsigned> ElfDynamicDTFlags[] = {
2202 LLVM_READOBJ_DT_FLAG_ENT(DF, ORIGIN),
2203 LLVM_READOBJ_DT_FLAG_ENT(DF, SYMBOLIC),
2204 LLVM_READOBJ_DT_FLAG_ENT(DF, TEXTREL),
2205 LLVM_READOBJ_DT_FLAG_ENT(DF, BIND_NOW),
2206 LLVM_READOBJ_DT_FLAG_ENT(DF, STATIC_TLS)
2209 const EnumEntry<unsigned> ElfDynamicDTFlags1[] = {
2210 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOW),
2211 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAL),
2212 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GROUP),
2213 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODELETE),
2214 LLVM_READOBJ_DT_FLAG_ENT(DF_1, LOADFLTR),
2215 LLVM_READOBJ_DT_FLAG_ENT(DF_1, INITFIRST),
2216 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOOPEN),
2217 LLVM_READOBJ_DT_FLAG_ENT(DF_1, ORIGIN),
2218 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DIRECT),
2219 LLVM_READOBJ_DT_FLAG_ENT(DF_1, TRANS),
2220 LLVM_READOBJ_DT_FLAG_ENT(DF_1, INTERPOSE),
2221 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODEFLIB),
2222 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODUMP),
2223 LLVM_READOBJ_DT_FLAG_ENT(DF_1, CONFALT),
2224 LLVM_READOBJ_DT_FLAG_ENT(DF_1, ENDFILTEE),
2225 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELDNE),
2226 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELPND),
2227 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODIRECT),
2228 LLVM_READOBJ_DT_FLAG_ENT(DF_1, IGNMULDEF),
2229 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOKSYMS),
2230 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOHDR),
2231 LLVM_READOBJ_DT_FLAG_ENT(DF_1, EDITED),
2232 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NORELOC),
2233 LLVM_READOBJ_DT_FLAG_ENT(DF_1, SYMINTPOSE),
2234 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAUDIT),
2235 LLVM_READOBJ_DT_FLAG_ENT(DF_1, SINGLETON),
2236 LLVM_READOBJ_DT_FLAG_ENT(DF_1, PIE),
2239 const EnumEntry<unsigned> ElfDynamicDTMipsFlags[] = {
2240 LLVM_READOBJ_DT_FLAG_ENT(RHF, NONE),
2241 LLVM_READOBJ_DT_FLAG_ENT(RHF, QUICKSTART),
2242 LLVM_READOBJ_DT_FLAG_ENT(RHF, NOTPOT),
2243 LLVM_READOBJ_DT_FLAG_ENT(RHS, NO_LIBRARY_REPLACEMENT),
2244 LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_MOVE),
2245 LLVM_READOBJ_DT_FLAG_ENT(RHF, SGI_ONLY),
2246 LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_INIT),
2247 LLVM_READOBJ_DT_FLAG_ENT(RHF, DELTA_C_PLUS_PLUS),
2248 LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_START_INIT),
2249 LLVM_READOBJ_DT_FLAG_ENT(RHF, PIXIE),
2250 LLVM_READOBJ_DT_FLAG_ENT(RHF, DEFAULT_DELAY_LOAD),
2251 LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTART),
2252 LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTARTED),
2253 LLVM_READOBJ_DT_FLAG_ENT(RHF, CORD),
2254 LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_UNRES_UNDEF),
2255 LLVM_READOBJ_DT_FLAG_ENT(RHF, RLD_ORDER_SAFE)
2258 #undef LLVM_READOBJ_DT_FLAG_ENT
2260 template <typename T, typename TFlag>
2261 void printFlags(T Value, ArrayRef<EnumEntry<TFlag>> Flags, raw_ostream &OS) {
2262 SmallVector<EnumEntry<TFlag>, 10> SetFlags;
2263 for (const EnumEntry<TFlag> &Flag : Flags)
2264 if (Flag.Value != 0 && (Value & Flag.Value) == Flag.Value)
2265 SetFlags.push_back(Flag);
2267 for (const EnumEntry<TFlag> &Flag : SetFlags)
2268 OS << Flag.Name << " ";
2271 template <class ELFT>
2272 const typename ELFT::Shdr *
2273 ELFDumper<ELFT>::findSectionByName(StringRef Name) const {
2274 for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
2275 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Shdr)) {
2276 if (*NameOrErr == Name)
2277 return &Shdr;
2278 } else {
2279 reportUniqueWarning("unable to read the name of " + describe(Shdr) +
2280 ": " + toString(NameOrErr.takeError()));
2283 return nullptr;
2286 template <class ELFT>
2287 std::string ELFDumper<ELFT>::getDynamicEntry(uint64_t Type,
2288 uint64_t Value) const {
2289 auto FormatHexValue = [](uint64_t V) {
2290 std::string Str;
2291 raw_string_ostream OS(Str);
2292 const char *ConvChar =
2293 (opts::Output == opts::GNU) ? "0x%" PRIx64 : "0x%" PRIX64;
2294 OS << format(ConvChar, V);
2295 return OS.str();
2298 auto FormatFlags = [](uint64_t V,
2299 llvm::ArrayRef<llvm::EnumEntry<unsigned int>> Array) {
2300 std::string Str;
2301 raw_string_ostream OS(Str);
2302 printFlags(V, Array, OS);
2303 return OS.str();
2306 // Handle custom printing of architecture specific tags
2307 switch (Obj.getHeader().e_machine) {
2308 case EM_AARCH64:
2309 switch (Type) {
2310 case DT_AARCH64_BTI_PLT:
2311 case DT_AARCH64_PAC_PLT:
2312 case DT_AARCH64_VARIANT_PCS:
2313 case DT_AARCH64_MEMTAG_GLOBALSSZ:
2314 return std::to_string(Value);
2315 case DT_AARCH64_MEMTAG_MODE:
2316 switch (Value) {
2317 case 0:
2318 return "Synchronous (0)";
2319 case 1:
2320 return "Asynchronous (1)";
2321 default:
2322 return (Twine("Unknown (") + Twine(Value) + ")").str();
2324 case DT_AARCH64_MEMTAG_HEAP:
2325 case DT_AARCH64_MEMTAG_STACK:
2326 switch (Value) {
2327 case 0:
2328 return "Disabled (0)";
2329 case 1:
2330 return "Enabled (1)";
2331 default:
2332 return (Twine("Unknown (") + Twine(Value) + ")").str();
2334 case DT_AARCH64_MEMTAG_GLOBALS:
2335 return (Twine("0x") + utohexstr(Value, /*LowerCase=*/true)).str();
2336 default:
2337 break;
2339 break;
2340 case EM_HEXAGON:
2341 switch (Type) {
2342 case DT_HEXAGON_VER:
2343 return std::to_string(Value);
2344 case DT_HEXAGON_SYMSZ:
2345 case DT_HEXAGON_PLT:
2346 return FormatHexValue(Value);
2347 default:
2348 break;
2350 break;
2351 case EM_MIPS:
2352 switch (Type) {
2353 case DT_MIPS_RLD_VERSION:
2354 case DT_MIPS_LOCAL_GOTNO:
2355 case DT_MIPS_SYMTABNO:
2356 case DT_MIPS_UNREFEXTNO:
2357 return std::to_string(Value);
2358 case DT_MIPS_TIME_STAMP:
2359 case DT_MIPS_ICHECKSUM:
2360 case DT_MIPS_IVERSION:
2361 case DT_MIPS_BASE_ADDRESS:
2362 case DT_MIPS_MSYM:
2363 case DT_MIPS_CONFLICT:
2364 case DT_MIPS_LIBLIST:
2365 case DT_MIPS_CONFLICTNO:
2366 case DT_MIPS_LIBLISTNO:
2367 case DT_MIPS_GOTSYM:
2368 case DT_MIPS_HIPAGENO:
2369 case DT_MIPS_RLD_MAP:
2370 case DT_MIPS_DELTA_CLASS:
2371 case DT_MIPS_DELTA_CLASS_NO:
2372 case DT_MIPS_DELTA_INSTANCE:
2373 case DT_MIPS_DELTA_RELOC:
2374 case DT_MIPS_DELTA_RELOC_NO:
2375 case DT_MIPS_DELTA_SYM:
2376 case DT_MIPS_DELTA_SYM_NO:
2377 case DT_MIPS_DELTA_CLASSSYM:
2378 case DT_MIPS_DELTA_CLASSSYM_NO:
2379 case DT_MIPS_CXX_FLAGS:
2380 case DT_MIPS_PIXIE_INIT:
2381 case DT_MIPS_SYMBOL_LIB:
2382 case DT_MIPS_LOCALPAGE_GOTIDX:
2383 case DT_MIPS_LOCAL_GOTIDX:
2384 case DT_MIPS_HIDDEN_GOTIDX:
2385 case DT_MIPS_PROTECTED_GOTIDX:
2386 case DT_MIPS_OPTIONS:
2387 case DT_MIPS_INTERFACE:
2388 case DT_MIPS_DYNSTR_ALIGN:
2389 case DT_MIPS_INTERFACE_SIZE:
2390 case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
2391 case DT_MIPS_PERF_SUFFIX:
2392 case DT_MIPS_COMPACT_SIZE:
2393 case DT_MIPS_GP_VALUE:
2394 case DT_MIPS_AUX_DYNAMIC:
2395 case DT_MIPS_PLTGOT:
2396 case DT_MIPS_RWPLT:
2397 case DT_MIPS_RLD_MAP_REL:
2398 case DT_MIPS_XHASH:
2399 return FormatHexValue(Value);
2400 case DT_MIPS_FLAGS:
2401 return FormatFlags(Value, ArrayRef(ElfDynamicDTMipsFlags));
2402 default:
2403 break;
2405 break;
2406 default:
2407 break;
2410 switch (Type) {
2411 case DT_PLTREL:
2412 if (Value == DT_REL)
2413 return "REL";
2414 if (Value == DT_RELA)
2415 return "RELA";
2416 [[fallthrough]];
2417 case DT_PLTGOT:
2418 case DT_HASH:
2419 case DT_STRTAB:
2420 case DT_SYMTAB:
2421 case DT_RELA:
2422 case DT_INIT:
2423 case DT_FINI:
2424 case DT_REL:
2425 case DT_JMPREL:
2426 case DT_INIT_ARRAY:
2427 case DT_FINI_ARRAY:
2428 case DT_PREINIT_ARRAY:
2429 case DT_DEBUG:
2430 case DT_VERDEF:
2431 case DT_VERNEED:
2432 case DT_VERSYM:
2433 case DT_GNU_HASH:
2434 case DT_NULL:
2435 return FormatHexValue(Value);
2436 case DT_RELACOUNT:
2437 case DT_RELCOUNT:
2438 case DT_VERDEFNUM:
2439 case DT_VERNEEDNUM:
2440 return std::to_string(Value);
2441 case DT_PLTRELSZ:
2442 case DT_RELASZ:
2443 case DT_RELAENT:
2444 case DT_STRSZ:
2445 case DT_SYMENT:
2446 case DT_RELSZ:
2447 case DT_RELENT:
2448 case DT_INIT_ARRAYSZ:
2449 case DT_FINI_ARRAYSZ:
2450 case DT_PREINIT_ARRAYSZ:
2451 case DT_RELRSZ:
2452 case DT_RELRENT:
2453 case DT_ANDROID_RELSZ:
2454 case DT_ANDROID_RELASZ:
2455 return std::to_string(Value) + " (bytes)";
2456 case DT_NEEDED:
2457 case DT_SONAME:
2458 case DT_AUXILIARY:
2459 case DT_USED:
2460 case DT_FILTER:
2461 case DT_RPATH:
2462 case DT_RUNPATH: {
2463 const std::map<uint64_t, const char *> TagNames = {
2464 {DT_NEEDED, "Shared library"}, {DT_SONAME, "Library soname"},
2465 {DT_AUXILIARY, "Auxiliary library"}, {DT_USED, "Not needed object"},
2466 {DT_FILTER, "Filter library"}, {DT_RPATH, "Library rpath"},
2467 {DT_RUNPATH, "Library runpath"},
2470 return (Twine(TagNames.at(Type)) + ": [" + getDynamicString(Value) + "]")
2471 .str();
2473 case DT_FLAGS:
2474 return FormatFlags(Value, ArrayRef(ElfDynamicDTFlags));
2475 case DT_FLAGS_1:
2476 return FormatFlags(Value, ArrayRef(ElfDynamicDTFlags1));
2477 default:
2478 return FormatHexValue(Value);
2482 template <class ELFT>
2483 StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const {
2484 if (DynamicStringTable.empty() && !DynamicStringTable.data()) {
2485 reportUniqueWarning("string table was not found");
2486 return "<?>";
2489 auto WarnAndReturn = [this](const Twine &Msg, uint64_t Offset) {
2490 reportUniqueWarning("string table at offset 0x" + Twine::utohexstr(Offset) +
2491 Msg);
2492 return "<?>";
2495 const uint64_t FileSize = Obj.getBufSize();
2496 const uint64_t Offset =
2497 (const uint8_t *)DynamicStringTable.data() - Obj.base();
2498 if (DynamicStringTable.size() > FileSize - Offset)
2499 return WarnAndReturn(" with size 0x" +
2500 Twine::utohexstr(DynamicStringTable.size()) +
2501 " goes past the end of the file (0x" +
2502 Twine::utohexstr(FileSize) + ")",
2503 Offset);
2505 if (Value >= DynamicStringTable.size())
2506 return WarnAndReturn(
2507 ": unable to read the string at 0x" + Twine::utohexstr(Offset + Value) +
2508 ": it goes past the end of the table (0x" +
2509 Twine::utohexstr(Offset + DynamicStringTable.size()) + ")",
2510 Offset);
2512 if (DynamicStringTable.back() != '\0')
2513 return WarnAndReturn(": unable to read the string at 0x" +
2514 Twine::utohexstr(Offset + Value) +
2515 ": the string table is not null-terminated",
2516 Offset);
2518 return DynamicStringTable.data() + Value;
2521 template <class ELFT> void ELFDumper<ELFT>::printUnwindInfo() {
2522 DwarfCFIEH::PrinterContext<ELFT> Ctx(W, ObjF);
2523 Ctx.printUnwindInformation();
2526 // The namespace is needed to fix the compilation with GCC older than 7.0+.
2527 namespace {
2528 template <> void ELFDumper<ELF32LE>::printUnwindInfo() {
2529 if (Obj.getHeader().e_machine == EM_ARM) {
2530 ARM::EHABI::PrinterContext<ELF32LE> Ctx(W, Obj, ObjF.getFileName(),
2531 DotSymtabSec);
2532 Ctx.PrintUnwindInformation();
2534 DwarfCFIEH::PrinterContext<ELF32LE> Ctx(W, ObjF);
2535 Ctx.printUnwindInformation();
2537 } // namespace
2539 template <class ELFT> void ELFDumper<ELFT>::printNeededLibraries() {
2540 ListScope D(W, "NeededLibraries");
2542 std::vector<StringRef> Libs;
2543 for (const auto &Entry : dynamic_table())
2544 if (Entry.d_tag == ELF::DT_NEEDED)
2545 Libs.push_back(getDynamicString(Entry.d_un.d_val));
2547 llvm::sort(Libs);
2549 for (StringRef L : Libs)
2550 W.startLine() << L << "\n";
2553 template <class ELFT>
2554 static Error checkHashTable(const ELFDumper<ELFT> &Dumper,
2555 const typename ELFT::Hash *H,
2556 bool *IsHeaderValid = nullptr) {
2557 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
2558 const uint64_t SecOffset = (const uint8_t *)H - Obj.base();
2559 if (Dumper.getHashTableEntSize() == 8) {
2560 auto It = llvm::find_if(ElfMachineType, [&](const EnumEntry<unsigned> &E) {
2561 return E.Value == Obj.getHeader().e_machine;
2563 if (IsHeaderValid)
2564 *IsHeaderValid = false;
2565 return createError("the hash table at 0x" + Twine::utohexstr(SecOffset) +
2566 " is not supported: it contains non-standard 8 "
2567 "byte entries on " +
2568 It->AltName + " platform");
2571 auto MakeError = [&](const Twine &Msg = "") {
2572 return createError("the hash table at offset 0x" +
2573 Twine::utohexstr(SecOffset) +
2574 " goes past the end of the file (0x" +
2575 Twine::utohexstr(Obj.getBufSize()) + ")" + Msg);
2578 // Each SHT_HASH section starts from two 32-bit fields: nbucket and nchain.
2579 const unsigned HeaderSize = 2 * sizeof(typename ELFT::Word);
2581 if (IsHeaderValid)
2582 *IsHeaderValid = Obj.getBufSize() - SecOffset >= HeaderSize;
2584 if (Obj.getBufSize() - SecOffset < HeaderSize)
2585 return MakeError();
2587 if (Obj.getBufSize() - SecOffset - HeaderSize <
2588 ((uint64_t)H->nbucket + H->nchain) * sizeof(typename ELFT::Word))
2589 return MakeError(", nbucket = " + Twine(H->nbucket) +
2590 ", nchain = " + Twine(H->nchain));
2591 return Error::success();
2594 template <class ELFT>
2595 static Error checkGNUHashTable(const ELFFile<ELFT> &Obj,
2596 const typename ELFT::GnuHash *GnuHashTable,
2597 bool *IsHeaderValid = nullptr) {
2598 const uint8_t *TableData = reinterpret_cast<const uint8_t *>(GnuHashTable);
2599 assert(TableData >= Obj.base() && TableData < Obj.base() + Obj.getBufSize() &&
2600 "GnuHashTable must always point to a location inside the file");
2602 uint64_t TableOffset = TableData - Obj.base();
2603 if (IsHeaderValid)
2604 *IsHeaderValid = TableOffset + /*Header size:*/ 16 < Obj.getBufSize();
2605 if (TableOffset + 16 + (uint64_t)GnuHashTable->nbuckets * 4 +
2606 (uint64_t)GnuHashTable->maskwords * sizeof(typename ELFT::Off) >=
2607 Obj.getBufSize())
2608 return createError("unable to dump the SHT_GNU_HASH "
2609 "section at 0x" +
2610 Twine::utohexstr(TableOffset) +
2611 ": it goes past the end of the file");
2612 return Error::success();
2615 template <typename ELFT> void ELFDumper<ELFT>::printHashTable() {
2616 DictScope D(W, "HashTable");
2617 if (!HashTable)
2618 return;
2620 bool IsHeaderValid;
2621 Error Err = checkHashTable(*this, HashTable, &IsHeaderValid);
2622 if (IsHeaderValid) {
2623 W.printNumber("Num Buckets", HashTable->nbucket);
2624 W.printNumber("Num Chains", HashTable->nchain);
2627 if (Err) {
2628 reportUniqueWarning(std::move(Err));
2629 return;
2632 W.printList("Buckets", HashTable->buckets());
2633 W.printList("Chains", HashTable->chains());
2636 template <class ELFT>
2637 static Expected<ArrayRef<typename ELFT::Word>>
2638 getGnuHashTableChains(std::optional<DynRegionInfo> DynSymRegion,
2639 const typename ELFT::GnuHash *GnuHashTable) {
2640 if (!DynSymRegion)
2641 return createError("no dynamic symbol table found");
2643 ArrayRef<typename ELFT::Sym> DynSymTable =
2644 DynSymRegion->template getAsArrayRef<typename ELFT::Sym>();
2645 size_t NumSyms = DynSymTable.size();
2646 if (!NumSyms)
2647 return createError("the dynamic symbol table is empty");
2649 if (GnuHashTable->symndx < NumSyms)
2650 return GnuHashTable->values(NumSyms);
2652 // A normal empty GNU hash table section produced by linker might have
2653 // symndx set to the number of dynamic symbols + 1 (for the zero symbol)
2654 // and have dummy null values in the Bloom filter and in the buckets
2655 // vector (or no values at all). It happens because the value of symndx is not
2656 // important for dynamic loaders when the GNU hash table is empty. They just
2657 // skip the whole object during symbol lookup. In such cases, the symndx value
2658 // is irrelevant and we should not report a warning.
2659 ArrayRef<typename ELFT::Word> Buckets = GnuHashTable->buckets();
2660 if (!llvm::all_of(Buckets, [](typename ELFT::Word V) { return V == 0; }))
2661 return createError(
2662 "the first hashed symbol index (" + Twine(GnuHashTable->symndx) +
2663 ") is greater than or equal to the number of dynamic symbols (" +
2664 Twine(NumSyms) + ")");
2665 // There is no way to represent an array of (dynamic symbols count - symndx)
2666 // length.
2667 return ArrayRef<typename ELFT::Word>();
2670 template <typename ELFT>
2671 void ELFDumper<ELFT>::printGnuHashTable() {
2672 DictScope D(W, "GnuHashTable");
2673 if (!GnuHashTable)
2674 return;
2676 bool IsHeaderValid;
2677 Error Err = checkGNUHashTable<ELFT>(Obj, GnuHashTable, &IsHeaderValid);
2678 if (IsHeaderValid) {
2679 W.printNumber("Num Buckets", GnuHashTable->nbuckets);
2680 W.printNumber("First Hashed Symbol Index", GnuHashTable->symndx);
2681 W.printNumber("Num Mask Words", GnuHashTable->maskwords);
2682 W.printNumber("Shift Count", GnuHashTable->shift2);
2685 if (Err) {
2686 reportUniqueWarning(std::move(Err));
2687 return;
2690 ArrayRef<typename ELFT::Off> BloomFilter = GnuHashTable->filter();
2691 W.printHexList("Bloom Filter", BloomFilter);
2693 ArrayRef<Elf_Word> Buckets = GnuHashTable->buckets();
2694 W.printList("Buckets", Buckets);
2696 Expected<ArrayRef<Elf_Word>> Chains =
2697 getGnuHashTableChains<ELFT>(DynSymRegion, GnuHashTable);
2698 if (!Chains) {
2699 reportUniqueWarning("unable to dump 'Values' for the SHT_GNU_HASH "
2700 "section: " +
2701 toString(Chains.takeError()));
2702 return;
2705 W.printHexList("Values", *Chains);
2708 template <typename ELFT> void ELFDumper<ELFT>::printHashHistograms() {
2709 // Print histogram for the .hash section.
2710 if (this->HashTable) {
2711 if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
2712 this->reportUniqueWarning(std::move(E));
2713 else
2714 printHashHistogram(*this->HashTable);
2717 // Print histogram for the .gnu.hash section.
2718 if (this->GnuHashTable) {
2719 if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
2720 this->reportUniqueWarning(std::move(E));
2721 else
2722 printGnuHashHistogram(*this->GnuHashTable);
2726 template <typename ELFT>
2727 void ELFDumper<ELFT>::printHashHistogram(const Elf_Hash &HashTable) const {
2728 size_t NBucket = HashTable.nbucket;
2729 size_t NChain = HashTable.nchain;
2730 ArrayRef<Elf_Word> Buckets = HashTable.buckets();
2731 ArrayRef<Elf_Word> Chains = HashTable.chains();
2732 size_t TotalSyms = 0;
2733 // If hash table is correct, we have at least chains with 0 length.
2734 size_t MaxChain = 1;
2736 if (NChain == 0 || NBucket == 0)
2737 return;
2739 std::vector<size_t> ChainLen(NBucket, 0);
2740 // Go over all buckets and and note chain lengths of each bucket (total
2741 // unique chain lengths).
2742 for (size_t B = 0; B < NBucket; ++B) {
2743 BitVector Visited(NChain);
2744 for (size_t C = Buckets[B]; C < NChain; C = Chains[C]) {
2745 if (C == ELF::STN_UNDEF)
2746 break;
2747 if (Visited[C]) {
2748 this->reportUniqueWarning(
2749 ".hash section is invalid: bucket " + Twine(C) +
2750 ": a cycle was detected in the linked chain");
2751 break;
2753 Visited[C] = true;
2754 if (MaxChain <= ++ChainLen[B])
2755 ++MaxChain;
2757 TotalSyms += ChainLen[B];
2760 if (!TotalSyms)
2761 return;
2763 std::vector<size_t> Count(MaxChain, 0);
2764 // Count how long is the chain for each bucket.
2765 for (size_t B = 0; B < NBucket; B++)
2766 ++Count[ChainLen[B]];
2767 // Print Number of buckets with each chain lengths and their cumulative
2768 // coverage of the symbols.
2769 printHashHistogramStats(NBucket, MaxChain, TotalSyms, Count, /*IsGnu=*/false);
2772 template <class ELFT>
2773 void ELFDumper<ELFT>::printGnuHashHistogram(
2774 const Elf_GnuHash &GnuHashTable) const {
2775 Expected<ArrayRef<Elf_Word>> ChainsOrErr =
2776 getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHashTable);
2777 if (!ChainsOrErr) {
2778 this->reportUniqueWarning("unable to print the GNU hash table histogram: " +
2779 toString(ChainsOrErr.takeError()));
2780 return;
2783 ArrayRef<Elf_Word> Chains = *ChainsOrErr;
2784 size_t Symndx = GnuHashTable.symndx;
2785 size_t TotalSyms = 0;
2786 size_t MaxChain = 1;
2788 size_t NBucket = GnuHashTable.nbuckets;
2789 if (Chains.empty() || NBucket == 0)
2790 return;
2792 ArrayRef<Elf_Word> Buckets = GnuHashTable.buckets();
2793 std::vector<size_t> ChainLen(NBucket, 0);
2794 for (size_t B = 0; B < NBucket; ++B) {
2795 if (!Buckets[B])
2796 continue;
2797 size_t Len = 1;
2798 for (size_t C = Buckets[B] - Symndx;
2799 C < Chains.size() && (Chains[C] & 1) == 0; ++C)
2800 if (MaxChain < ++Len)
2801 ++MaxChain;
2802 ChainLen[B] = Len;
2803 TotalSyms += Len;
2805 ++MaxChain;
2807 if (!TotalSyms)
2808 return;
2810 std::vector<size_t> Count(MaxChain, 0);
2811 for (size_t B = 0; B < NBucket; ++B)
2812 ++Count[ChainLen[B]];
2813 // Print Number of buckets with each chain lengths and their cumulative
2814 // coverage of the symbols.
2815 printHashHistogramStats(NBucket, MaxChain, TotalSyms, Count, /*IsGnu=*/true);
2818 template <typename ELFT> void ELFDumper<ELFT>::printLoadName() {
2819 StringRef SOName = "<Not found>";
2820 if (SONameOffset)
2821 SOName = getDynamicString(*SONameOffset);
2822 W.printString("LoadName", SOName);
2825 template <class ELFT> void ELFDumper<ELFT>::printArchSpecificInfo() {
2826 switch (Obj.getHeader().e_machine) {
2827 case EM_ARM:
2828 if (Obj.isLE())
2829 printAttributes(ELF::SHT_ARM_ATTRIBUTES,
2830 std::make_unique<ARMAttributeParser>(&W),
2831 support::little);
2832 else
2833 reportUniqueWarning("attribute printing not implemented for big-endian "
2834 "ARM objects");
2835 break;
2836 case EM_RISCV:
2837 if (Obj.isLE())
2838 printAttributes(ELF::SHT_RISCV_ATTRIBUTES,
2839 std::make_unique<RISCVAttributeParser>(&W),
2840 support::little);
2841 else
2842 reportUniqueWarning("attribute printing not implemented for big-endian "
2843 "RISC-V objects");
2844 break;
2845 case EM_MSP430:
2846 printAttributes(ELF::SHT_MSP430_ATTRIBUTES,
2847 std::make_unique<MSP430AttributeParser>(&W),
2848 support::little);
2849 break;
2850 case EM_MIPS: {
2851 printMipsABIFlags();
2852 printMipsOptions();
2853 printMipsReginfo();
2854 MipsGOTParser<ELFT> Parser(*this);
2855 if (Error E = Parser.findGOT(dynamic_table(), dynamic_symbols()))
2856 reportUniqueWarning(std::move(E));
2857 else if (!Parser.isGotEmpty())
2858 printMipsGOT(Parser);
2860 if (Error E = Parser.findPLT(dynamic_table()))
2861 reportUniqueWarning(std::move(E));
2862 else if (!Parser.isPltEmpty())
2863 printMipsPLT(Parser);
2864 break;
2866 default:
2867 break;
2871 template <class ELFT>
2872 void ELFDumper<ELFT>::printAttributes(
2873 unsigned AttrShType, std::unique_ptr<ELFAttributeParser> AttrParser,
2874 support::endianness Endianness) {
2875 assert((AttrShType != ELF::SHT_NULL) && AttrParser &&
2876 "Incomplete ELF attribute implementation");
2877 DictScope BA(W, "BuildAttributes");
2878 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
2879 if (Sec.sh_type != AttrShType)
2880 continue;
2882 ArrayRef<uint8_t> Contents;
2883 if (Expected<ArrayRef<uint8_t>> ContentOrErr =
2884 Obj.getSectionContents(Sec)) {
2885 Contents = *ContentOrErr;
2886 if (Contents.empty()) {
2887 reportUniqueWarning("the " + describe(Sec) + " is empty");
2888 continue;
2890 } else {
2891 reportUniqueWarning("unable to read the content of the " + describe(Sec) +
2892 ": " + toString(ContentOrErr.takeError()));
2893 continue;
2896 W.printHex("FormatVersion", Contents[0]);
2898 if (Error E = AttrParser->parse(Contents, Endianness))
2899 reportUniqueWarning("unable to dump attributes from the " +
2900 describe(Sec) + ": " + toString(std::move(E)));
2904 namespace {
2906 template <class ELFT> class MipsGOTParser {
2907 public:
2908 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
2909 using Entry = typename ELFT::Addr;
2910 using Entries = ArrayRef<Entry>;
2912 const bool IsStatic;
2913 const ELFFile<ELFT> &Obj;
2914 const ELFDumper<ELFT> &Dumper;
2916 MipsGOTParser(const ELFDumper<ELFT> &D);
2917 Error findGOT(Elf_Dyn_Range DynTable, Elf_Sym_Range DynSyms);
2918 Error findPLT(Elf_Dyn_Range DynTable);
2920 bool isGotEmpty() const { return GotEntries.empty(); }
2921 bool isPltEmpty() const { return PltEntries.empty(); }
2923 uint64_t getGp() const;
2925 const Entry *getGotLazyResolver() const;
2926 const Entry *getGotModulePointer() const;
2927 const Entry *getPltLazyResolver() const;
2928 const Entry *getPltModulePointer() const;
2930 Entries getLocalEntries() const;
2931 Entries getGlobalEntries() const;
2932 Entries getOtherEntries() const;
2933 Entries getPltEntries() const;
2935 uint64_t getGotAddress(const Entry * E) const;
2936 int64_t getGotOffset(const Entry * E) const;
2937 const Elf_Sym *getGotSym(const Entry *E) const;
2939 uint64_t getPltAddress(const Entry * E) const;
2940 const Elf_Sym *getPltSym(const Entry *E) const;
2942 StringRef getPltStrTable() const { return PltStrTable; }
2943 const Elf_Shdr *getPltSymTable() const { return PltSymTable; }
2945 private:
2946 const Elf_Shdr *GotSec;
2947 size_t LocalNum;
2948 size_t GlobalNum;
2950 const Elf_Shdr *PltSec;
2951 const Elf_Shdr *PltRelSec;
2952 const Elf_Shdr *PltSymTable;
2953 StringRef FileName;
2955 Elf_Sym_Range GotDynSyms;
2956 StringRef PltStrTable;
2958 Entries GotEntries;
2959 Entries PltEntries;
2962 } // end anonymous namespace
2964 template <class ELFT>
2965 MipsGOTParser<ELFT>::MipsGOTParser(const ELFDumper<ELFT> &D)
2966 : IsStatic(D.dynamic_table().empty()), Obj(D.getElfObject().getELFFile()),
2967 Dumper(D), GotSec(nullptr), LocalNum(0), GlobalNum(0), PltSec(nullptr),
2968 PltRelSec(nullptr), PltSymTable(nullptr),
2969 FileName(D.getElfObject().getFileName()) {}
2971 template <class ELFT>
2972 Error MipsGOTParser<ELFT>::findGOT(Elf_Dyn_Range DynTable,
2973 Elf_Sym_Range DynSyms) {
2974 // See "Global Offset Table" in Chapter 5 in the following document
2975 // for detailed GOT description.
2976 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
2978 // Find static GOT secton.
2979 if (IsStatic) {
2980 GotSec = Dumper.findSectionByName(".got");
2981 if (!GotSec)
2982 return Error::success();
2984 ArrayRef<uint8_t> Content =
2985 unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
2986 GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
2987 Content.size() / sizeof(Entry));
2988 LocalNum = GotEntries.size();
2989 return Error::success();
2992 // Lookup dynamic table tags which define the GOT layout.
2993 std::optional<uint64_t> DtPltGot;
2994 std::optional<uint64_t> DtLocalGotNum;
2995 std::optional<uint64_t> DtGotSym;
2996 for (const auto &Entry : DynTable) {
2997 switch (Entry.getTag()) {
2998 case ELF::DT_PLTGOT:
2999 DtPltGot = Entry.getVal();
3000 break;
3001 case ELF::DT_MIPS_LOCAL_GOTNO:
3002 DtLocalGotNum = Entry.getVal();
3003 break;
3004 case ELF::DT_MIPS_GOTSYM:
3005 DtGotSym = Entry.getVal();
3006 break;
3010 if (!DtPltGot && !DtLocalGotNum && !DtGotSym)
3011 return Error::success();
3013 if (!DtPltGot)
3014 return createError("cannot find PLTGOT dynamic tag");
3015 if (!DtLocalGotNum)
3016 return createError("cannot find MIPS_LOCAL_GOTNO dynamic tag");
3017 if (!DtGotSym)
3018 return createError("cannot find MIPS_GOTSYM dynamic tag");
3020 size_t DynSymTotal = DynSyms.size();
3021 if (*DtGotSym > DynSymTotal)
3022 return createError("DT_MIPS_GOTSYM value (" + Twine(*DtGotSym) +
3023 ") exceeds the number of dynamic symbols (" +
3024 Twine(DynSymTotal) + ")");
3026 GotSec = findNotEmptySectionByAddress(Obj, FileName, *DtPltGot);
3027 if (!GotSec)
3028 return createError("there is no non-empty GOT section at 0x" +
3029 Twine::utohexstr(*DtPltGot));
3031 LocalNum = *DtLocalGotNum;
3032 GlobalNum = DynSymTotal - *DtGotSym;
3034 ArrayRef<uint8_t> Content =
3035 unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
3036 GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
3037 Content.size() / sizeof(Entry));
3038 GotDynSyms = DynSyms.drop_front(*DtGotSym);
3040 return Error::success();
3043 template <class ELFT>
3044 Error MipsGOTParser<ELFT>::findPLT(Elf_Dyn_Range DynTable) {
3045 // Lookup dynamic table tags which define the PLT layout.
3046 std::optional<uint64_t> DtMipsPltGot;
3047 std::optional<uint64_t> DtJmpRel;
3048 for (const auto &Entry : DynTable) {
3049 switch (Entry.getTag()) {
3050 case ELF::DT_MIPS_PLTGOT:
3051 DtMipsPltGot = Entry.getVal();
3052 break;
3053 case ELF::DT_JMPREL:
3054 DtJmpRel = Entry.getVal();
3055 break;
3059 if (!DtMipsPltGot && !DtJmpRel)
3060 return Error::success();
3062 // Find PLT section.
3063 if (!DtMipsPltGot)
3064 return createError("cannot find MIPS_PLTGOT dynamic tag");
3065 if (!DtJmpRel)
3066 return createError("cannot find JMPREL dynamic tag");
3068 PltSec = findNotEmptySectionByAddress(Obj, FileName, *DtMipsPltGot);
3069 if (!PltSec)
3070 return createError("there is no non-empty PLTGOT section at 0x" +
3071 Twine::utohexstr(*DtMipsPltGot));
3073 PltRelSec = findNotEmptySectionByAddress(Obj, FileName, *DtJmpRel);
3074 if (!PltRelSec)
3075 return createError("there is no non-empty RELPLT section at 0x" +
3076 Twine::utohexstr(*DtJmpRel));
3078 if (Expected<ArrayRef<uint8_t>> PltContentOrErr =
3079 Obj.getSectionContents(*PltSec))
3080 PltEntries =
3081 Entries(reinterpret_cast<const Entry *>(PltContentOrErr->data()),
3082 PltContentOrErr->size() / sizeof(Entry));
3083 else
3084 return createError("unable to read PLTGOT section content: " +
3085 toString(PltContentOrErr.takeError()));
3087 if (Expected<const Elf_Shdr *> PltSymTableOrErr =
3088 Obj.getSection(PltRelSec->sh_link))
3089 PltSymTable = *PltSymTableOrErr;
3090 else
3091 return createError("unable to get a symbol table linked to the " +
3092 describe(Obj, *PltRelSec) + ": " +
3093 toString(PltSymTableOrErr.takeError()));
3095 if (Expected<StringRef> StrTabOrErr =
3096 Obj.getStringTableForSymtab(*PltSymTable))
3097 PltStrTable = *StrTabOrErr;
3098 else
3099 return createError("unable to get a string table for the " +
3100 describe(Obj, *PltSymTable) + ": " +
3101 toString(StrTabOrErr.takeError()));
3103 return Error::success();
3106 template <class ELFT> uint64_t MipsGOTParser<ELFT>::getGp() const {
3107 return GotSec->sh_addr + 0x7ff0;
3110 template <class ELFT>
3111 const typename MipsGOTParser<ELFT>::Entry *
3112 MipsGOTParser<ELFT>::getGotLazyResolver() const {
3113 return LocalNum > 0 ? &GotEntries[0] : nullptr;
3116 template <class ELFT>
3117 const typename MipsGOTParser<ELFT>::Entry *
3118 MipsGOTParser<ELFT>::getGotModulePointer() const {
3119 if (LocalNum < 2)
3120 return nullptr;
3121 const Entry &E = GotEntries[1];
3122 if ((E >> (sizeof(Entry) * 8 - 1)) == 0)
3123 return nullptr;
3124 return &E;
3127 template <class ELFT>
3128 typename MipsGOTParser<ELFT>::Entries
3129 MipsGOTParser<ELFT>::getLocalEntries() const {
3130 size_t Skip = getGotModulePointer() ? 2 : 1;
3131 if (LocalNum - Skip <= 0)
3132 return Entries();
3133 return GotEntries.slice(Skip, LocalNum - Skip);
3136 template <class ELFT>
3137 typename MipsGOTParser<ELFT>::Entries
3138 MipsGOTParser<ELFT>::getGlobalEntries() const {
3139 if (GlobalNum == 0)
3140 return Entries();
3141 return GotEntries.slice(LocalNum, GlobalNum);
3144 template <class ELFT>
3145 typename MipsGOTParser<ELFT>::Entries
3146 MipsGOTParser<ELFT>::getOtherEntries() const {
3147 size_t OtherNum = GotEntries.size() - LocalNum - GlobalNum;
3148 if (OtherNum == 0)
3149 return Entries();
3150 return GotEntries.slice(LocalNum + GlobalNum, OtherNum);
3153 template <class ELFT>
3154 uint64_t MipsGOTParser<ELFT>::getGotAddress(const Entry *E) const {
3155 int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
3156 return GotSec->sh_addr + Offset;
3159 template <class ELFT>
3160 int64_t MipsGOTParser<ELFT>::getGotOffset(const Entry *E) const {
3161 int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
3162 return Offset - 0x7ff0;
3165 template <class ELFT>
3166 const typename MipsGOTParser<ELFT>::Elf_Sym *
3167 MipsGOTParser<ELFT>::getGotSym(const Entry *E) const {
3168 int64_t Offset = std::distance(GotEntries.data(), E);
3169 return &GotDynSyms[Offset - LocalNum];
3172 template <class ELFT>
3173 const typename MipsGOTParser<ELFT>::Entry *
3174 MipsGOTParser<ELFT>::getPltLazyResolver() const {
3175 return PltEntries.empty() ? nullptr : &PltEntries[0];
3178 template <class ELFT>
3179 const typename MipsGOTParser<ELFT>::Entry *
3180 MipsGOTParser<ELFT>::getPltModulePointer() const {
3181 return PltEntries.size() < 2 ? nullptr : &PltEntries[1];
3184 template <class ELFT>
3185 typename MipsGOTParser<ELFT>::Entries
3186 MipsGOTParser<ELFT>::getPltEntries() const {
3187 if (PltEntries.size() <= 2)
3188 return Entries();
3189 return PltEntries.slice(2, PltEntries.size() - 2);
3192 template <class ELFT>
3193 uint64_t MipsGOTParser<ELFT>::getPltAddress(const Entry *E) const {
3194 int64_t Offset = std::distance(PltEntries.data(), E) * sizeof(Entry);
3195 return PltSec->sh_addr + Offset;
3198 template <class ELFT>
3199 const typename MipsGOTParser<ELFT>::Elf_Sym *
3200 MipsGOTParser<ELFT>::getPltSym(const Entry *E) const {
3201 int64_t Offset = std::distance(getPltEntries().data(), E);
3202 if (PltRelSec->sh_type == ELF::SHT_REL) {
3203 Elf_Rel_Range Rels = unwrapOrError(FileName, Obj.rels(*PltRelSec));
3204 return unwrapOrError(FileName,
3205 Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
3206 } else {
3207 Elf_Rela_Range Rels = unwrapOrError(FileName, Obj.relas(*PltRelSec));
3208 return unwrapOrError(FileName,
3209 Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
3213 const EnumEntry<unsigned> ElfMipsISAExtType[] = {
3214 {"None", Mips::AFL_EXT_NONE},
3215 {"Broadcom SB-1", Mips::AFL_EXT_SB1},
3216 {"Cavium Networks Octeon", Mips::AFL_EXT_OCTEON},
3217 {"Cavium Networks Octeon2", Mips::AFL_EXT_OCTEON2},
3218 {"Cavium Networks OcteonP", Mips::AFL_EXT_OCTEONP},
3219 {"Cavium Networks Octeon3", Mips::AFL_EXT_OCTEON3},
3220 {"LSI R4010", Mips::AFL_EXT_4010},
3221 {"Loongson 2E", Mips::AFL_EXT_LOONGSON_2E},
3222 {"Loongson 2F", Mips::AFL_EXT_LOONGSON_2F},
3223 {"Loongson 3A", Mips::AFL_EXT_LOONGSON_3A},
3224 {"MIPS R4650", Mips::AFL_EXT_4650},
3225 {"MIPS R5900", Mips::AFL_EXT_5900},
3226 {"MIPS R10000", Mips::AFL_EXT_10000},
3227 {"NEC VR4100", Mips::AFL_EXT_4100},
3228 {"NEC VR4111/VR4181", Mips::AFL_EXT_4111},
3229 {"NEC VR4120", Mips::AFL_EXT_4120},
3230 {"NEC VR5400", Mips::AFL_EXT_5400},
3231 {"NEC VR5500", Mips::AFL_EXT_5500},
3232 {"RMI Xlr", Mips::AFL_EXT_XLR},
3233 {"Toshiba R3900", Mips::AFL_EXT_3900}
3236 const EnumEntry<unsigned> ElfMipsASEFlags[] = {
3237 {"DSP", Mips::AFL_ASE_DSP},
3238 {"DSPR2", Mips::AFL_ASE_DSPR2},
3239 {"Enhanced VA Scheme", Mips::AFL_ASE_EVA},
3240 {"MCU", Mips::AFL_ASE_MCU},
3241 {"MDMX", Mips::AFL_ASE_MDMX},
3242 {"MIPS-3D", Mips::AFL_ASE_MIPS3D},
3243 {"MT", Mips::AFL_ASE_MT},
3244 {"SmartMIPS", Mips::AFL_ASE_SMARTMIPS},
3245 {"VZ", Mips::AFL_ASE_VIRT},
3246 {"MSA", Mips::AFL_ASE_MSA},
3247 {"MIPS16", Mips::AFL_ASE_MIPS16},
3248 {"microMIPS", Mips::AFL_ASE_MICROMIPS},
3249 {"XPA", Mips::AFL_ASE_XPA},
3250 {"CRC", Mips::AFL_ASE_CRC},
3251 {"GINV", Mips::AFL_ASE_GINV},
3254 const EnumEntry<unsigned> ElfMipsFpABIType[] = {
3255 {"Hard or soft float", Mips::Val_GNU_MIPS_ABI_FP_ANY},
3256 {"Hard float (double precision)", Mips::Val_GNU_MIPS_ABI_FP_DOUBLE},
3257 {"Hard float (single precision)", Mips::Val_GNU_MIPS_ABI_FP_SINGLE},
3258 {"Soft float", Mips::Val_GNU_MIPS_ABI_FP_SOFT},
3259 {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)",
3260 Mips::Val_GNU_MIPS_ABI_FP_OLD_64},
3261 {"Hard float (32-bit CPU, Any FPU)", Mips::Val_GNU_MIPS_ABI_FP_XX},
3262 {"Hard float (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64},
3263 {"Hard float compat (32-bit CPU, 64-bit FPU)",
3264 Mips::Val_GNU_MIPS_ABI_FP_64A}
3267 static const EnumEntry<unsigned> ElfMipsFlags1[] {
3268 {"ODDSPREG", Mips::AFL_FLAGS1_ODDSPREG},
3271 static int getMipsRegisterSize(uint8_t Flag) {
3272 switch (Flag) {
3273 case Mips::AFL_REG_NONE:
3274 return 0;
3275 case Mips::AFL_REG_32:
3276 return 32;
3277 case Mips::AFL_REG_64:
3278 return 64;
3279 case Mips::AFL_REG_128:
3280 return 128;
3281 default:
3282 return -1;
3286 template <class ELFT>
3287 static void printMipsReginfoData(ScopedPrinter &W,
3288 const Elf_Mips_RegInfo<ELFT> &Reginfo) {
3289 W.printHex("GP", Reginfo.ri_gp_value);
3290 W.printHex("General Mask", Reginfo.ri_gprmask);
3291 W.printHex("Co-Proc Mask0", Reginfo.ri_cprmask[0]);
3292 W.printHex("Co-Proc Mask1", Reginfo.ri_cprmask[1]);
3293 W.printHex("Co-Proc Mask2", Reginfo.ri_cprmask[2]);
3294 W.printHex("Co-Proc Mask3", Reginfo.ri_cprmask[3]);
3297 template <class ELFT> void ELFDumper<ELFT>::printMipsReginfo() {
3298 const Elf_Shdr *RegInfoSec = findSectionByName(".reginfo");
3299 if (!RegInfoSec) {
3300 W.startLine() << "There is no .reginfo section in the file.\n";
3301 return;
3304 Expected<ArrayRef<uint8_t>> ContentsOrErr =
3305 Obj.getSectionContents(*RegInfoSec);
3306 if (!ContentsOrErr) {
3307 this->reportUniqueWarning(
3308 "unable to read the content of the .reginfo section (" +
3309 describe(*RegInfoSec) + "): " + toString(ContentsOrErr.takeError()));
3310 return;
3313 if (ContentsOrErr->size() < sizeof(Elf_Mips_RegInfo<ELFT>)) {
3314 this->reportUniqueWarning("the .reginfo section has an invalid size (0x" +
3315 Twine::utohexstr(ContentsOrErr->size()) + ")");
3316 return;
3319 DictScope GS(W, "MIPS RegInfo");
3320 printMipsReginfoData(W, *reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(
3321 ContentsOrErr->data()));
3324 template <class ELFT>
3325 static Expected<const Elf_Mips_Options<ELFT> *>
3326 readMipsOptions(const uint8_t *SecBegin, ArrayRef<uint8_t> &SecData,
3327 bool &IsSupported) {
3328 if (SecData.size() < sizeof(Elf_Mips_Options<ELFT>))
3329 return createError("the .MIPS.options section has an invalid size (0x" +
3330 Twine::utohexstr(SecData.size()) + ")");
3332 const Elf_Mips_Options<ELFT> *O =
3333 reinterpret_cast<const Elf_Mips_Options<ELFT> *>(SecData.data());
3334 const uint8_t Size = O->size;
3335 if (Size > SecData.size()) {
3336 const uint64_t Offset = SecData.data() - SecBegin;
3337 const uint64_t SecSize = Offset + SecData.size();
3338 return createError("a descriptor of size 0x" + Twine::utohexstr(Size) +
3339 " at offset 0x" + Twine::utohexstr(Offset) +
3340 " goes past the end of the .MIPS.options "
3341 "section of size 0x" +
3342 Twine::utohexstr(SecSize));
3345 IsSupported = O->kind == ODK_REGINFO;
3346 const size_t ExpectedSize =
3347 sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>);
3349 if (IsSupported)
3350 if (Size < ExpectedSize)
3351 return createError(
3352 "a .MIPS.options entry of kind " +
3353 Twine(getElfMipsOptionsOdkType(O->kind)) +
3354 " has an invalid size (0x" + Twine::utohexstr(Size) +
3355 "), the expected size is 0x" + Twine::utohexstr(ExpectedSize));
3357 SecData = SecData.drop_front(Size);
3358 return O;
3361 template <class ELFT> void ELFDumper<ELFT>::printMipsOptions() {
3362 const Elf_Shdr *MipsOpts = findSectionByName(".MIPS.options");
3363 if (!MipsOpts) {
3364 W.startLine() << "There is no .MIPS.options section in the file.\n";
3365 return;
3368 DictScope GS(W, "MIPS Options");
3370 ArrayRef<uint8_t> Data =
3371 unwrapOrError(ObjF.getFileName(), Obj.getSectionContents(*MipsOpts));
3372 const uint8_t *const SecBegin = Data.begin();
3373 while (!Data.empty()) {
3374 bool IsSupported;
3375 Expected<const Elf_Mips_Options<ELFT> *> OptsOrErr =
3376 readMipsOptions<ELFT>(SecBegin, Data, IsSupported);
3377 if (!OptsOrErr) {
3378 reportUniqueWarning(OptsOrErr.takeError());
3379 break;
3382 unsigned Kind = (*OptsOrErr)->kind;
3383 const char *Type = getElfMipsOptionsOdkType(Kind);
3384 if (!IsSupported) {
3385 W.startLine() << "Unsupported MIPS options tag: " << Type << " (" << Kind
3386 << ")\n";
3387 continue;
3390 DictScope GS(W, Type);
3391 if (Kind == ODK_REGINFO)
3392 printMipsReginfoData(W, (*OptsOrErr)->getRegInfo());
3393 else
3394 llvm_unreachable("unexpected .MIPS.options section descriptor kind");
3398 template <class ELFT> void ELFDumper<ELFT>::printStackMap() const {
3399 const Elf_Shdr *StackMapSection = findSectionByName(".llvm_stackmaps");
3400 if (!StackMapSection)
3401 return;
3403 auto Warn = [&](Error &&E) {
3404 this->reportUniqueWarning("unable to read the stack map from " +
3405 describe(*StackMapSection) + ": " +
3406 toString(std::move(E)));
3409 Expected<ArrayRef<uint8_t>> ContentOrErr =
3410 Obj.getSectionContents(*StackMapSection);
3411 if (!ContentOrErr) {
3412 Warn(ContentOrErr.takeError());
3413 return;
3416 if (Error E = StackMapParser<ELFT::TargetEndianness>::validateHeader(
3417 *ContentOrErr)) {
3418 Warn(std::move(E));
3419 return;
3422 prettyPrintStackMap(W, StackMapParser<ELFT::TargetEndianness>(*ContentOrErr));
3425 template <class ELFT>
3426 void ELFDumper<ELFT>::printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
3427 const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
3428 Expected<RelSymbol<ELFT>> Target = getRelocationTarget(R, SymTab);
3429 if (!Target)
3430 reportUniqueWarning("unable to print relocation " + Twine(RelIndex) +
3431 " in " + describe(Sec) + ": " +
3432 toString(Target.takeError()));
3433 else
3434 printRelRelaReloc(R, *Target);
3437 template <class ELFT>
3438 std::vector<EnumEntry<unsigned>>
3439 ELFDumper<ELFT>::getOtherFlagsFromSymbol(const Elf_Ehdr &Header,
3440 const Elf_Sym &Symbol) const {
3441 std::vector<EnumEntry<unsigned>> SymOtherFlags(std::begin(ElfSymOtherFlags),
3442 std::end(ElfSymOtherFlags));
3443 if (Header.e_machine == EM_MIPS) {
3444 // Someone in their infinite wisdom decided to make STO_MIPS_MIPS16
3445 // flag overlap with other ST_MIPS_xxx flags. So consider both
3446 // cases separately.
3447 if ((Symbol.st_other & STO_MIPS_MIPS16) == STO_MIPS_MIPS16)
3448 SymOtherFlags.insert(SymOtherFlags.end(),
3449 std::begin(ElfMips16SymOtherFlags),
3450 std::end(ElfMips16SymOtherFlags));
3451 else
3452 SymOtherFlags.insert(SymOtherFlags.end(),
3453 std::begin(ElfMipsSymOtherFlags),
3454 std::end(ElfMipsSymOtherFlags));
3455 } else if (Header.e_machine == EM_AARCH64) {
3456 SymOtherFlags.insert(SymOtherFlags.end(),
3457 std::begin(ElfAArch64SymOtherFlags),
3458 std::end(ElfAArch64SymOtherFlags));
3459 } else if (Header.e_machine == EM_RISCV) {
3460 SymOtherFlags.insert(SymOtherFlags.end(), std::begin(ElfRISCVSymOtherFlags),
3461 std::end(ElfRISCVSymOtherFlags));
3463 return SymOtherFlags;
3466 static inline void printFields(formatted_raw_ostream &OS, StringRef Str1,
3467 StringRef Str2) {
3468 OS.PadToColumn(2u);
3469 OS << Str1;
3470 OS.PadToColumn(37u);
3471 OS << Str2 << "\n";
3472 OS.flush();
3475 template <class ELFT>
3476 static std::string getSectionHeadersNumString(const ELFFile<ELFT> &Obj,
3477 StringRef FileName) {
3478 const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3479 if (ElfHeader.e_shnum != 0)
3480 return to_string(ElfHeader.e_shnum);
3482 Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3483 if (!ArrOrErr) {
3484 // In this case we can ignore an error, because we have already reported a
3485 // warning about the broken section header table earlier.
3486 consumeError(ArrOrErr.takeError());
3487 return "<?>";
3490 if (ArrOrErr->empty())
3491 return "0";
3492 return "0 (" + to_string((*ArrOrErr)[0].sh_size) + ")";
3495 template <class ELFT>
3496 static std::string getSectionHeaderTableIndexString(const ELFFile<ELFT> &Obj,
3497 StringRef FileName) {
3498 const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3499 if (ElfHeader.e_shstrndx != SHN_XINDEX)
3500 return to_string(ElfHeader.e_shstrndx);
3502 Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3503 if (!ArrOrErr) {
3504 // In this case we can ignore an error, because we have already reported a
3505 // warning about the broken section header table earlier.
3506 consumeError(ArrOrErr.takeError());
3507 return "<?>";
3510 if (ArrOrErr->empty())
3511 return "65535 (corrupt: out of range)";
3512 return to_string(ElfHeader.e_shstrndx) + " (" +
3513 to_string((*ArrOrErr)[0].sh_link) + ")";
3516 static const EnumEntry<unsigned> *getObjectFileEnumEntry(unsigned Type) {
3517 auto It = llvm::find_if(ElfObjectFileType, [&](const EnumEntry<unsigned> &E) {
3518 return E.Value == Type;
3520 if (It != ArrayRef(ElfObjectFileType).end())
3521 return It;
3522 return nullptr;
3525 template <class ELFT>
3526 void GNUELFDumper<ELFT>::printFileSummary(StringRef FileStr, ObjectFile &Obj,
3527 ArrayRef<std::string> InputFilenames,
3528 const Archive *A) {
3529 if (InputFilenames.size() > 1 || A) {
3530 this->W.startLine() << "\n";
3531 this->W.printString("File", FileStr);
3535 template <class ELFT> void GNUELFDumper<ELFT>::printFileHeaders() {
3536 const Elf_Ehdr &e = this->Obj.getHeader();
3537 OS << "ELF Header:\n";
3538 OS << " Magic: ";
3539 std::string Str;
3540 for (int i = 0; i < ELF::EI_NIDENT; i++)
3541 OS << format(" %02x", static_cast<int>(e.e_ident[i]));
3542 OS << "\n";
3543 Str = enumToString(e.e_ident[ELF::EI_CLASS], ArrayRef(ElfClass));
3544 printFields(OS, "Class:", Str);
3545 Str = enumToString(e.e_ident[ELF::EI_DATA], ArrayRef(ElfDataEncoding));
3546 printFields(OS, "Data:", Str);
3547 OS.PadToColumn(2u);
3548 OS << "Version:";
3549 OS.PadToColumn(37u);
3550 OS << utohexstr(e.e_ident[ELF::EI_VERSION]);
3551 if (e.e_version == ELF::EV_CURRENT)
3552 OS << " (current)";
3553 OS << "\n";
3554 Str = enumToString(e.e_ident[ELF::EI_OSABI], ArrayRef(ElfOSABI));
3555 printFields(OS, "OS/ABI:", Str);
3556 printFields(OS,
3557 "ABI Version:", std::to_string(e.e_ident[ELF::EI_ABIVERSION]));
3559 if (const EnumEntry<unsigned> *E = getObjectFileEnumEntry(e.e_type)) {
3560 Str = E->AltName.str();
3561 } else {
3562 if (e.e_type >= ET_LOPROC)
3563 Str = "Processor Specific: (" + utohexstr(e.e_type, /*LowerCase=*/true) + ")";
3564 else if (e.e_type >= ET_LOOS)
3565 Str = "OS Specific: (" + utohexstr(e.e_type, /*LowerCase=*/true) + ")";
3566 else
3567 Str = "<unknown>: " + utohexstr(e.e_type, /*LowerCase=*/true);
3569 printFields(OS, "Type:", Str);
3571 Str = enumToString(e.e_machine, ArrayRef(ElfMachineType));
3572 printFields(OS, "Machine:", Str);
3573 Str = "0x" + utohexstr(e.e_version);
3574 printFields(OS, "Version:", Str);
3575 Str = "0x" + utohexstr(e.e_entry);
3576 printFields(OS, "Entry point address:", Str);
3577 Str = to_string(e.e_phoff) + " (bytes into file)";
3578 printFields(OS, "Start of program headers:", Str);
3579 Str = to_string(e.e_shoff) + " (bytes into file)";
3580 printFields(OS, "Start of section headers:", Str);
3581 std::string ElfFlags;
3582 if (e.e_machine == EM_MIPS)
3583 ElfFlags = printFlags(
3584 e.e_flags, ArrayRef(ElfHeaderMipsFlags), unsigned(ELF::EF_MIPS_ARCH),
3585 unsigned(ELF::EF_MIPS_ABI), unsigned(ELF::EF_MIPS_MACH));
3586 else if (e.e_machine == EM_RISCV)
3587 ElfFlags = printFlags(e.e_flags, ArrayRef(ElfHeaderRISCVFlags));
3588 else if (e.e_machine == EM_AVR)
3589 ElfFlags = printFlags(e.e_flags, ArrayRef(ElfHeaderAVRFlags),
3590 unsigned(ELF::EF_AVR_ARCH_MASK));
3591 else if (e.e_machine == EM_LOONGARCH)
3592 ElfFlags = printFlags(e.e_flags, ArrayRef(ElfHeaderLoongArchFlags),
3593 unsigned(ELF::EF_LOONGARCH_ABI_MODIFIER_MASK),
3594 unsigned(ELF::EF_LOONGARCH_OBJABI_MASK));
3595 else if (e.e_machine == EM_XTENSA)
3596 ElfFlags = printFlags(e.e_flags, ArrayRef(ElfHeaderXtensaFlags),
3597 unsigned(ELF::EF_XTENSA_MACH));
3598 Str = "0x" + utohexstr(e.e_flags);
3599 if (!ElfFlags.empty())
3600 Str = Str + ", " + ElfFlags;
3601 printFields(OS, "Flags:", Str);
3602 Str = to_string(e.e_ehsize) + " (bytes)";
3603 printFields(OS, "Size of this header:", Str);
3604 Str = to_string(e.e_phentsize) + " (bytes)";
3605 printFields(OS, "Size of program headers:", Str);
3606 Str = to_string(e.e_phnum);
3607 printFields(OS, "Number of program headers:", Str);
3608 Str = to_string(e.e_shentsize) + " (bytes)";
3609 printFields(OS, "Size of section headers:", Str);
3610 Str = getSectionHeadersNumString(this->Obj, this->FileName);
3611 printFields(OS, "Number of section headers:", Str);
3612 Str = getSectionHeaderTableIndexString(this->Obj, this->FileName);
3613 printFields(OS, "Section header string table index:", Str);
3616 template <class ELFT> std::vector<GroupSection> ELFDumper<ELFT>::getGroups() {
3617 auto GetSignature = [&](const Elf_Sym &Sym, unsigned SymNdx,
3618 const Elf_Shdr &Symtab) -> StringRef {
3619 Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(Symtab);
3620 if (!StrTableOrErr) {
3621 reportUniqueWarning("unable to get the string table for " +
3622 describe(Symtab) + ": " +
3623 toString(StrTableOrErr.takeError()));
3624 return "<?>";
3627 StringRef Strings = *StrTableOrErr;
3628 if (Sym.st_name >= Strings.size()) {
3629 reportUniqueWarning("unable to get the name of the symbol with index " +
3630 Twine(SymNdx) + ": st_name (0x" +
3631 Twine::utohexstr(Sym.st_name) +
3632 ") is past the end of the string table of size 0x" +
3633 Twine::utohexstr(Strings.size()));
3634 return "<?>";
3637 return StrTableOrErr->data() + Sym.st_name;
3640 std::vector<GroupSection> Ret;
3641 uint64_t I = 0;
3642 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
3643 ++I;
3644 if (Sec.sh_type != ELF::SHT_GROUP)
3645 continue;
3647 StringRef Signature = "<?>";
3648 if (Expected<const Elf_Shdr *> SymtabOrErr = Obj.getSection(Sec.sh_link)) {
3649 if (Expected<const Elf_Sym *> SymOrErr =
3650 Obj.template getEntry<Elf_Sym>(**SymtabOrErr, Sec.sh_info))
3651 Signature = GetSignature(**SymOrErr, Sec.sh_info, **SymtabOrErr);
3652 else
3653 reportUniqueWarning("unable to get the signature symbol for " +
3654 describe(Sec) + ": " +
3655 toString(SymOrErr.takeError()));
3656 } else {
3657 reportUniqueWarning("unable to get the symbol table for " +
3658 describe(Sec) + ": " +
3659 toString(SymtabOrErr.takeError()));
3662 ArrayRef<Elf_Word> Data;
3663 if (Expected<ArrayRef<Elf_Word>> ContentsOrErr =
3664 Obj.template getSectionContentsAsArray<Elf_Word>(Sec)) {
3665 if (ContentsOrErr->empty())
3666 reportUniqueWarning("unable to read the section group flag from the " +
3667 describe(Sec) + ": the section is empty");
3668 else
3669 Data = *ContentsOrErr;
3670 } else {
3671 reportUniqueWarning("unable to get the content of the " + describe(Sec) +
3672 ": " + toString(ContentsOrErr.takeError()));
3675 Ret.push_back({getPrintableSectionName(Sec),
3676 maybeDemangle(Signature),
3677 Sec.sh_name,
3678 I - 1,
3679 Sec.sh_link,
3680 Sec.sh_info,
3681 Data.empty() ? Elf_Word(0) : Data[0],
3682 {}});
3684 if (Data.empty())
3685 continue;
3687 std::vector<GroupMember> &GM = Ret.back().Members;
3688 for (uint32_t Ndx : Data.slice(1)) {
3689 if (Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(Ndx)) {
3690 GM.push_back({getPrintableSectionName(**SecOrErr), Ndx});
3691 } else {
3692 reportUniqueWarning("unable to get the section with index " +
3693 Twine(Ndx) + " when dumping the " + describe(Sec) +
3694 ": " + toString(SecOrErr.takeError()));
3695 GM.push_back({"<?>", Ndx});
3699 return Ret;
3702 static DenseMap<uint64_t, const GroupSection *>
3703 mapSectionsToGroups(ArrayRef<GroupSection> Groups) {
3704 DenseMap<uint64_t, const GroupSection *> Ret;
3705 for (const GroupSection &G : Groups)
3706 for (const GroupMember &GM : G.Members)
3707 Ret.insert({GM.Index, &G});
3708 return Ret;
3711 template <class ELFT> void GNUELFDumper<ELFT>::printGroupSections() {
3712 std::vector<GroupSection> V = this->getGroups();
3713 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
3714 for (const GroupSection &G : V) {
3715 OS << "\n"
3716 << getGroupType(G.Type) << " group section ["
3717 << format_decimal(G.Index, 5) << "] `" << G.Name << "' [" << G.Signature
3718 << "] contains " << G.Members.size() << " sections:\n"
3719 << " [Index] Name\n";
3720 for (const GroupMember &GM : G.Members) {
3721 const GroupSection *MainGroup = Map[GM.Index];
3722 if (MainGroup != &G)
3723 this->reportUniqueWarning(
3724 "section with index " + Twine(GM.Index) +
3725 ", included in the group section with index " +
3726 Twine(MainGroup->Index) +
3727 ", was also found in the group section with index " +
3728 Twine(G.Index));
3729 OS << " [" << format_decimal(GM.Index, 5) << "] " << GM.Name << "\n";
3733 if (V.empty())
3734 OS << "There are no section groups in this file.\n";
3737 template <class ELFT>
3738 void GNUELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
3739 OS << to_string(format_hex_no_prefix(R, ELFT::Is64Bits ? 16 : 8)) << "\n";
3742 template <class ELFT>
3743 void GNUELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
3744 const RelSymbol<ELFT> &RelSym) {
3745 // First two fields are bit width dependent. The rest of them are fixed width.
3746 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3747 Field Fields[5] = {0, 10 + Bias, 19 + 2 * Bias, 42 + 2 * Bias, 53 + 2 * Bias};
3748 unsigned Width = ELFT::Is64Bits ? 16 : 8;
3750 Fields[0].Str = to_string(format_hex_no_prefix(R.Offset, Width));
3751 Fields[1].Str = to_string(format_hex_no_prefix(R.Info, Width));
3753 SmallString<32> RelocName;
3754 this->Obj.getRelocationTypeName(R.Type, RelocName);
3755 Fields[2].Str = RelocName.c_str();
3757 if (RelSym.Sym)
3758 Fields[3].Str =
3759 to_string(format_hex_no_prefix(RelSym.Sym->getValue(), Width));
3761 Fields[4].Str = std::string(RelSym.Name);
3762 for (const Field &F : Fields)
3763 printField(F);
3765 std::string Addend;
3766 if (std::optional<int64_t> A = R.Addend) {
3767 int64_t RelAddend = *A;
3768 if (!RelSym.Name.empty()) {
3769 if (RelAddend < 0) {
3770 Addend = " - ";
3771 RelAddend = std::abs(RelAddend);
3772 } else {
3773 Addend = " + ";
3776 Addend += utohexstr(RelAddend, /*LowerCase=*/true);
3778 OS << Addend << "\n";
3781 template <class ELFT>
3782 static void printRelocHeaderFields(formatted_raw_ostream &OS, unsigned SType) {
3783 bool IsRela = SType == ELF::SHT_RELA || SType == ELF::SHT_ANDROID_RELA;
3784 bool IsRelr = SType == ELF::SHT_RELR || SType == ELF::SHT_ANDROID_RELR;
3785 if (ELFT::Is64Bits)
3786 OS << " ";
3787 else
3788 OS << " ";
3789 if (IsRelr && opts::RawRelr)
3790 OS << "Data ";
3791 else
3792 OS << "Offset";
3793 if (ELFT::Is64Bits)
3794 OS << " Info Type"
3795 << " Symbol's Value Symbol's Name";
3796 else
3797 OS << " Info Type Sym. Value Symbol's Name";
3798 if (IsRela)
3799 OS << " + Addend";
3800 OS << "\n";
3803 template <class ELFT>
3804 void GNUELFDumper<ELFT>::printDynamicRelocHeader(unsigned Type, StringRef Name,
3805 const DynRegionInfo &Reg) {
3806 uint64_t Offset = Reg.Addr - this->Obj.base();
3807 OS << "\n'" << Name.str().c_str() << "' relocation section at offset 0x"
3808 << utohexstr(Offset, /*LowerCase=*/true) << " contains " << Reg.Size << " bytes:\n";
3809 printRelocHeaderFields<ELFT>(OS, Type);
3812 template <class ELFT>
3813 static bool isRelocationSec(const typename ELFT::Shdr &Sec) {
3814 return Sec.sh_type == ELF::SHT_REL || Sec.sh_type == ELF::SHT_RELA ||
3815 Sec.sh_type == ELF::SHT_RELR || Sec.sh_type == ELF::SHT_ANDROID_REL ||
3816 Sec.sh_type == ELF::SHT_ANDROID_RELA ||
3817 Sec.sh_type == ELF::SHT_ANDROID_RELR;
3820 template <class ELFT> void GNUELFDumper<ELFT>::printRelocations() {
3821 auto GetEntriesNum = [&](const Elf_Shdr &Sec) -> Expected<size_t> {
3822 // Android's packed relocation section needs to be unpacked first
3823 // to get the actual number of entries.
3824 if (Sec.sh_type == ELF::SHT_ANDROID_REL ||
3825 Sec.sh_type == ELF::SHT_ANDROID_RELA) {
3826 Expected<std::vector<typename ELFT::Rela>> RelasOrErr =
3827 this->Obj.android_relas(Sec);
3828 if (!RelasOrErr)
3829 return RelasOrErr.takeError();
3830 return RelasOrErr->size();
3833 if (!opts::RawRelr && (Sec.sh_type == ELF::SHT_RELR ||
3834 Sec.sh_type == ELF::SHT_ANDROID_RELR)) {
3835 Expected<Elf_Relr_Range> RelrsOrErr = this->Obj.relrs(Sec);
3836 if (!RelrsOrErr)
3837 return RelrsOrErr.takeError();
3838 return this->Obj.decode_relrs(*RelrsOrErr).size();
3841 return Sec.getEntityCount();
3844 bool HasRelocSections = false;
3845 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
3846 if (!isRelocationSec<ELFT>(Sec))
3847 continue;
3848 HasRelocSections = true;
3850 std::string EntriesNum = "<?>";
3851 if (Expected<size_t> NumOrErr = GetEntriesNum(Sec))
3852 EntriesNum = std::to_string(*NumOrErr);
3853 else
3854 this->reportUniqueWarning("unable to get the number of relocations in " +
3855 this->describe(Sec) + ": " +
3856 toString(NumOrErr.takeError()));
3858 uintX_t Offset = Sec.sh_offset;
3859 StringRef Name = this->getPrintableSectionName(Sec);
3860 OS << "\nRelocation section '" << Name << "' at offset 0x"
3861 << utohexstr(Offset, /*LowerCase=*/true) << " contains " << EntriesNum
3862 << " entries:\n";
3863 printRelocHeaderFields<ELFT>(OS, Sec.sh_type);
3864 this->printRelocationsHelper(Sec);
3866 if (!HasRelocSections)
3867 OS << "\nThere are no relocations in this file.\n";
3870 // Print the offset of a particular section from anyone of the ranges:
3871 // [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER].
3872 // If 'Type' does not fall within any of those ranges, then a string is
3873 // returned as '<unknown>' followed by the type value.
3874 static std::string getSectionTypeOffsetString(unsigned Type) {
3875 if (Type >= SHT_LOOS && Type <= SHT_HIOS)
3876 return "LOOS+0x" + utohexstr(Type - SHT_LOOS);
3877 else if (Type >= SHT_LOPROC && Type <= SHT_HIPROC)
3878 return "LOPROC+0x" + utohexstr(Type - SHT_LOPROC);
3879 else if (Type >= SHT_LOUSER && Type <= SHT_HIUSER)
3880 return "LOUSER+0x" + utohexstr(Type - SHT_LOUSER);
3881 return "0x" + utohexstr(Type) + ": <unknown>";
3884 static std::string getSectionTypeString(unsigned Machine, unsigned Type) {
3885 StringRef Name = getELFSectionTypeName(Machine, Type);
3887 // Handle SHT_GNU_* type names.
3888 if (Name.consume_front("SHT_GNU_")) {
3889 if (Name == "HASH")
3890 return "GNU_HASH";
3891 // E.g. SHT_GNU_verneed -> VERNEED.
3892 return Name.upper();
3895 if (Name == "SHT_SYMTAB_SHNDX")
3896 return "SYMTAB SECTION INDICES";
3898 if (Name.consume_front("SHT_"))
3899 return Name.str();
3900 return getSectionTypeOffsetString(Type);
3903 static void printSectionDescription(formatted_raw_ostream &OS,
3904 unsigned EMachine) {
3905 OS << "Key to Flags:\n";
3906 OS << " W (write), A (alloc), X (execute), M (merge), S (strings), I "
3907 "(info),\n";
3908 OS << " L (link order), O (extra OS processing required), G (group), T "
3909 "(TLS),\n";
3910 OS << " C (compressed), x (unknown), o (OS specific), E (exclude),\n";
3911 OS << " R (retain)";
3913 if (EMachine == EM_X86_64)
3914 OS << ", l (large)";
3915 else if (EMachine == EM_ARM)
3916 OS << ", y (purecode)";
3918 OS << ", p (processor specific)\n";
3921 template <class ELFT> void GNUELFDumper<ELFT>::printSectionHeaders() {
3922 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
3923 if (Sections.empty()) {
3924 OS << "\nThere are no sections in this file.\n";
3925 Expected<StringRef> SecStrTableOrErr =
3926 this->Obj.getSectionStringTable(Sections, this->WarningHandler);
3927 if (!SecStrTableOrErr)
3928 this->reportUniqueWarning(SecStrTableOrErr.takeError());
3929 return;
3931 unsigned Bias = ELFT::Is64Bits ? 0 : 8;
3932 OS << "There are " << to_string(Sections.size())
3933 << " section headers, starting at offset "
3934 << "0x" << utohexstr(this->Obj.getHeader().e_shoff, /*LowerCase=*/true) << ":\n\n";
3935 OS << "Section Headers:\n";
3936 Field Fields[11] = {
3937 {"[Nr]", 2}, {"Name", 7}, {"Type", 25},
3938 {"Address", 41}, {"Off", 58 - Bias}, {"Size", 65 - Bias},
3939 {"ES", 72 - Bias}, {"Flg", 75 - Bias}, {"Lk", 79 - Bias},
3940 {"Inf", 82 - Bias}, {"Al", 86 - Bias}};
3941 for (const Field &F : Fields)
3942 printField(F);
3943 OS << "\n";
3945 StringRef SecStrTable;
3946 if (Expected<StringRef> SecStrTableOrErr =
3947 this->Obj.getSectionStringTable(Sections, this->WarningHandler))
3948 SecStrTable = *SecStrTableOrErr;
3949 else
3950 this->reportUniqueWarning(SecStrTableOrErr.takeError());
3952 size_t SectionIndex = 0;
3953 for (const Elf_Shdr &Sec : Sections) {
3954 Fields[0].Str = to_string(SectionIndex);
3955 if (SecStrTable.empty())
3956 Fields[1].Str = "<no-strings>";
3957 else
3958 Fields[1].Str = std::string(unwrapOrError<StringRef>(
3959 this->FileName, this->Obj.getSectionName(Sec, SecStrTable)));
3960 Fields[2].Str =
3961 getSectionTypeString(this->Obj.getHeader().e_machine, Sec.sh_type);
3962 Fields[3].Str =
3963 to_string(format_hex_no_prefix(Sec.sh_addr, ELFT::Is64Bits ? 16 : 8));
3964 Fields[4].Str = to_string(format_hex_no_prefix(Sec.sh_offset, 6));
3965 Fields[5].Str = to_string(format_hex_no_prefix(Sec.sh_size, 6));
3966 Fields[6].Str = to_string(format_hex_no_prefix(Sec.sh_entsize, 2));
3967 Fields[7].Str = getGNUFlags(this->Obj.getHeader().e_ident[ELF::EI_OSABI],
3968 this->Obj.getHeader().e_machine, Sec.sh_flags);
3969 Fields[8].Str = to_string(Sec.sh_link);
3970 Fields[9].Str = to_string(Sec.sh_info);
3971 Fields[10].Str = to_string(Sec.sh_addralign);
3973 OS.PadToColumn(Fields[0].Column);
3974 OS << "[" << right_justify(Fields[0].Str, 2) << "]";
3975 for (int i = 1; i < 7; i++)
3976 printField(Fields[i]);
3977 OS.PadToColumn(Fields[7].Column);
3978 OS << right_justify(Fields[7].Str, 3);
3979 OS.PadToColumn(Fields[8].Column);
3980 OS << right_justify(Fields[8].Str, 2);
3981 OS.PadToColumn(Fields[9].Column);
3982 OS << right_justify(Fields[9].Str, 3);
3983 OS.PadToColumn(Fields[10].Column);
3984 OS << right_justify(Fields[10].Str, 2);
3985 OS << "\n";
3986 ++SectionIndex;
3988 printSectionDescription(OS, this->Obj.getHeader().e_machine);
3991 template <class ELFT>
3992 void GNUELFDumper<ELFT>::printSymtabMessage(const Elf_Shdr *Symtab,
3993 size_t Entries,
3994 bool NonVisibilityBitsUsed) const {
3995 StringRef Name;
3996 if (Symtab)
3997 Name = this->getPrintableSectionName(*Symtab);
3998 if (!Name.empty())
3999 OS << "\nSymbol table '" << Name << "'";
4000 else
4001 OS << "\nSymbol table for image";
4002 OS << " contains " << Entries << " entries:\n";
4004 if (ELFT::Is64Bits)
4005 OS << " Num: Value Size Type Bind Vis";
4006 else
4007 OS << " Num: Value Size Type Bind Vis";
4009 if (NonVisibilityBitsUsed)
4010 OS << " ";
4011 OS << " Ndx Name\n";
4014 template <class ELFT>
4015 std::string
4016 GNUELFDumper<ELFT>::getSymbolSectionNdx(const Elf_Sym &Symbol,
4017 unsigned SymIndex,
4018 DataRegion<Elf_Word> ShndxTable) const {
4019 unsigned SectionIndex = Symbol.st_shndx;
4020 switch (SectionIndex) {
4021 case ELF::SHN_UNDEF:
4022 return "UND";
4023 case ELF::SHN_ABS:
4024 return "ABS";
4025 case ELF::SHN_COMMON:
4026 return "COM";
4027 case ELF::SHN_XINDEX: {
4028 Expected<uint32_t> IndexOrErr =
4029 object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, ShndxTable);
4030 if (!IndexOrErr) {
4031 assert(Symbol.st_shndx == SHN_XINDEX &&
4032 "getExtendedSymbolTableIndex should only fail due to an invalid "
4033 "SHT_SYMTAB_SHNDX table/reference");
4034 this->reportUniqueWarning(IndexOrErr.takeError());
4035 return "RSV[0xffff]";
4037 return to_string(format_decimal(*IndexOrErr, 3));
4039 default:
4040 // Find if:
4041 // Processor specific
4042 if (SectionIndex >= ELF::SHN_LOPROC && SectionIndex <= ELF::SHN_HIPROC)
4043 return std::string("PRC[0x") +
4044 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
4045 // OS specific
4046 if (SectionIndex >= ELF::SHN_LOOS && SectionIndex <= ELF::SHN_HIOS)
4047 return std::string("OS[0x") +
4048 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
4049 // Architecture reserved:
4050 if (SectionIndex >= ELF::SHN_LORESERVE &&
4051 SectionIndex <= ELF::SHN_HIRESERVE)
4052 return std::string("RSV[0x") +
4053 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]";
4054 // A normal section with an index
4055 return to_string(format_decimal(SectionIndex, 3));
4059 template <class ELFT>
4060 void GNUELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
4061 DataRegion<Elf_Word> ShndxTable,
4062 std::optional<StringRef> StrTable,
4063 bool IsDynamic,
4064 bool NonVisibilityBitsUsed) const {
4065 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4066 Field Fields[8] = {0, 8, 17 + Bias, 23 + Bias,
4067 31 + Bias, 38 + Bias, 48 + Bias, 51 + Bias};
4068 Fields[0].Str = to_string(format_decimal(SymIndex, 6)) + ":";
4069 Fields[1].Str =
4070 to_string(format_hex_no_prefix(Symbol.st_value, ELFT::Is64Bits ? 16 : 8));
4071 Fields[2].Str = to_string(format_decimal(Symbol.st_size, 5));
4073 unsigned char SymbolType = Symbol.getType();
4074 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
4075 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
4076 Fields[3].Str = enumToString(SymbolType, ArrayRef(AMDGPUSymbolTypes));
4077 else
4078 Fields[3].Str = enumToString(SymbolType, ArrayRef(ElfSymbolTypes));
4080 Fields[4].Str =
4081 enumToString(Symbol.getBinding(), ArrayRef(ElfSymbolBindings));
4082 Fields[5].Str =
4083 enumToString(Symbol.getVisibility(), ArrayRef(ElfSymbolVisibilities));
4085 if (Symbol.st_other & ~0x3) {
4086 if (this->Obj.getHeader().e_machine == ELF::EM_AARCH64) {
4087 uint8_t Other = Symbol.st_other & ~0x3;
4088 if (Other & STO_AARCH64_VARIANT_PCS) {
4089 Other &= ~STO_AARCH64_VARIANT_PCS;
4090 Fields[5].Str += " [VARIANT_PCS";
4091 if (Other != 0)
4092 Fields[5].Str.append(" | " + utohexstr(Other, /*LowerCase=*/true));
4093 Fields[5].Str.append("]");
4095 } else if (this->Obj.getHeader().e_machine == ELF::EM_RISCV) {
4096 uint8_t Other = Symbol.st_other & ~0x3;
4097 if (Other & STO_RISCV_VARIANT_CC) {
4098 Other &= ~STO_RISCV_VARIANT_CC;
4099 Fields[5].Str += " [VARIANT_CC";
4100 if (Other != 0)
4101 Fields[5].Str.append(" | " + utohexstr(Other, /*LowerCase=*/true));
4102 Fields[5].Str.append("]");
4104 } else {
4105 Fields[5].Str +=
4106 " [<other: " + to_string(format_hex(Symbol.st_other, 2)) + ">]";
4110 Fields[6].Column += NonVisibilityBitsUsed ? 13 : 0;
4111 Fields[6].Str = getSymbolSectionNdx(Symbol, SymIndex, ShndxTable);
4113 Fields[7].Str = this->getFullSymbolName(Symbol, SymIndex, ShndxTable,
4114 StrTable, IsDynamic);
4115 for (const Field &Entry : Fields)
4116 printField(Entry);
4117 OS << "\n";
4120 template <class ELFT>
4121 void GNUELFDumper<ELFT>::printHashedSymbol(const Elf_Sym *Symbol,
4122 unsigned SymIndex,
4123 DataRegion<Elf_Word> ShndxTable,
4124 StringRef StrTable,
4125 uint32_t Bucket) {
4126 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4127 Field Fields[9] = {0, 6, 11, 20 + Bias, 25 + Bias,
4128 34 + Bias, 41 + Bias, 49 + Bias, 53 + Bias};
4129 Fields[0].Str = to_string(format_decimal(SymIndex, 5));
4130 Fields[1].Str = to_string(format_decimal(Bucket, 3)) + ":";
4132 Fields[2].Str = to_string(
4133 format_hex_no_prefix(Symbol->st_value, ELFT::Is64Bits ? 16 : 8));
4134 Fields[3].Str = to_string(format_decimal(Symbol->st_size, 5));
4136 unsigned char SymbolType = Symbol->getType();
4137 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
4138 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
4139 Fields[4].Str = enumToString(SymbolType, ArrayRef(AMDGPUSymbolTypes));
4140 else
4141 Fields[4].Str = enumToString(SymbolType, ArrayRef(ElfSymbolTypes));
4143 Fields[5].Str =
4144 enumToString(Symbol->getBinding(), ArrayRef(ElfSymbolBindings));
4145 Fields[6].Str =
4146 enumToString(Symbol->getVisibility(), ArrayRef(ElfSymbolVisibilities));
4147 Fields[7].Str = getSymbolSectionNdx(*Symbol, SymIndex, ShndxTable);
4148 Fields[8].Str =
4149 this->getFullSymbolName(*Symbol, SymIndex, ShndxTable, StrTable, true);
4151 for (const Field &Entry : Fields)
4152 printField(Entry);
4153 OS << "\n";
4156 template <class ELFT>
4157 void GNUELFDumper<ELFT>::printSymbols(bool PrintSymbols,
4158 bool PrintDynamicSymbols) {
4159 if (!PrintSymbols && !PrintDynamicSymbols)
4160 return;
4161 // GNU readelf prints both the .dynsym and .symtab with --symbols.
4162 this->printSymbolsHelper(true);
4163 if (PrintSymbols)
4164 this->printSymbolsHelper(false);
4167 template <class ELFT>
4168 void GNUELFDumper<ELFT>::printHashTableSymbols(const Elf_Hash &SysVHash) {
4169 if (this->DynamicStringTable.empty())
4170 return;
4172 if (ELFT::Is64Bits)
4173 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4174 else
4175 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4176 OS << "\n";
4178 Elf_Sym_Range DynSyms = this->dynamic_symbols();
4179 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
4180 if (!FirstSym) {
4181 this->reportUniqueWarning(
4182 Twine("unable to print symbols for the .hash table: the "
4183 "dynamic symbol table ") +
4184 (this->DynSymRegion ? "is empty" : "was not found"));
4185 return;
4188 DataRegion<Elf_Word> ShndxTable(
4189 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
4190 auto Buckets = SysVHash.buckets();
4191 auto Chains = SysVHash.chains();
4192 for (uint32_t Buc = 0; Buc < SysVHash.nbucket; Buc++) {
4193 if (Buckets[Buc] == ELF::STN_UNDEF)
4194 continue;
4195 BitVector Visited(SysVHash.nchain);
4196 for (uint32_t Ch = Buckets[Buc]; Ch < SysVHash.nchain; Ch = Chains[Ch]) {
4197 if (Ch == ELF::STN_UNDEF)
4198 break;
4200 if (Visited[Ch]) {
4201 this->reportUniqueWarning(".hash section is invalid: bucket " +
4202 Twine(Ch) +
4203 ": a cycle was detected in the linked chain");
4204 break;
4207 printHashedSymbol(FirstSym + Ch, Ch, ShndxTable, this->DynamicStringTable,
4208 Buc);
4209 Visited[Ch] = true;
4214 template <class ELFT>
4215 void GNUELFDumper<ELFT>::printGnuHashTableSymbols(const Elf_GnuHash &GnuHash) {
4216 if (this->DynamicStringTable.empty())
4217 return;
4219 Elf_Sym_Range DynSyms = this->dynamic_symbols();
4220 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
4221 if (!FirstSym) {
4222 this->reportUniqueWarning(
4223 Twine("unable to print symbols for the .gnu.hash table: the "
4224 "dynamic symbol table ") +
4225 (this->DynSymRegion ? "is empty" : "was not found"));
4226 return;
4229 auto GetSymbol = [&](uint64_t SymIndex,
4230 uint64_t SymsTotal) -> const Elf_Sym * {
4231 if (SymIndex >= SymsTotal) {
4232 this->reportUniqueWarning(
4233 "unable to print hashed symbol with index " + Twine(SymIndex) +
4234 ", which is greater than or equal to the number of dynamic symbols "
4235 "(" +
4236 Twine::utohexstr(SymsTotal) + ")");
4237 return nullptr;
4239 return FirstSym + SymIndex;
4242 Expected<ArrayRef<Elf_Word>> ValuesOrErr =
4243 getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHash);
4244 ArrayRef<Elf_Word> Values;
4245 if (!ValuesOrErr)
4246 this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH "
4247 "section: " +
4248 toString(ValuesOrErr.takeError()));
4249 else
4250 Values = *ValuesOrErr;
4252 DataRegion<Elf_Word> ShndxTable(
4253 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
4254 ArrayRef<Elf_Word> Buckets = GnuHash.buckets();
4255 for (uint32_t Buc = 0; Buc < GnuHash.nbuckets; Buc++) {
4256 if (Buckets[Buc] == ELF::STN_UNDEF)
4257 continue;
4258 uint32_t Index = Buckets[Buc];
4259 // Print whole chain.
4260 while (true) {
4261 uint32_t SymIndex = Index++;
4262 if (const Elf_Sym *Sym = GetSymbol(SymIndex, DynSyms.size()))
4263 printHashedSymbol(Sym, SymIndex, ShndxTable, this->DynamicStringTable,
4264 Buc);
4265 else
4266 break;
4268 if (SymIndex < GnuHash.symndx) {
4269 this->reportUniqueWarning(
4270 "unable to read the hash value for symbol with index " +
4271 Twine(SymIndex) +
4272 ", which is less than the index of the first hashed symbol (" +
4273 Twine(GnuHash.symndx) + ")");
4274 break;
4277 // Chain ends at symbol with stopper bit.
4278 if ((Values[SymIndex - GnuHash.symndx] & 1) == 1)
4279 break;
4284 template <class ELFT> void GNUELFDumper<ELFT>::printHashSymbols() {
4285 if (this->HashTable) {
4286 OS << "\n Symbol table of .hash for image:\n";
4287 if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
4288 this->reportUniqueWarning(std::move(E));
4289 else
4290 printHashTableSymbols(*this->HashTable);
4293 // Try printing the .gnu.hash table.
4294 if (this->GnuHashTable) {
4295 OS << "\n Symbol table of .gnu.hash for image:\n";
4296 if (ELFT::Is64Bits)
4297 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4298 else
4299 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4300 OS << "\n";
4302 if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
4303 this->reportUniqueWarning(std::move(E));
4304 else
4305 printGnuHashTableSymbols(*this->GnuHashTable);
4309 template <class ELFT> void GNUELFDumper<ELFT>::printSectionDetails() {
4310 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
4311 if (Sections.empty()) {
4312 OS << "\nThere are no sections in this file.\n";
4313 Expected<StringRef> SecStrTableOrErr =
4314 this->Obj.getSectionStringTable(Sections, this->WarningHandler);
4315 if (!SecStrTableOrErr)
4316 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4317 return;
4319 OS << "There are " << to_string(Sections.size())
4320 << " section headers, starting at offset "
4321 << "0x" << utohexstr(this->Obj.getHeader().e_shoff, /*LowerCase=*/true) << ":\n\n";
4323 OS << "Section Headers:\n";
4325 auto PrintFields = [&](ArrayRef<Field> V) {
4326 for (const Field &F : V)
4327 printField(F);
4328 OS << "\n";
4331 PrintFields({{"[Nr]", 2}, {"Name", 7}});
4333 constexpr bool Is64 = ELFT::Is64Bits;
4334 PrintFields({{"Type", 7},
4335 {Is64 ? "Address" : "Addr", 23},
4336 {"Off", Is64 ? 40 : 32},
4337 {"Size", Is64 ? 47 : 39},
4338 {"ES", Is64 ? 54 : 46},
4339 {"Lk", Is64 ? 59 : 51},
4340 {"Inf", Is64 ? 62 : 54},
4341 {"Al", Is64 ? 66 : 57}});
4342 PrintFields({{"Flags", 7}});
4344 StringRef SecStrTable;
4345 if (Expected<StringRef> SecStrTableOrErr =
4346 this->Obj.getSectionStringTable(Sections, this->WarningHandler))
4347 SecStrTable = *SecStrTableOrErr;
4348 else
4349 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4351 size_t SectionIndex = 0;
4352 const unsigned AddrSize = Is64 ? 16 : 8;
4353 for (const Elf_Shdr &S : Sections) {
4354 StringRef Name = "<?>";
4355 if (Expected<StringRef> NameOrErr =
4356 this->Obj.getSectionName(S, SecStrTable))
4357 Name = *NameOrErr;
4358 else
4359 this->reportUniqueWarning(NameOrErr.takeError());
4361 OS.PadToColumn(2);
4362 OS << "[" << right_justify(to_string(SectionIndex), 2) << "]";
4363 PrintFields({{Name, 7}});
4364 PrintFields(
4365 {{getSectionTypeString(this->Obj.getHeader().e_machine, S.sh_type), 7},
4366 {to_string(format_hex_no_prefix(S.sh_addr, AddrSize)), 23},
4367 {to_string(format_hex_no_prefix(S.sh_offset, 6)), Is64 ? 39 : 32},
4368 {to_string(format_hex_no_prefix(S.sh_size, 6)), Is64 ? 47 : 39},
4369 {to_string(format_hex_no_prefix(S.sh_entsize, 2)), Is64 ? 54 : 46},
4370 {to_string(S.sh_link), Is64 ? 59 : 51},
4371 {to_string(S.sh_info), Is64 ? 63 : 55},
4372 {to_string(S.sh_addralign), Is64 ? 66 : 58}});
4374 OS.PadToColumn(7);
4375 OS << "[" << to_string(format_hex_no_prefix(S.sh_flags, AddrSize)) << "]: ";
4377 DenseMap<unsigned, StringRef> FlagToName = {
4378 {SHF_WRITE, "WRITE"}, {SHF_ALLOC, "ALLOC"},
4379 {SHF_EXECINSTR, "EXEC"}, {SHF_MERGE, "MERGE"},
4380 {SHF_STRINGS, "STRINGS"}, {SHF_INFO_LINK, "INFO LINK"},
4381 {SHF_LINK_ORDER, "LINK ORDER"}, {SHF_OS_NONCONFORMING, "OS NONCONF"},
4382 {SHF_GROUP, "GROUP"}, {SHF_TLS, "TLS"},
4383 {SHF_COMPRESSED, "COMPRESSED"}, {SHF_EXCLUDE, "EXCLUDE"}};
4385 uint64_t Flags = S.sh_flags;
4386 uint64_t UnknownFlags = 0;
4387 ListSeparator LS;
4388 while (Flags) {
4389 // Take the least significant bit as a flag.
4390 uint64_t Flag = Flags & -Flags;
4391 Flags -= Flag;
4393 auto It = FlagToName.find(Flag);
4394 if (It != FlagToName.end())
4395 OS << LS << It->second;
4396 else
4397 UnknownFlags |= Flag;
4400 auto PrintUnknownFlags = [&](uint64_t Mask, StringRef Name) {
4401 uint64_t FlagsToPrint = UnknownFlags & Mask;
4402 if (!FlagsToPrint)
4403 return;
4405 OS << LS << Name << " ("
4406 << to_string(format_hex_no_prefix(FlagsToPrint, AddrSize)) << ")";
4407 UnknownFlags &= ~Mask;
4410 PrintUnknownFlags(SHF_MASKOS, "OS");
4411 PrintUnknownFlags(SHF_MASKPROC, "PROC");
4412 PrintUnknownFlags(uint64_t(-1), "UNKNOWN");
4414 OS << "\n";
4415 ++SectionIndex;
4417 if (!(S.sh_flags & SHF_COMPRESSED))
4418 continue;
4419 Expected<ArrayRef<uint8_t>> Data = this->Obj.getSectionContents(S);
4420 if (!Data || Data->size() < sizeof(Elf_Chdr)) {
4421 consumeError(Data.takeError());
4422 reportWarning(createError("SHF_COMPRESSED section '" + Name +
4423 "' does not have an Elf_Chdr header"),
4424 this->FileName);
4425 OS.indent(7);
4426 OS << "[<corrupt>]";
4427 } else {
4428 OS.indent(7);
4429 auto *Chdr = reinterpret_cast<const Elf_Chdr *>(Data->data());
4430 if (Chdr->ch_type == ELFCOMPRESS_ZLIB)
4431 OS << "ZLIB";
4432 else if (Chdr->ch_type == ELFCOMPRESS_ZSTD)
4433 OS << "ZSTD";
4434 else
4435 OS << format("[<unknown>: 0x%x]", unsigned(Chdr->ch_type));
4436 OS << ", " << format_hex_no_prefix(Chdr->ch_size, ELFT::Is64Bits ? 16 : 8)
4437 << ", " << Chdr->ch_addralign;
4439 OS << '\n';
4443 static inline std::string printPhdrFlags(unsigned Flag) {
4444 std::string Str;
4445 Str = (Flag & PF_R) ? "R" : " ";
4446 Str += (Flag & PF_W) ? "W" : " ";
4447 Str += (Flag & PF_X) ? "E" : " ";
4448 return Str;
4451 template <class ELFT>
4452 static bool checkTLSSections(const typename ELFT::Phdr &Phdr,
4453 const typename ELFT::Shdr &Sec) {
4454 if (Sec.sh_flags & ELF::SHF_TLS) {
4455 // .tbss must only be shown in the PT_TLS segment.
4456 if (Sec.sh_type == ELF::SHT_NOBITS)
4457 return Phdr.p_type == ELF::PT_TLS;
4459 // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO
4460 // segments.
4461 return (Phdr.p_type == ELF::PT_TLS) || (Phdr.p_type == ELF::PT_LOAD) ||
4462 (Phdr.p_type == ELF::PT_GNU_RELRO);
4465 // PT_TLS must only have SHF_TLS sections.
4466 return Phdr.p_type != ELF::PT_TLS;
4469 template <class ELFT>
4470 static bool checkOffsets(const typename ELFT::Phdr &Phdr,
4471 const typename ELFT::Shdr &Sec) {
4472 // SHT_NOBITS sections don't need to have an offset inside the segment.
4473 if (Sec.sh_type == ELF::SHT_NOBITS)
4474 return true;
4476 if (Sec.sh_offset < Phdr.p_offset)
4477 return false;
4479 // Only non-empty sections can be at the end of a segment.
4480 if (Sec.sh_size == 0)
4481 return (Sec.sh_offset + 1 <= Phdr.p_offset + Phdr.p_filesz);
4482 return Sec.sh_offset + Sec.sh_size <= Phdr.p_offset + Phdr.p_filesz;
4485 // Check that an allocatable section belongs to a virtual address
4486 // space of a segment.
4487 template <class ELFT>
4488 static bool checkVMA(const typename ELFT::Phdr &Phdr,
4489 const typename ELFT::Shdr &Sec) {
4490 if (!(Sec.sh_flags & ELF::SHF_ALLOC))
4491 return true;
4493 if (Sec.sh_addr < Phdr.p_vaddr)
4494 return false;
4496 bool IsTbss =
4497 (Sec.sh_type == ELF::SHT_NOBITS) && ((Sec.sh_flags & ELF::SHF_TLS) != 0);
4498 // .tbss is special, it only has memory in PT_TLS and has NOBITS properties.
4499 bool IsTbssInNonTLS = IsTbss && Phdr.p_type != ELF::PT_TLS;
4500 // Only non-empty sections can be at the end of a segment.
4501 if (Sec.sh_size == 0 || IsTbssInNonTLS)
4502 return Sec.sh_addr + 1 <= Phdr.p_vaddr + Phdr.p_memsz;
4503 return Sec.sh_addr + Sec.sh_size <= Phdr.p_vaddr + Phdr.p_memsz;
4506 template <class ELFT>
4507 static bool checkPTDynamic(const typename ELFT::Phdr &Phdr,
4508 const typename ELFT::Shdr &Sec) {
4509 if (Phdr.p_type != ELF::PT_DYNAMIC || Phdr.p_memsz == 0 || Sec.sh_size != 0)
4510 return true;
4512 // We get here when we have an empty section. Only non-empty sections can be
4513 // at the start or at the end of PT_DYNAMIC.
4514 // Is section within the phdr both based on offset and VMA?
4515 bool CheckOffset = (Sec.sh_type == ELF::SHT_NOBITS) ||
4516 (Sec.sh_offset > Phdr.p_offset &&
4517 Sec.sh_offset < Phdr.p_offset + Phdr.p_filesz);
4518 bool CheckVA = !(Sec.sh_flags & ELF::SHF_ALLOC) ||
4519 (Sec.sh_addr > Phdr.p_vaddr && Sec.sh_addr < Phdr.p_memsz);
4520 return CheckOffset && CheckVA;
4523 template <class ELFT>
4524 void GNUELFDumper<ELFT>::printProgramHeaders(
4525 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
4526 const bool ShouldPrintSectionMapping = (PrintSectionMapping != cl::BOU_FALSE);
4527 // Exit early if no program header or section mapping details were requested.
4528 if (!PrintProgramHeaders && !ShouldPrintSectionMapping)
4529 return;
4531 if (PrintProgramHeaders) {
4532 const Elf_Ehdr &Header = this->Obj.getHeader();
4533 if (Header.e_phnum == 0) {
4534 OS << "\nThere are no program headers in this file.\n";
4535 } else {
4536 printProgramHeaders();
4540 if (ShouldPrintSectionMapping)
4541 printSectionMapping();
4544 template <class ELFT> void GNUELFDumper<ELFT>::printProgramHeaders() {
4545 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4546 const Elf_Ehdr &Header = this->Obj.getHeader();
4547 Field Fields[8] = {2, 17, 26, 37 + Bias,
4548 48 + Bias, 56 + Bias, 64 + Bias, 68 + Bias};
4549 OS << "\nElf file type is "
4550 << enumToString(Header.e_type, ArrayRef(ElfObjectFileType)) << "\n"
4551 << "Entry point " << format_hex(Header.e_entry, 3) << "\n"
4552 << "There are " << Header.e_phnum << " program headers,"
4553 << " starting at offset " << Header.e_phoff << "\n\n"
4554 << "Program Headers:\n";
4555 if (ELFT::Is64Bits)
4556 OS << " Type Offset VirtAddr PhysAddr "
4557 << " FileSiz MemSiz Flg Align\n";
4558 else
4559 OS << " Type Offset VirtAddr PhysAddr FileSiz "
4560 << "MemSiz Flg Align\n";
4562 unsigned Width = ELFT::Is64Bits ? 18 : 10;
4563 unsigned SizeWidth = ELFT::Is64Bits ? 8 : 7;
4565 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4566 if (!PhdrsOrErr) {
4567 this->reportUniqueWarning("unable to dump program headers: " +
4568 toString(PhdrsOrErr.takeError()));
4569 return;
4572 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4573 Fields[0].Str = getGNUPtType(Header.e_machine, Phdr.p_type);
4574 Fields[1].Str = to_string(format_hex(Phdr.p_offset, 8));
4575 Fields[2].Str = to_string(format_hex(Phdr.p_vaddr, Width));
4576 Fields[3].Str = to_string(format_hex(Phdr.p_paddr, Width));
4577 Fields[4].Str = to_string(format_hex(Phdr.p_filesz, SizeWidth));
4578 Fields[5].Str = to_string(format_hex(Phdr.p_memsz, SizeWidth));
4579 Fields[6].Str = printPhdrFlags(Phdr.p_flags);
4580 Fields[7].Str = to_string(format_hex(Phdr.p_align, 1));
4581 for (const Field &F : Fields)
4582 printField(F);
4583 if (Phdr.p_type == ELF::PT_INTERP) {
4584 OS << "\n";
4585 auto ReportBadInterp = [&](const Twine &Msg) {
4586 this->reportUniqueWarning(
4587 "unable to read program interpreter name at offset 0x" +
4588 Twine::utohexstr(Phdr.p_offset) + ": " + Msg);
4591 if (Phdr.p_offset >= this->Obj.getBufSize()) {
4592 ReportBadInterp("it goes past the end of the file (0x" +
4593 Twine::utohexstr(this->Obj.getBufSize()) + ")");
4594 continue;
4597 const char *Data =
4598 reinterpret_cast<const char *>(this->Obj.base()) + Phdr.p_offset;
4599 size_t MaxSize = this->Obj.getBufSize() - Phdr.p_offset;
4600 size_t Len = strnlen(Data, MaxSize);
4601 if (Len == MaxSize) {
4602 ReportBadInterp("it is not null-terminated");
4603 continue;
4606 OS << " [Requesting program interpreter: ";
4607 OS << StringRef(Data, Len) << "]";
4609 OS << "\n";
4613 template <class ELFT> void GNUELFDumper<ELFT>::printSectionMapping() {
4614 OS << "\n Section to Segment mapping:\n Segment Sections...\n";
4615 DenseSet<const Elf_Shdr *> BelongsToSegment;
4616 int Phnum = 0;
4618 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4619 if (!PhdrsOrErr) {
4620 this->reportUniqueWarning(
4621 "can't read program headers to build section to segment mapping: " +
4622 toString(PhdrsOrErr.takeError()));
4623 return;
4626 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4627 std::string Sections;
4628 OS << format(" %2.2d ", Phnum++);
4629 // Check if each section is in a segment and then print mapping.
4630 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4631 if (Sec.sh_type == ELF::SHT_NULL)
4632 continue;
4634 // readelf additionally makes sure it does not print zero sized sections
4635 // at end of segments and for PT_DYNAMIC both start and end of section
4636 // .tbss must only be shown in PT_TLS section.
4637 if (checkTLSSections<ELFT>(Phdr, Sec) && checkOffsets<ELFT>(Phdr, Sec) &&
4638 checkVMA<ELFT>(Phdr, Sec) && checkPTDynamic<ELFT>(Phdr, Sec)) {
4639 Sections +=
4640 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4641 " ";
4642 BelongsToSegment.insert(&Sec);
4645 OS << Sections << "\n";
4646 OS.flush();
4649 // Display sections that do not belong to a segment.
4650 std::string Sections;
4651 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4652 if (BelongsToSegment.find(&Sec) == BelongsToSegment.end())
4653 Sections +=
4654 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4655 ' ';
4657 if (!Sections.empty()) {
4658 OS << " None " << Sections << '\n';
4659 OS.flush();
4663 namespace {
4665 template <class ELFT>
4666 RelSymbol<ELFT> getSymbolForReloc(const ELFDumper<ELFT> &Dumper,
4667 const Relocation<ELFT> &Reloc) {
4668 using Elf_Sym = typename ELFT::Sym;
4669 auto WarnAndReturn = [&](const Elf_Sym *Sym,
4670 const Twine &Reason) -> RelSymbol<ELFT> {
4671 Dumper.reportUniqueWarning(
4672 "unable to get name of the dynamic symbol with index " +
4673 Twine(Reloc.Symbol) + ": " + Reason);
4674 return {Sym, "<corrupt>"};
4677 ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols();
4678 const Elf_Sym *FirstSym = Symbols.begin();
4679 if (!FirstSym)
4680 return WarnAndReturn(nullptr, "no dynamic symbol table found");
4682 // We might have an object without a section header. In this case the size of
4683 // Symbols is zero, because there is no way to know the size of the dynamic
4684 // table. We should allow this case and not print a warning.
4685 if (!Symbols.empty() && Reloc.Symbol >= Symbols.size())
4686 return WarnAndReturn(
4687 nullptr,
4688 "index is greater than or equal to the number of dynamic symbols (" +
4689 Twine(Symbols.size()) + ")");
4691 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
4692 const uint64_t FileSize = Obj.getBufSize();
4693 const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) +
4694 (uint64_t)Reloc.Symbol * sizeof(Elf_Sym);
4695 if (SymOffset + sizeof(Elf_Sym) > FileSize)
4696 return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(SymOffset) +
4697 " goes past the end of the file (0x" +
4698 Twine::utohexstr(FileSize) + ")");
4700 const Elf_Sym *Sym = FirstSym + Reloc.Symbol;
4701 Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable());
4702 if (!ErrOrName)
4703 return WarnAndReturn(Sym, toString(ErrOrName.takeError()));
4705 return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(*ErrOrName)};
4707 } // namespace
4709 template <class ELFT>
4710 static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj,
4711 typename ELFT::DynRange Tags) {
4712 size_t Max = 0;
4713 for (const typename ELFT::Dyn &Dyn : Tags)
4714 Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size());
4715 return Max;
4718 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicTable() {
4719 Elf_Dyn_Range Table = this->dynamic_table();
4720 if (Table.empty())
4721 return;
4723 OS << "Dynamic section at offset "
4724 << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable.Addr) -
4725 this->Obj.base(),
4727 << " contains " << Table.size() << " entries:\n";
4729 // The type name is surrounded with round brackets, hence add 2.
4730 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2;
4731 // The "Name/Value" column should be indented from the "Type" column by N
4732 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
4733 // space (1) = 3.
4734 OS << " Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type"
4735 << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
4737 std::string ValueFmt = " %-" + std::to_string(MaxTagSize) + "s ";
4738 for (auto Entry : Table) {
4739 uintX_t Tag = Entry.getTag();
4740 std::string Type =
4741 std::string("(") + this->Obj.getDynamicTagAsString(Tag) + ")";
4742 std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
4743 OS << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10)
4744 << format(ValueFmt.c_str(), Type.c_str()) << Value << "\n";
4748 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicRelocations() {
4749 this->printDynamicRelocationsHelper();
4752 template <class ELFT>
4753 void ELFDumper<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) {
4754 printRelRelaReloc(R, getSymbolForReloc(*this, R));
4757 template <class ELFT>
4758 void ELFDumper<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) {
4759 this->forEachRelocationDo(
4760 Sec, opts::RawRelr,
4761 [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
4762 const Elf_Shdr *SymTab) { printReloc(R, Ndx, Sec, SymTab); },
4763 [&](const Elf_Relr &R) { printRelrReloc(R); });
4766 template <class ELFT> void ELFDumper<ELFT>::printDynamicRelocationsHelper() {
4767 const bool IsMips64EL = this->Obj.isMips64EL();
4768 if (this->DynRelaRegion.Size > 0) {
4769 printDynamicRelocHeader(ELF::SHT_RELA, "RELA", this->DynRelaRegion);
4770 for (const Elf_Rela &Rela :
4771 this->DynRelaRegion.template getAsArrayRef<Elf_Rela>())
4772 printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
4775 if (this->DynRelRegion.Size > 0) {
4776 printDynamicRelocHeader(ELF::SHT_REL, "REL", this->DynRelRegion);
4777 for (const Elf_Rel &Rel :
4778 this->DynRelRegion.template getAsArrayRef<Elf_Rel>())
4779 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4782 if (this->DynRelrRegion.Size > 0) {
4783 printDynamicRelocHeader(ELF::SHT_REL, "RELR", this->DynRelrRegion);
4784 Elf_Relr_Range Relrs =
4785 this->DynRelrRegion.template getAsArrayRef<Elf_Relr>();
4786 for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs))
4787 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4790 if (this->DynPLTRelRegion.Size) {
4791 if (this->DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) {
4792 printDynamicRelocHeader(ELF::SHT_RELA, "PLT", this->DynPLTRelRegion);
4793 for (const Elf_Rela &Rela :
4794 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rela>())
4795 printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL));
4796 } else {
4797 printDynamicRelocHeader(ELF::SHT_REL, "PLT", this->DynPLTRelRegion);
4798 for (const Elf_Rel &Rel :
4799 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rel>())
4800 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL));
4805 template <class ELFT>
4806 void GNUELFDumper<ELFT>::printGNUVersionSectionProlog(
4807 const typename ELFT::Shdr &Sec, const Twine &Label, unsigned EntriesNum) {
4808 // Don't inline the SecName, because it might report a warning to stderr and
4809 // corrupt the output.
4810 StringRef SecName = this->getPrintableSectionName(Sec);
4811 OS << Label << " section '" << SecName << "' "
4812 << "contains " << EntriesNum << " entries:\n";
4814 StringRef LinkedSecName = "<corrupt>";
4815 if (Expected<const typename ELFT::Shdr *> LinkedSecOrErr =
4816 this->Obj.getSection(Sec.sh_link))
4817 LinkedSecName = this->getPrintableSectionName(**LinkedSecOrErr);
4818 else
4819 this->reportUniqueWarning("invalid section linked to " +
4820 this->describe(Sec) + ": " +
4821 toString(LinkedSecOrErr.takeError()));
4823 OS << " Addr: " << format_hex_no_prefix(Sec.sh_addr, 16)
4824 << " Offset: " << format_hex(Sec.sh_offset, 8)
4825 << " Link: " << Sec.sh_link << " (" << LinkedSecName << ")\n";
4828 template <class ELFT>
4829 void GNUELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
4830 if (!Sec)
4831 return;
4833 printGNUVersionSectionProlog(*Sec, "Version symbols",
4834 Sec->sh_size / sizeof(Elf_Versym));
4835 Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
4836 this->getVersionTable(*Sec, /*SymTab=*/nullptr,
4837 /*StrTab=*/nullptr, /*SymTabSec=*/nullptr);
4838 if (!VerTableOrErr) {
4839 this->reportUniqueWarning(VerTableOrErr.takeError());
4840 return;
4843 SmallVector<std::optional<VersionEntry>, 0> *VersionMap = nullptr;
4844 if (Expected<SmallVector<std::optional<VersionEntry>, 0> *> MapOrErr =
4845 this->getVersionMap())
4846 VersionMap = *MapOrErr;
4847 else
4848 this->reportUniqueWarning(MapOrErr.takeError());
4850 ArrayRef<Elf_Versym> VerTable = *VerTableOrErr;
4851 std::vector<StringRef> Versions;
4852 for (size_t I = 0, E = VerTable.size(); I < E; ++I) {
4853 unsigned Ndx = VerTable[I].vs_index;
4854 if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) {
4855 Versions.emplace_back(Ndx == VER_NDX_LOCAL ? "*local*" : "*global*");
4856 continue;
4859 if (!VersionMap) {
4860 Versions.emplace_back("<corrupt>");
4861 continue;
4864 bool IsDefault;
4865 Expected<StringRef> NameOrErr = this->Obj.getSymbolVersionByIndex(
4866 Ndx, IsDefault, *VersionMap, /*IsSymHidden=*/std::nullopt);
4867 if (!NameOrErr) {
4868 this->reportUniqueWarning("unable to get a version for entry " +
4869 Twine(I) + " of " + this->describe(*Sec) +
4870 ": " + toString(NameOrErr.takeError()));
4871 Versions.emplace_back("<corrupt>");
4872 continue;
4874 Versions.emplace_back(*NameOrErr);
4877 // readelf prints 4 entries per line.
4878 uint64_t Entries = VerTable.size();
4879 for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) {
4880 OS << " " << format_hex_no_prefix(VersymRow, 3) << ":";
4881 for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) {
4882 unsigned Ndx = VerTable[VersymRow + I].vs_index;
4883 OS << format("%4x%c", Ndx & VERSYM_VERSION,
4884 Ndx & VERSYM_HIDDEN ? 'h' : ' ');
4885 OS << left_justify("(" + std::string(Versions[VersymRow + I]) + ")", 13);
4887 OS << '\n';
4889 OS << '\n';
4892 static std::string versionFlagToString(unsigned Flags) {
4893 if (Flags == 0)
4894 return "none";
4896 std::string Ret;
4897 auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) {
4898 if (!(Flags & Flag))
4899 return;
4900 if (!Ret.empty())
4901 Ret += " | ";
4902 Ret += Name;
4903 Flags &= ~Flag;
4906 AddFlag(VER_FLG_BASE, "BASE");
4907 AddFlag(VER_FLG_WEAK, "WEAK");
4908 AddFlag(VER_FLG_INFO, "INFO");
4909 AddFlag(~0, "<unknown>");
4910 return Ret;
4913 template <class ELFT>
4914 void GNUELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
4915 if (!Sec)
4916 return;
4918 printGNUVersionSectionProlog(*Sec, "Version definition", Sec->sh_info);
4920 Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
4921 if (!V) {
4922 this->reportUniqueWarning(V.takeError());
4923 return;
4926 for (const VerDef &Def : *V) {
4927 OS << format(" 0x%04x: Rev: %u Flags: %s Index: %u Cnt: %u Name: %s\n",
4928 Def.Offset, Def.Version,
4929 versionFlagToString(Def.Flags).c_str(), Def.Ndx, Def.Cnt,
4930 Def.Name.data());
4931 unsigned I = 0;
4932 for (const VerdAux &Aux : Def.AuxV)
4933 OS << format(" 0x%04x: Parent %u: %s\n", Aux.Offset, ++I,
4934 Aux.Name.data());
4937 OS << '\n';
4940 template <class ELFT>
4941 void GNUELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
4942 if (!Sec)
4943 return;
4945 unsigned VerneedNum = Sec->sh_info;
4946 printGNUVersionSectionProlog(*Sec, "Version needs", VerneedNum);
4948 Expected<std::vector<VerNeed>> V =
4949 this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
4950 if (!V) {
4951 this->reportUniqueWarning(V.takeError());
4952 return;
4955 for (const VerNeed &VN : *V) {
4956 OS << format(" 0x%04x: Version: %u File: %s Cnt: %u\n", VN.Offset,
4957 VN.Version, VN.File.data(), VN.Cnt);
4958 for (const VernAux &Aux : VN.AuxV)
4959 OS << format(" 0x%04x: Name: %s Flags: %s Version: %u\n", Aux.Offset,
4960 Aux.Name.data(), versionFlagToString(Aux.Flags).c_str(),
4961 Aux.Other);
4963 OS << '\n';
4966 template <class ELFT>
4967 void GNUELFDumper<ELFT>::printHashHistogramStats(size_t NBucket,
4968 size_t MaxChain,
4969 size_t TotalSyms,
4970 ArrayRef<size_t> Count,
4971 bool IsGnu) const {
4972 size_t CumulativeNonZero = 0;
4973 OS << "Histogram for" << (IsGnu ? " `.gnu.hash'" : "")
4974 << " bucket list length (total of " << NBucket << " buckets)\n"
4975 << " Length Number % of total Coverage\n";
4976 for (size_t I = 0; I < MaxChain; ++I) {
4977 CumulativeNonZero += Count[I] * I;
4978 OS << format("%7lu %-10lu (%5.1f%%) %5.1f%%\n", I, Count[I],
4979 (Count[I] * 100.0) / NBucket,
4980 (CumulativeNonZero * 100.0) / TotalSyms);
4984 template <class ELFT> void GNUELFDumper<ELFT>::printCGProfile() {
4985 OS << "GNUStyle::printCGProfile not implemented\n";
4988 template <class ELFT> void GNUELFDumper<ELFT>::printBBAddrMaps() {
4989 OS << "GNUStyle::printBBAddrMaps not implemented\n";
4992 static Expected<std::vector<uint64_t>> toULEB128Array(ArrayRef<uint8_t> Data) {
4993 std::vector<uint64_t> Ret;
4994 const uint8_t *Cur = Data.begin();
4995 const uint8_t *End = Data.end();
4996 while (Cur != End) {
4997 unsigned Size;
4998 const char *Err;
4999 Ret.push_back(decodeULEB128(Cur, &Size, End, &Err));
5000 if (Err)
5001 return createError(Err);
5002 Cur += Size;
5004 return Ret;
5007 template <class ELFT>
5008 static Expected<std::vector<uint64_t>>
5009 decodeAddrsigSection(const ELFFile<ELFT> &Obj, const typename ELFT::Shdr &Sec) {
5010 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Sec);
5011 if (!ContentsOrErr)
5012 return ContentsOrErr.takeError();
5014 if (Expected<std::vector<uint64_t>> SymsOrErr =
5015 toULEB128Array(*ContentsOrErr))
5016 return *SymsOrErr;
5017 else
5018 return createError("unable to decode " + describe(Obj, Sec) + ": " +
5019 toString(SymsOrErr.takeError()));
5022 template <class ELFT> void GNUELFDumper<ELFT>::printAddrsig() {
5023 if (!this->DotAddrsigSec)
5024 return;
5026 Expected<std::vector<uint64_t>> SymsOrErr =
5027 decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
5028 if (!SymsOrErr) {
5029 this->reportUniqueWarning(SymsOrErr.takeError());
5030 return;
5033 StringRef Name = this->getPrintableSectionName(*this->DotAddrsigSec);
5034 OS << "\nAddress-significant symbols section '" << Name << "'"
5035 << " contains " << SymsOrErr->size() << " entries:\n";
5036 OS << " Num: Name\n";
5038 Field Fields[2] = {0, 8};
5039 size_t SymIndex = 0;
5040 for (uint64_t Sym : *SymsOrErr) {
5041 Fields[0].Str = to_string(format_decimal(++SymIndex, 6)) + ":";
5042 Fields[1].Str = this->getStaticSymbolName(Sym);
5043 for (const Field &Entry : Fields)
5044 printField(Entry);
5045 OS << "\n";
5049 template <typename ELFT>
5050 static std::string getGNUProperty(uint32_t Type, uint32_t DataSize,
5051 ArrayRef<uint8_t> Data) {
5052 std::string str;
5053 raw_string_ostream OS(str);
5054 uint32_t PrData;
5055 auto DumpBit = [&](uint32_t Flag, StringRef Name) {
5056 if (PrData & Flag) {
5057 PrData &= ~Flag;
5058 OS << Name;
5059 if (PrData)
5060 OS << ", ";
5064 switch (Type) {
5065 default:
5066 OS << format("<application-specific type 0x%x>", Type);
5067 return OS.str();
5068 case GNU_PROPERTY_STACK_SIZE: {
5069 OS << "stack size: ";
5070 if (DataSize == sizeof(typename ELFT::uint))
5071 OS << formatv("{0:x}",
5072 (uint64_t)(*(const typename ELFT::Addr *)Data.data()));
5073 else
5074 OS << format("<corrupt length: 0x%x>", DataSize);
5075 return OS.str();
5077 case GNU_PROPERTY_NO_COPY_ON_PROTECTED:
5078 OS << "no copy on protected";
5079 if (DataSize)
5080 OS << format(" <corrupt length: 0x%x>", DataSize);
5081 return OS.str();
5082 case GNU_PROPERTY_AARCH64_FEATURE_1_AND:
5083 case GNU_PROPERTY_X86_FEATURE_1_AND:
5084 OS << ((Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) ? "aarch64 feature: "
5085 : "x86 feature: ");
5086 if (DataSize != 4) {
5087 OS << format("<corrupt length: 0x%x>", DataSize);
5088 return OS.str();
5090 PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
5091 if (PrData == 0) {
5092 OS << "<None>";
5093 return OS.str();
5095 if (Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) {
5096 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI, "BTI");
5097 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC, "PAC");
5098 } else {
5099 DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT, "IBT");
5100 DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK, "SHSTK");
5102 if (PrData)
5103 OS << format("<unknown flags: 0x%x>", PrData);
5104 return OS.str();
5105 case GNU_PROPERTY_X86_FEATURE_2_NEEDED:
5106 case GNU_PROPERTY_X86_FEATURE_2_USED:
5107 OS << "x86 feature "
5108 << (Type == GNU_PROPERTY_X86_FEATURE_2_NEEDED ? "needed: " : "used: ");
5109 if (DataSize != 4) {
5110 OS << format("<corrupt length: 0x%x>", DataSize);
5111 return OS.str();
5113 PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
5114 if (PrData == 0) {
5115 OS << "<None>";
5116 return OS.str();
5118 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86, "x86");
5119 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87, "x87");
5120 DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX, "MMX");
5121 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM, "XMM");
5122 DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM, "YMM");
5123 DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM, "ZMM");
5124 DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR, "FXSR");
5125 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE, "XSAVE");
5126 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT, "XSAVEOPT");
5127 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC, "XSAVEC");
5128 if (PrData)
5129 OS << format("<unknown flags: 0x%x>", PrData);
5130 return OS.str();
5131 case GNU_PROPERTY_X86_ISA_1_NEEDED:
5132 case GNU_PROPERTY_X86_ISA_1_USED:
5133 OS << "x86 ISA "
5134 << (Type == GNU_PROPERTY_X86_ISA_1_NEEDED ? "needed: " : "used: ");
5135 if (DataSize != 4) {
5136 OS << format("<corrupt length: 0x%x>", DataSize);
5137 return OS.str();
5139 PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data());
5140 if (PrData == 0) {
5141 OS << "<None>";
5142 return OS.str();
5144 DumpBit(GNU_PROPERTY_X86_ISA_1_BASELINE, "x86-64-baseline");
5145 DumpBit(GNU_PROPERTY_X86_ISA_1_V2, "x86-64-v2");
5146 DumpBit(GNU_PROPERTY_X86_ISA_1_V3, "x86-64-v3");
5147 DumpBit(GNU_PROPERTY_X86_ISA_1_V4, "x86-64-v4");
5148 if (PrData)
5149 OS << format("<unknown flags: 0x%x>", PrData);
5150 return OS.str();
5154 template <typename ELFT>
5155 static SmallVector<std::string, 4> getGNUPropertyList(ArrayRef<uint8_t> Arr) {
5156 using Elf_Word = typename ELFT::Word;
5158 SmallVector<std::string, 4> Properties;
5159 while (Arr.size() >= 8) {
5160 uint32_t Type = *reinterpret_cast<const Elf_Word *>(Arr.data());
5161 uint32_t DataSize = *reinterpret_cast<const Elf_Word *>(Arr.data() + 4);
5162 Arr = Arr.drop_front(8);
5164 // Take padding size into account if present.
5165 uint64_t PaddedSize = alignTo(DataSize, sizeof(typename ELFT::uint));
5166 std::string str;
5167 raw_string_ostream OS(str);
5168 if (Arr.size() < PaddedSize) {
5169 OS << format("<corrupt type (0x%x) datasz: 0x%x>", Type, DataSize);
5170 Properties.push_back(OS.str());
5171 break;
5173 Properties.push_back(
5174 getGNUProperty<ELFT>(Type, DataSize, Arr.take_front(PaddedSize)));
5175 Arr = Arr.drop_front(PaddedSize);
5178 if (!Arr.empty())
5179 Properties.push_back("<corrupted GNU_PROPERTY_TYPE_0>");
5181 return Properties;
5184 struct GNUAbiTag {
5185 std::string OSName;
5186 std::string ABI;
5187 bool IsValid;
5190 template <typename ELFT> static GNUAbiTag getGNUAbiTag(ArrayRef<uint8_t> Desc) {
5191 typedef typename ELFT::Word Elf_Word;
5193 ArrayRef<Elf_Word> Words(reinterpret_cast<const Elf_Word *>(Desc.begin()),
5194 reinterpret_cast<const Elf_Word *>(Desc.end()));
5196 if (Words.size() < 4)
5197 return {"", "", /*IsValid=*/false};
5199 static const char *OSNames[] = {
5200 "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable", "NaCl",
5202 StringRef OSName = "Unknown";
5203 if (Words[0] < std::size(OSNames))
5204 OSName = OSNames[Words[0]];
5205 uint32_t Major = Words[1], Minor = Words[2], Patch = Words[3];
5206 std::string str;
5207 raw_string_ostream ABI(str);
5208 ABI << Major << "." << Minor << "." << Patch;
5209 return {std::string(OSName), ABI.str(), /*IsValid=*/true};
5212 static std::string getGNUBuildId(ArrayRef<uint8_t> Desc) {
5213 std::string str;
5214 raw_string_ostream OS(str);
5215 for (uint8_t B : Desc)
5216 OS << format_hex_no_prefix(B, 2);
5217 return OS.str();
5220 static StringRef getDescAsStringRef(ArrayRef<uint8_t> Desc) {
5221 return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
5224 template <typename ELFT>
5225 static bool printGNUNote(raw_ostream &OS, uint32_t NoteType,
5226 ArrayRef<uint8_t> Desc) {
5227 // Return true if we were able to pretty-print the note, false otherwise.
5228 switch (NoteType) {
5229 default:
5230 return false;
5231 case ELF::NT_GNU_ABI_TAG: {
5232 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
5233 if (!AbiTag.IsValid)
5234 OS << " <corrupt GNU_ABI_TAG>";
5235 else
5236 OS << " OS: " << AbiTag.OSName << ", ABI: " << AbiTag.ABI;
5237 break;
5239 case ELF::NT_GNU_BUILD_ID: {
5240 OS << " Build ID: " << getGNUBuildId(Desc);
5241 break;
5243 case ELF::NT_GNU_GOLD_VERSION:
5244 OS << " Version: " << getDescAsStringRef(Desc);
5245 break;
5246 case ELF::NT_GNU_PROPERTY_TYPE_0:
5247 OS << " Properties:";
5248 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
5249 OS << " " << Property << "\n";
5250 break;
5252 OS << '\n';
5253 return true;
5256 using AndroidNoteProperties = std::vector<std::pair<StringRef, std::string>>;
5257 static AndroidNoteProperties getAndroidNoteProperties(uint32_t NoteType,
5258 ArrayRef<uint8_t> Desc) {
5259 AndroidNoteProperties Props;
5260 switch (NoteType) {
5261 case ELF::NT_ANDROID_TYPE_MEMTAG:
5262 if (Desc.empty()) {
5263 Props.emplace_back("Invalid .note.android.memtag", "");
5264 return Props;
5267 switch (Desc[0] & NT_MEMTAG_LEVEL_MASK) {
5268 case NT_MEMTAG_LEVEL_NONE:
5269 Props.emplace_back("Tagging Mode", "NONE");
5270 break;
5271 case NT_MEMTAG_LEVEL_ASYNC:
5272 Props.emplace_back("Tagging Mode", "ASYNC");
5273 break;
5274 case NT_MEMTAG_LEVEL_SYNC:
5275 Props.emplace_back("Tagging Mode", "SYNC");
5276 break;
5277 default:
5278 Props.emplace_back(
5279 "Tagging Mode",
5280 ("Unknown (" + Twine::utohexstr(Desc[0] & NT_MEMTAG_LEVEL_MASK) + ")")
5281 .str());
5282 break;
5284 Props.emplace_back("Heap",
5285 (Desc[0] & NT_MEMTAG_HEAP) ? "Enabled" : "Disabled");
5286 Props.emplace_back("Stack",
5287 (Desc[0] & NT_MEMTAG_STACK) ? "Enabled" : "Disabled");
5288 break;
5289 default:
5290 return Props;
5292 return Props;
5295 static bool printAndroidNote(raw_ostream &OS, uint32_t NoteType,
5296 ArrayRef<uint8_t> Desc) {
5297 // Return true if we were able to pretty-print the note, false otherwise.
5298 AndroidNoteProperties Props = getAndroidNoteProperties(NoteType, Desc);
5299 if (Props.empty())
5300 return false;
5301 for (const auto &KV : Props)
5302 OS << " " << KV.first << ": " << KV.second << '\n';
5303 return true;
5306 template <class ELFT>
5307 void GNUELFDumper<ELFT>::printMemtag(
5308 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
5309 const ArrayRef<uint8_t> AndroidNoteDesc,
5310 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) {
5311 OS << "Memtag Dynamic Entries:\n";
5312 if (DynamicEntries.empty())
5313 OS << " < none found >\n";
5314 for (const auto &DynamicEntryKV : DynamicEntries)
5315 OS << " " << DynamicEntryKV.first << ": " << DynamicEntryKV.second
5316 << "\n";
5318 if (!AndroidNoteDesc.empty()) {
5319 OS << "Memtag Android Note:\n";
5320 printAndroidNote(OS, ELF::NT_ANDROID_TYPE_MEMTAG, AndroidNoteDesc);
5323 if (Descriptors.empty())
5324 return;
5326 OS << "Memtag Global Descriptors:\n";
5327 for (const auto &[Addr, BytesToTag] : Descriptors) {
5328 OS << " 0x" << utohexstr(Addr, /*LowerCase=*/true) << ": 0x"
5329 << utohexstr(BytesToTag, /*LowerCase=*/true) << "\n";
5333 template <typename ELFT>
5334 static bool printLLVMOMPOFFLOADNote(raw_ostream &OS, uint32_t NoteType,
5335 ArrayRef<uint8_t> Desc) {
5336 switch (NoteType) {
5337 default:
5338 return false;
5339 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
5340 OS << " Version: " << getDescAsStringRef(Desc);
5341 break;
5342 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
5343 OS << " Producer: " << getDescAsStringRef(Desc);
5344 break;
5345 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
5346 OS << " Producer version: " << getDescAsStringRef(Desc);
5347 break;
5349 OS << '\n';
5350 return true;
5353 const EnumEntry<unsigned> FreeBSDFeatureCtlFlags[] = {
5354 {"ASLR_DISABLE", NT_FREEBSD_FCTL_ASLR_DISABLE},
5355 {"PROTMAX_DISABLE", NT_FREEBSD_FCTL_PROTMAX_DISABLE},
5356 {"STKGAP_DISABLE", NT_FREEBSD_FCTL_STKGAP_DISABLE},
5357 {"WXNEEDED", NT_FREEBSD_FCTL_WXNEEDED},
5358 {"LA48", NT_FREEBSD_FCTL_LA48},
5359 {"ASG_DISABLE", NT_FREEBSD_FCTL_ASG_DISABLE},
5362 struct FreeBSDNote {
5363 std::string Type;
5364 std::string Value;
5367 template <typename ELFT>
5368 static std::optional<FreeBSDNote>
5369 getFreeBSDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc, bool IsCore) {
5370 if (IsCore)
5371 return std::nullopt; // No pretty-printing yet.
5372 switch (NoteType) {
5373 case ELF::NT_FREEBSD_ABI_TAG:
5374 if (Desc.size() != 4)
5375 return std::nullopt;
5376 return FreeBSDNote{
5377 "ABI tag",
5378 utostr(support::endian::read32<ELFT::TargetEndianness>(Desc.data()))};
5379 case ELF::NT_FREEBSD_ARCH_TAG:
5380 return FreeBSDNote{"Arch tag", toStringRef(Desc).str()};
5381 case ELF::NT_FREEBSD_FEATURE_CTL: {
5382 if (Desc.size() != 4)
5383 return std::nullopt;
5384 unsigned Value =
5385 support::endian::read32<ELFT::TargetEndianness>(Desc.data());
5386 std::string FlagsStr;
5387 raw_string_ostream OS(FlagsStr);
5388 printFlags(Value, ArrayRef(FreeBSDFeatureCtlFlags), OS);
5389 if (OS.str().empty())
5390 OS << "0x" << utohexstr(Value);
5391 else
5392 OS << "(0x" << utohexstr(Value) << ")";
5393 return FreeBSDNote{"Feature flags", OS.str()};
5395 default:
5396 return std::nullopt;
5400 struct AMDNote {
5401 std::string Type;
5402 std::string Value;
5405 template <typename ELFT>
5406 static AMDNote getAMDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
5407 switch (NoteType) {
5408 default:
5409 return {"", ""};
5410 case ELF::NT_AMD_HSA_CODE_OBJECT_VERSION: {
5411 struct CodeObjectVersion {
5412 uint32_t MajorVersion;
5413 uint32_t MinorVersion;
5415 if (Desc.size() != sizeof(CodeObjectVersion))
5416 return {"AMD HSA Code Object Version",
5417 "Invalid AMD HSA Code Object Version"};
5418 std::string VersionString;
5419 raw_string_ostream StrOS(VersionString);
5420 auto Version = reinterpret_cast<const CodeObjectVersion *>(Desc.data());
5421 StrOS << "[Major: " << Version->MajorVersion
5422 << ", Minor: " << Version->MinorVersion << "]";
5423 return {"AMD HSA Code Object Version", VersionString};
5425 case ELF::NT_AMD_HSA_HSAIL: {
5426 struct HSAILProperties {
5427 uint32_t HSAILMajorVersion;
5428 uint32_t HSAILMinorVersion;
5429 uint8_t Profile;
5430 uint8_t MachineModel;
5431 uint8_t DefaultFloatRound;
5433 if (Desc.size() != sizeof(HSAILProperties))
5434 return {"AMD HSA HSAIL Properties", "Invalid AMD HSA HSAIL Properties"};
5435 auto Properties = reinterpret_cast<const HSAILProperties *>(Desc.data());
5436 std::string HSAILPropetiesString;
5437 raw_string_ostream StrOS(HSAILPropetiesString);
5438 StrOS << "[HSAIL Major: " << Properties->HSAILMajorVersion
5439 << ", HSAIL Minor: " << Properties->HSAILMinorVersion
5440 << ", Profile: " << uint32_t(Properties->Profile)
5441 << ", Machine Model: " << uint32_t(Properties->MachineModel)
5442 << ", Default Float Round: "
5443 << uint32_t(Properties->DefaultFloatRound) << "]";
5444 return {"AMD HSA HSAIL Properties", HSAILPropetiesString};
5446 case ELF::NT_AMD_HSA_ISA_VERSION: {
5447 struct IsaVersion {
5448 uint16_t VendorNameSize;
5449 uint16_t ArchitectureNameSize;
5450 uint32_t Major;
5451 uint32_t Minor;
5452 uint32_t Stepping;
5454 if (Desc.size() < sizeof(IsaVersion))
5455 return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"};
5456 auto Isa = reinterpret_cast<const IsaVersion *>(Desc.data());
5457 if (Desc.size() < sizeof(IsaVersion) +
5458 Isa->VendorNameSize + Isa->ArchitectureNameSize ||
5459 Isa->VendorNameSize == 0 || Isa->ArchitectureNameSize == 0)
5460 return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"};
5461 std::string IsaString;
5462 raw_string_ostream StrOS(IsaString);
5463 StrOS << "[Vendor: "
5464 << StringRef((const char*)Desc.data() + sizeof(IsaVersion), Isa->VendorNameSize - 1)
5465 << ", Architecture: "
5466 << StringRef((const char*)Desc.data() + sizeof(IsaVersion) + Isa->VendorNameSize,
5467 Isa->ArchitectureNameSize - 1)
5468 << ", Major: " << Isa->Major << ", Minor: " << Isa->Minor
5469 << ", Stepping: " << Isa->Stepping << "]";
5470 return {"AMD HSA ISA Version", IsaString};
5472 case ELF::NT_AMD_HSA_METADATA: {
5473 if (Desc.size() == 0)
5474 return {"AMD HSA Metadata", ""};
5475 return {
5476 "AMD HSA Metadata",
5477 std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size() - 1)};
5479 case ELF::NT_AMD_HSA_ISA_NAME: {
5480 if (Desc.size() == 0)
5481 return {"AMD HSA ISA Name", ""};
5482 return {
5483 "AMD HSA ISA Name",
5484 std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
5486 case ELF::NT_AMD_PAL_METADATA: {
5487 struct PALMetadata {
5488 uint32_t Key;
5489 uint32_t Value;
5491 if (Desc.size() % sizeof(PALMetadata) != 0)
5492 return {"AMD PAL Metadata", "Invalid AMD PAL Metadata"};
5493 auto Isa = reinterpret_cast<const PALMetadata *>(Desc.data());
5494 std::string MetadataString;
5495 raw_string_ostream StrOS(MetadataString);
5496 for (size_t I = 0, E = Desc.size() / sizeof(PALMetadata); I < E; ++I) {
5497 StrOS << "[" << Isa[I].Key << ": " << Isa[I].Value << "]";
5499 return {"AMD PAL Metadata", MetadataString};
5504 struct AMDGPUNote {
5505 std::string Type;
5506 std::string Value;
5509 template <typename ELFT>
5510 static AMDGPUNote getAMDGPUNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
5511 switch (NoteType) {
5512 default:
5513 return {"", ""};
5514 case ELF::NT_AMDGPU_METADATA: {
5515 StringRef MsgPackString =
5516 StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
5517 msgpack::Document MsgPackDoc;
5518 if (!MsgPackDoc.readFromBlob(MsgPackString, /*Multi=*/false))
5519 return {"", ""};
5521 std::string MetadataString;
5523 // FIXME: Metadata Verifier only works with AMDHSA.
5524 // This is an ugly workaround to avoid the verifier for other MD
5525 // formats (e.g. amdpal)
5526 if (MsgPackString.find("amdhsa.") != StringRef::npos) {
5527 AMDGPU::HSAMD::V3::MetadataVerifier Verifier(true);
5528 if (!Verifier.verify(MsgPackDoc.getRoot()))
5529 MetadataString = "Invalid AMDGPU Metadata\n";
5532 raw_string_ostream StrOS(MetadataString);
5533 if (MsgPackDoc.getRoot().isScalar()) {
5534 // TODO: passing a scalar root to toYAML() asserts:
5535 // (PolymorphicTraits<T>::getKind(Val) != NodeKind::Scalar &&
5536 // "plain scalar documents are not supported")
5537 // To avoid this crash we print the raw data instead.
5538 return {"", ""};
5540 MsgPackDoc.toYAML(StrOS);
5541 return {"AMDGPU Metadata", StrOS.str()};
5546 struct CoreFileMapping {
5547 uint64_t Start, End, Offset;
5548 StringRef Filename;
5551 struct CoreNote {
5552 uint64_t PageSize;
5553 std::vector<CoreFileMapping> Mappings;
5556 static Expected<CoreNote> readCoreNote(DataExtractor Desc) {
5557 // Expected format of the NT_FILE note description:
5558 // 1. # of file mappings (call it N)
5559 // 2. Page size
5560 // 3. N (start, end, offset) triples
5561 // 4. N packed filenames (null delimited)
5562 // Each field is an Elf_Addr, except for filenames which are char* strings.
5564 CoreNote Ret;
5565 const int Bytes = Desc.getAddressSize();
5567 if (!Desc.isValidOffsetForAddress(2))
5568 return createError("the note of size 0x" + Twine::utohexstr(Desc.size()) +
5569 " is too short, expected at least 0x" +
5570 Twine::utohexstr(Bytes * 2));
5571 if (Desc.getData().back() != 0)
5572 return createError("the note is not NUL terminated");
5574 uint64_t DescOffset = 0;
5575 uint64_t FileCount = Desc.getAddress(&DescOffset);
5576 Ret.PageSize = Desc.getAddress(&DescOffset);
5578 if (!Desc.isValidOffsetForAddress(3 * FileCount * Bytes))
5579 return createError("unable to read file mappings (found " +
5580 Twine(FileCount) + "): the note of size 0x" +
5581 Twine::utohexstr(Desc.size()) + " is too short");
5583 uint64_t FilenamesOffset = 0;
5584 DataExtractor Filenames(
5585 Desc.getData().drop_front(DescOffset + 3 * FileCount * Bytes),
5586 Desc.isLittleEndian(), Desc.getAddressSize());
5588 Ret.Mappings.resize(FileCount);
5589 size_t I = 0;
5590 for (CoreFileMapping &Mapping : Ret.Mappings) {
5591 ++I;
5592 if (!Filenames.isValidOffsetForDataOfSize(FilenamesOffset, 1))
5593 return createError(
5594 "unable to read the file name for the mapping with index " +
5595 Twine(I) + ": the note of size 0x" + Twine::utohexstr(Desc.size()) +
5596 " is truncated");
5597 Mapping.Start = Desc.getAddress(&DescOffset);
5598 Mapping.End = Desc.getAddress(&DescOffset);
5599 Mapping.Offset = Desc.getAddress(&DescOffset);
5600 Mapping.Filename = Filenames.getCStrRef(&FilenamesOffset);
5603 return Ret;
5606 template <typename ELFT>
5607 static void printCoreNote(raw_ostream &OS, const CoreNote &Note) {
5608 // Length of "0x<address>" string.
5609 const int FieldWidth = ELFT::Is64Bits ? 18 : 10;
5611 OS << " Page size: " << format_decimal(Note.PageSize, 0) << '\n';
5612 OS << " " << right_justify("Start", FieldWidth) << " "
5613 << right_justify("End", FieldWidth) << " "
5614 << right_justify("Page Offset", FieldWidth) << '\n';
5615 for (const CoreFileMapping &Mapping : Note.Mappings) {
5616 OS << " " << format_hex(Mapping.Start, FieldWidth) << " "
5617 << format_hex(Mapping.End, FieldWidth) << " "
5618 << format_hex(Mapping.Offset, FieldWidth) << "\n "
5619 << Mapping.Filename << '\n';
5623 const NoteType GenericNoteTypes[] = {
5624 {ELF::NT_VERSION, "NT_VERSION (version)"},
5625 {ELF::NT_ARCH, "NT_ARCH (architecture)"},
5626 {ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN, "OPEN"},
5627 {ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC, "func"},
5630 const NoteType GNUNoteTypes[] = {
5631 {ELF::NT_GNU_ABI_TAG, "NT_GNU_ABI_TAG (ABI version tag)"},
5632 {ELF::NT_GNU_HWCAP, "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"},
5633 {ELF::NT_GNU_BUILD_ID, "NT_GNU_BUILD_ID (unique build ID bitstring)"},
5634 {ELF::NT_GNU_GOLD_VERSION, "NT_GNU_GOLD_VERSION (gold version)"},
5635 {ELF::NT_GNU_PROPERTY_TYPE_0, "NT_GNU_PROPERTY_TYPE_0 (property note)"},
5638 const NoteType FreeBSDCoreNoteTypes[] = {
5639 {ELF::NT_FREEBSD_THRMISC, "NT_THRMISC (thrmisc structure)"},
5640 {ELF::NT_FREEBSD_PROCSTAT_PROC, "NT_PROCSTAT_PROC (proc data)"},
5641 {ELF::NT_FREEBSD_PROCSTAT_FILES, "NT_PROCSTAT_FILES (files data)"},
5642 {ELF::NT_FREEBSD_PROCSTAT_VMMAP, "NT_PROCSTAT_VMMAP (vmmap data)"},
5643 {ELF::NT_FREEBSD_PROCSTAT_GROUPS, "NT_PROCSTAT_GROUPS (groups data)"},
5644 {ELF::NT_FREEBSD_PROCSTAT_UMASK, "NT_PROCSTAT_UMASK (umask data)"},
5645 {ELF::NT_FREEBSD_PROCSTAT_RLIMIT, "NT_PROCSTAT_RLIMIT (rlimit data)"},
5646 {ELF::NT_FREEBSD_PROCSTAT_OSREL, "NT_PROCSTAT_OSREL (osreldate data)"},
5647 {ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS,
5648 "NT_PROCSTAT_PSSTRINGS (ps_strings data)"},
5649 {ELF::NT_FREEBSD_PROCSTAT_AUXV, "NT_PROCSTAT_AUXV (auxv data)"},
5652 const NoteType FreeBSDNoteTypes[] = {
5653 {ELF::NT_FREEBSD_ABI_TAG, "NT_FREEBSD_ABI_TAG (ABI version tag)"},
5654 {ELF::NT_FREEBSD_NOINIT_TAG, "NT_FREEBSD_NOINIT_TAG (no .init tag)"},
5655 {ELF::NT_FREEBSD_ARCH_TAG, "NT_FREEBSD_ARCH_TAG (architecture tag)"},
5656 {ELF::NT_FREEBSD_FEATURE_CTL,
5657 "NT_FREEBSD_FEATURE_CTL (FreeBSD feature control)"},
5660 const NoteType NetBSDCoreNoteTypes[] = {
5661 {ELF::NT_NETBSDCORE_PROCINFO,
5662 "NT_NETBSDCORE_PROCINFO (procinfo structure)"},
5663 {ELF::NT_NETBSDCORE_AUXV, "NT_NETBSDCORE_AUXV (ELF auxiliary vector data)"},
5664 {ELF::NT_NETBSDCORE_LWPSTATUS, "PT_LWPSTATUS (ptrace_lwpstatus structure)"},
5667 const NoteType OpenBSDCoreNoteTypes[] = {
5668 {ELF::NT_OPENBSD_PROCINFO, "NT_OPENBSD_PROCINFO (procinfo structure)"},
5669 {ELF::NT_OPENBSD_AUXV, "NT_OPENBSD_AUXV (ELF auxiliary vector data)"},
5670 {ELF::NT_OPENBSD_REGS, "NT_OPENBSD_REGS (regular registers)"},
5671 {ELF::NT_OPENBSD_FPREGS, "NT_OPENBSD_FPREGS (floating point registers)"},
5672 {ELF::NT_OPENBSD_WCOOKIE, "NT_OPENBSD_WCOOKIE (window cookie)"},
5675 const NoteType AMDNoteTypes[] = {
5676 {ELF::NT_AMD_HSA_CODE_OBJECT_VERSION,
5677 "NT_AMD_HSA_CODE_OBJECT_VERSION (AMD HSA Code Object Version)"},
5678 {ELF::NT_AMD_HSA_HSAIL, "NT_AMD_HSA_HSAIL (AMD HSA HSAIL Properties)"},
5679 {ELF::NT_AMD_HSA_ISA_VERSION, "NT_AMD_HSA_ISA_VERSION (AMD HSA ISA Version)"},
5680 {ELF::NT_AMD_HSA_METADATA, "NT_AMD_HSA_METADATA (AMD HSA Metadata)"},
5681 {ELF::NT_AMD_HSA_ISA_NAME, "NT_AMD_HSA_ISA_NAME (AMD HSA ISA Name)"},
5682 {ELF::NT_AMD_PAL_METADATA, "NT_AMD_PAL_METADATA (AMD PAL Metadata)"},
5685 const NoteType AMDGPUNoteTypes[] = {
5686 {ELF::NT_AMDGPU_METADATA, "NT_AMDGPU_METADATA (AMDGPU Metadata)"},
5689 const NoteType LLVMOMPOFFLOADNoteTypes[] = {
5690 {ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION,
5691 "NT_LLVM_OPENMP_OFFLOAD_VERSION (image format version)"},
5692 {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER,
5693 "NT_LLVM_OPENMP_OFFLOAD_PRODUCER (producing toolchain)"},
5694 {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION,
5695 "NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION (producing toolchain version)"},
5698 const NoteType AndroidNoteTypes[] = {
5699 {ELF::NT_ANDROID_TYPE_IDENT, "NT_ANDROID_TYPE_IDENT"},
5700 {ELF::NT_ANDROID_TYPE_KUSER, "NT_ANDROID_TYPE_KUSER"},
5701 {ELF::NT_ANDROID_TYPE_MEMTAG,
5702 "NT_ANDROID_TYPE_MEMTAG (Android memory tagging information)"},
5705 const NoteType CoreNoteTypes[] = {
5706 {ELF::NT_PRSTATUS, "NT_PRSTATUS (prstatus structure)"},
5707 {ELF::NT_FPREGSET, "NT_FPREGSET (floating point registers)"},
5708 {ELF::NT_PRPSINFO, "NT_PRPSINFO (prpsinfo structure)"},
5709 {ELF::NT_TASKSTRUCT, "NT_TASKSTRUCT (task structure)"},
5710 {ELF::NT_AUXV, "NT_AUXV (auxiliary vector)"},
5711 {ELF::NT_PSTATUS, "NT_PSTATUS (pstatus structure)"},
5712 {ELF::NT_FPREGS, "NT_FPREGS (floating point registers)"},
5713 {ELF::NT_PSINFO, "NT_PSINFO (psinfo structure)"},
5714 {ELF::NT_LWPSTATUS, "NT_LWPSTATUS (lwpstatus_t structure)"},
5715 {ELF::NT_LWPSINFO, "NT_LWPSINFO (lwpsinfo_t structure)"},
5716 {ELF::NT_WIN32PSTATUS, "NT_WIN32PSTATUS (win32_pstatus structure)"},
5718 {ELF::NT_PPC_VMX, "NT_PPC_VMX (ppc Altivec registers)"},
5719 {ELF::NT_PPC_VSX, "NT_PPC_VSX (ppc VSX registers)"},
5720 {ELF::NT_PPC_TAR, "NT_PPC_TAR (ppc TAR register)"},
5721 {ELF::NT_PPC_PPR, "NT_PPC_PPR (ppc PPR register)"},
5722 {ELF::NT_PPC_DSCR, "NT_PPC_DSCR (ppc DSCR register)"},
5723 {ELF::NT_PPC_EBB, "NT_PPC_EBB (ppc EBB registers)"},
5724 {ELF::NT_PPC_PMU, "NT_PPC_PMU (ppc PMU registers)"},
5725 {ELF::NT_PPC_TM_CGPR, "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"},
5726 {ELF::NT_PPC_TM_CFPR,
5727 "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"},
5728 {ELF::NT_PPC_TM_CVMX,
5729 "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"},
5730 {ELF::NT_PPC_TM_CVSX, "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"},
5731 {ELF::NT_PPC_TM_SPR, "NT_PPC_TM_SPR (ppc TM special purpose registers)"},
5732 {ELF::NT_PPC_TM_CTAR, "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"},
5733 {ELF::NT_PPC_TM_CPPR, "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"},
5734 {ELF::NT_PPC_TM_CDSCR, "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"},
5736 {ELF::NT_386_TLS, "NT_386_TLS (x86 TLS information)"},
5737 {ELF::NT_386_IOPERM, "NT_386_IOPERM (x86 I/O permissions)"},
5738 {ELF::NT_X86_XSTATE, "NT_X86_XSTATE (x86 XSAVE extended state)"},
5740 {ELF::NT_S390_HIGH_GPRS, "NT_S390_HIGH_GPRS (s390 upper register halves)"},
5741 {ELF::NT_S390_TIMER, "NT_S390_TIMER (s390 timer register)"},
5742 {ELF::NT_S390_TODCMP, "NT_S390_TODCMP (s390 TOD comparator register)"},
5743 {ELF::NT_S390_TODPREG, "NT_S390_TODPREG (s390 TOD programmable register)"},
5744 {ELF::NT_S390_CTRS, "NT_S390_CTRS (s390 control registers)"},
5745 {ELF::NT_S390_PREFIX, "NT_S390_PREFIX (s390 prefix register)"},
5746 {ELF::NT_S390_LAST_BREAK,
5747 "NT_S390_LAST_BREAK (s390 last breaking event address)"},
5748 {ELF::NT_S390_SYSTEM_CALL,
5749 "NT_S390_SYSTEM_CALL (s390 system call restart data)"},
5750 {ELF::NT_S390_TDB, "NT_S390_TDB (s390 transaction diagnostic block)"},
5751 {ELF::NT_S390_VXRS_LOW,
5752 "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"},
5753 {ELF::NT_S390_VXRS_HIGH, "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"},
5754 {ELF::NT_S390_GS_CB, "NT_S390_GS_CB (s390 guarded-storage registers)"},
5755 {ELF::NT_S390_GS_BC,
5756 "NT_S390_GS_BC (s390 guarded-storage broadcast control)"},
5758 {ELF::NT_ARM_VFP, "NT_ARM_VFP (arm VFP registers)"},
5759 {ELF::NT_ARM_TLS, "NT_ARM_TLS (AArch TLS registers)"},
5760 {ELF::NT_ARM_HW_BREAK,
5761 "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"},
5762 {ELF::NT_ARM_HW_WATCH,
5763 "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"},
5764 {ELF::NT_ARM_SVE, "NT_ARM_SVE (AArch64 SVE registers)"},
5765 {ELF::NT_ARM_PAC_MASK,
5766 "NT_ARM_PAC_MASK (AArch64 Pointer Authentication code masks)"},
5767 {ELF::NT_ARM_SSVE, "NT_ARM_SSVE (AArch64 Streaming SVE registers)"},
5768 {ELF::NT_ARM_ZA, "NT_ARM_ZA (AArch64 SME ZA registers)"},
5769 {ELF::NT_ARM_ZT, "NT_ARM_ZT (AArch64 SME ZT registers)"},
5771 {ELF::NT_FILE, "NT_FILE (mapped files)"},
5772 {ELF::NT_PRXFPREG, "NT_PRXFPREG (user_xfpregs structure)"},
5773 {ELF::NT_SIGINFO, "NT_SIGINFO (siginfo_t data)"},
5776 template <class ELFT>
5777 StringRef getNoteTypeName(const typename ELFT::Note &Note, unsigned ELFType) {
5778 uint32_t Type = Note.getType();
5779 auto FindNote = [&](ArrayRef<NoteType> V) -> StringRef {
5780 for (const NoteType &N : V)
5781 if (N.ID == Type)
5782 return N.Name;
5783 return "";
5786 StringRef Name = Note.getName();
5787 if (Name == "GNU")
5788 return FindNote(GNUNoteTypes);
5789 if (Name == "FreeBSD") {
5790 if (ELFType == ELF::ET_CORE) {
5791 // FreeBSD also places the generic core notes in the FreeBSD namespace.
5792 StringRef Result = FindNote(FreeBSDCoreNoteTypes);
5793 if (!Result.empty())
5794 return Result;
5795 return FindNote(CoreNoteTypes);
5796 } else {
5797 return FindNote(FreeBSDNoteTypes);
5800 if (ELFType == ELF::ET_CORE && Name.startswith("NetBSD-CORE")) {
5801 StringRef Result = FindNote(NetBSDCoreNoteTypes);
5802 if (!Result.empty())
5803 return Result;
5804 return FindNote(CoreNoteTypes);
5806 if (ELFType == ELF::ET_CORE && Name.startswith("OpenBSD")) {
5807 // OpenBSD also places the generic core notes in the OpenBSD namespace.
5808 StringRef Result = FindNote(OpenBSDCoreNoteTypes);
5809 if (!Result.empty())
5810 return Result;
5811 return FindNote(CoreNoteTypes);
5813 if (Name == "AMD")
5814 return FindNote(AMDNoteTypes);
5815 if (Name == "AMDGPU")
5816 return FindNote(AMDGPUNoteTypes);
5817 if (Name == "LLVMOMPOFFLOAD")
5818 return FindNote(LLVMOMPOFFLOADNoteTypes);
5819 if (Name == "Android")
5820 return FindNote(AndroidNoteTypes);
5822 if (ELFType == ELF::ET_CORE)
5823 return FindNote(CoreNoteTypes);
5824 return FindNote(GenericNoteTypes);
5827 template <class ELFT>
5828 static void processNotesHelper(
5829 const ELFDumper<ELFT> &Dumper,
5830 llvm::function_ref<void(std::optional<StringRef>, typename ELFT::Off,
5831 typename ELFT::Addr, size_t)>
5832 StartNotesFn,
5833 llvm::function_ref<Error(const typename ELFT::Note &, bool)> ProcessNoteFn,
5834 llvm::function_ref<void()> FinishNotesFn) {
5835 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
5836 bool IsCoreFile = Obj.getHeader().e_type == ELF::ET_CORE;
5838 ArrayRef<typename ELFT::Shdr> Sections = cantFail(Obj.sections());
5839 if (!IsCoreFile && !Sections.empty()) {
5840 for (const typename ELFT::Shdr &S : Sections) {
5841 if (S.sh_type != SHT_NOTE)
5842 continue;
5843 StartNotesFn(expectedToStdOptional(Obj.getSectionName(S)), S.sh_offset,
5844 S.sh_size, S.sh_addralign);
5845 Error Err = Error::success();
5846 size_t I = 0;
5847 for (const typename ELFT::Note Note : Obj.notes(S, Err)) {
5848 if (Error E = ProcessNoteFn(Note, IsCoreFile))
5849 Dumper.reportUniqueWarning(
5850 "unable to read note with index " + Twine(I) + " from the " +
5851 describe(Obj, S) + ": " + toString(std::move(E)));
5852 ++I;
5854 if (Err)
5855 Dumper.reportUniqueWarning("unable to read notes from the " +
5856 describe(Obj, S) + ": " +
5857 toString(std::move(Err)));
5858 FinishNotesFn();
5860 return;
5863 Expected<ArrayRef<typename ELFT::Phdr>> PhdrsOrErr = Obj.program_headers();
5864 if (!PhdrsOrErr) {
5865 Dumper.reportUniqueWarning(
5866 "unable to read program headers to locate the PT_NOTE segment: " +
5867 toString(PhdrsOrErr.takeError()));
5868 return;
5871 for (size_t I = 0, E = (*PhdrsOrErr).size(); I != E; ++I) {
5872 const typename ELFT::Phdr &P = (*PhdrsOrErr)[I];
5873 if (P.p_type != PT_NOTE)
5874 continue;
5875 StartNotesFn(/*SecName=*/std::nullopt, P.p_offset, P.p_filesz, P.p_align);
5876 Error Err = Error::success();
5877 size_t Index = 0;
5878 for (const typename ELFT::Note Note : Obj.notes(P, Err)) {
5879 if (Error E = ProcessNoteFn(Note, IsCoreFile))
5880 Dumper.reportUniqueWarning("unable to read note with index " +
5881 Twine(Index) +
5882 " from the PT_NOTE segment with index " +
5883 Twine(I) + ": " + toString(std::move(E)));
5884 ++Index;
5886 if (Err)
5887 Dumper.reportUniqueWarning(
5888 "unable to read notes from the PT_NOTE segment with index " +
5889 Twine(I) + ": " + toString(std::move(Err)));
5890 FinishNotesFn();
5894 template <class ELFT> void GNUELFDumper<ELFT>::printNotes() {
5895 size_t Align = 0;
5896 bool IsFirstHeader = true;
5897 auto PrintHeader = [&](std::optional<StringRef> SecName,
5898 const typename ELFT::Off Offset,
5899 const typename ELFT::Addr Size, size_t Al) {
5900 Align = std::max<size_t>(Al, 4);
5901 // Print a newline between notes sections to match GNU readelf.
5902 if (!IsFirstHeader) {
5903 OS << '\n';
5904 } else {
5905 IsFirstHeader = false;
5908 OS << "Displaying notes found ";
5910 if (SecName)
5911 OS << "in: " << *SecName << "\n";
5912 else
5913 OS << "at file offset " << format_hex(Offset, 10) << " with length "
5914 << format_hex(Size, 10) << ":\n";
5916 OS << " Owner Data size \tDescription\n";
5919 auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
5920 StringRef Name = Note.getName();
5921 ArrayRef<uint8_t> Descriptor = Note.getDesc(Align);
5922 Elf_Word Type = Note.getType();
5924 // Print the note owner/type.
5925 OS << " " << left_justify(Name, 20) << ' '
5926 << format_hex(Descriptor.size(), 10) << '\t';
5928 StringRef NoteType =
5929 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
5930 if (!NoteType.empty())
5931 OS << NoteType << '\n';
5932 else
5933 OS << "Unknown note type: (" << format_hex(Type, 10) << ")\n";
5935 // Print the description, or fallback to printing raw bytes for unknown
5936 // owners/if we fail to pretty-print the contents.
5937 if (Name == "GNU") {
5938 if (printGNUNote<ELFT>(OS, Type, Descriptor))
5939 return Error::success();
5940 } else if (Name == "FreeBSD") {
5941 if (std::optional<FreeBSDNote> N =
5942 getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
5943 OS << " " << N->Type << ": " << N->Value << '\n';
5944 return Error::success();
5946 } else if (Name == "AMD") {
5947 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
5948 if (!N.Type.empty()) {
5949 OS << " " << N.Type << ":\n " << N.Value << '\n';
5950 return Error::success();
5952 } else if (Name == "AMDGPU") {
5953 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
5954 if (!N.Type.empty()) {
5955 OS << " " << N.Type << ":\n " << N.Value << '\n';
5956 return Error::success();
5958 } else if (Name == "LLVMOMPOFFLOAD") {
5959 if (printLLVMOMPOFFLOADNote<ELFT>(OS, Type, Descriptor))
5960 return Error::success();
5961 } else if (Name == "CORE") {
5962 if (Type == ELF::NT_FILE) {
5963 DataExtractor DescExtractor(Descriptor,
5964 ELFT::TargetEndianness == support::little,
5965 sizeof(Elf_Addr));
5966 if (Expected<CoreNote> NoteOrErr = readCoreNote(DescExtractor)) {
5967 printCoreNote<ELFT>(OS, *NoteOrErr);
5968 return Error::success();
5969 } else {
5970 return NoteOrErr.takeError();
5973 } else if (Name == "Android") {
5974 if (printAndroidNote(OS, Type, Descriptor))
5975 return Error::success();
5977 if (!Descriptor.empty()) {
5978 OS << " description data:";
5979 for (uint8_t B : Descriptor)
5980 OS << " " << format("%02x", B);
5981 OS << '\n';
5983 return Error::success();
5986 processNotesHelper(*this, /*StartNotesFn=*/PrintHeader,
5987 /*ProcessNoteFn=*/ProcessNote, /*FinishNotesFn=*/[]() {});
5990 template <class ELFT>
5991 ArrayRef<uint8_t>
5992 ELFDumper<ELFT>::getMemtagGlobalsSectionContents(uint64_t ExpectedAddr) {
5993 for (const typename ELFT::Shdr &Sec : cantFail(Obj.sections())) {
5994 if (Sec.sh_type != SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC)
5995 continue;
5996 if (Sec.sh_addr != ExpectedAddr) {
5997 reportUniqueWarning(
5998 "SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section was unexpectedly at 0x" +
5999 Twine::utohexstr(Sec.sh_addr) +
6000 ", when DT_AARCH64_MEMTAG_GLOBALS says it should be at 0x" +
6001 Twine::utohexstr(ExpectedAddr));
6002 return ArrayRef<uint8_t>();
6004 Expected<ArrayRef<uint8_t>> Contents = Obj.getSectionContents(Sec);
6005 if (auto E = Contents.takeError()) {
6006 reportUniqueWarning(
6007 "couldn't get SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section contents: " +
6008 toString(std::move(E)));
6009 return ArrayRef<uint8_t>();
6011 return Contents.get();
6013 return ArrayRef<uint8_t>();
6016 // Reserve the lower three bits of the first byte of the step distance when
6017 // encoding the memtag descriptors. Found to be the best overall size tradeoff
6018 // when compiling Android T with full MTE globals enabled.
6019 constexpr uint64_t MemtagStepVarintReservedBits = 3;
6020 constexpr uint64_t MemtagGranuleSize = 16;
6022 template <typename ELFT> void ELFDumper<ELFT>::printMemtag() {
6023 if (Obj.getHeader().e_machine != EM_AARCH64) return;
6024 std::vector<std::pair<std::string, std::string>> DynamicEntries;
6025 uint64_t MemtagGlobalsSz = 0;
6026 uint64_t MemtagGlobals = 0;
6027 for (const typename ELFT::Dyn &Entry : dynamic_table()) {
6028 uintX_t Tag = Entry.getTag();
6029 switch (Tag) {
6030 case DT_AARCH64_MEMTAG_GLOBALSSZ:
6031 MemtagGlobalsSz = Entry.getVal();
6032 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6033 getDynamicEntry(Tag, Entry.getVal()));
6034 break;
6035 case DT_AARCH64_MEMTAG_GLOBALS:
6036 MemtagGlobals = Entry.getVal();
6037 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6038 getDynamicEntry(Tag, Entry.getVal()));
6039 break;
6040 case DT_AARCH64_MEMTAG_MODE:
6041 case DT_AARCH64_MEMTAG_HEAP:
6042 case DT_AARCH64_MEMTAG_STACK:
6043 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6044 getDynamicEntry(Tag, Entry.getVal()));
6045 break;
6049 ArrayRef<uint8_t> AndroidNoteDesc;
6050 auto FindAndroidNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
6051 if (Note.getName() == "Android" &&
6052 Note.getType() == ELF::NT_ANDROID_TYPE_MEMTAG)
6053 AndroidNoteDesc = Note.getDesc(4);
6054 return Error::success();
6057 processNotesHelper(
6058 *this,
6059 /*StartNotesFn=*/
6060 [](std::optional<StringRef>, const typename ELFT::Off,
6061 const typename ELFT::Addr, size_t) {},
6062 /*ProcessNoteFn=*/FindAndroidNote, /*FinishNotesFn=*/[]() {});
6064 ArrayRef<uint8_t> Contents = getMemtagGlobalsSectionContents(MemtagGlobals);
6065 if (Contents.size() != MemtagGlobalsSz) {
6066 reportUniqueWarning(
6067 "mismatch between DT_AARCH64_MEMTAG_GLOBALSSZ (0x" +
6068 Twine::utohexstr(MemtagGlobalsSz) +
6069 ") and SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section size (0x" +
6070 Twine::utohexstr(Contents.size()) + ")");
6071 Contents = ArrayRef<uint8_t>();
6074 std::vector<std::pair<uint64_t, uint64_t>> GlobalDescriptors;
6075 uint64_t Address = 0;
6076 // See the AArch64 MemtagABI document for a description of encoding scheme:
6077 // https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#83encoding-of-sht_aarch64_memtag_globals_dynamic
6078 for (size_t I = 0; I < Contents.size();) {
6079 const char *Error = nullptr;
6080 unsigned DecodedBytes = 0;
6081 uint64_t Value = decodeULEB128(Contents.data() + I, &DecodedBytes,
6082 Contents.end(), &Error);
6083 I += DecodedBytes;
6084 if (Error) {
6085 reportUniqueWarning(
6086 "error decoding distance uleb, " + Twine(DecodedBytes) +
6087 " byte(s) into SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC: " + Twine(Error));
6088 GlobalDescriptors.clear();
6089 break;
6091 uint64_t Distance = Value >> MemtagStepVarintReservedBits;
6092 uint64_t GranulesToTag = Value & ((1 << MemtagStepVarintReservedBits) - 1);
6093 if (GranulesToTag == 0) {
6094 GranulesToTag = decodeULEB128(Contents.data() + I, &DecodedBytes,
6095 Contents.end(), &Error) +
6097 I += DecodedBytes;
6098 if (Error) {
6099 reportUniqueWarning(
6100 "error decoding size-only uleb, " + Twine(DecodedBytes) +
6101 " byte(s) into SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC: " + Twine(Error));
6102 GlobalDescriptors.clear();
6103 break;
6106 Address += Distance * MemtagGranuleSize;
6107 GlobalDescriptors.emplace_back(Address, GranulesToTag * MemtagGranuleSize);
6108 Address += GranulesToTag * MemtagGranuleSize;
6111 printMemtag(DynamicEntries, AndroidNoteDesc, GlobalDescriptors);
6114 template <class ELFT> void GNUELFDumper<ELFT>::printELFLinkerOptions() {
6115 OS << "printELFLinkerOptions not implemented!\n";
6118 template <class ELFT>
6119 void ELFDumper<ELFT>::printDependentLibsHelper(
6120 function_ref<void(const Elf_Shdr &)> OnSectionStart,
6121 function_ref<void(StringRef, uint64_t)> OnLibEntry) {
6122 auto Warn = [this](unsigned SecNdx, StringRef Msg) {
6123 this->reportUniqueWarning("SHT_LLVM_DEPENDENT_LIBRARIES section at index " +
6124 Twine(SecNdx) + " is broken: " + Msg);
6127 unsigned I = -1;
6128 for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
6129 ++I;
6130 if (Shdr.sh_type != ELF::SHT_LLVM_DEPENDENT_LIBRARIES)
6131 continue;
6133 OnSectionStart(Shdr);
6135 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Shdr);
6136 if (!ContentsOrErr) {
6137 Warn(I, toString(ContentsOrErr.takeError()));
6138 continue;
6141 ArrayRef<uint8_t> Contents = *ContentsOrErr;
6142 if (!Contents.empty() && Contents.back() != 0) {
6143 Warn(I, "the content is not null-terminated");
6144 continue;
6147 for (const uint8_t *I = Contents.begin(), *E = Contents.end(); I < E;) {
6148 StringRef Lib((const char *)I);
6149 OnLibEntry(Lib, I - Contents.begin());
6150 I += Lib.size() + 1;
6155 template <class ELFT>
6156 void ELFDumper<ELFT>::forEachRelocationDo(
6157 const Elf_Shdr &Sec, bool RawRelr,
6158 llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
6159 const Elf_Shdr &, const Elf_Shdr *)>
6160 RelRelaFn,
6161 llvm::function_ref<void(const Elf_Relr &)> RelrFn) {
6162 auto Warn = [&](Error &&E,
6163 const Twine &Prefix = "unable to read relocations from") {
6164 this->reportUniqueWarning(Prefix + " " + describe(Sec) + ": " +
6165 toString(std::move(E)));
6168 // SHT_RELR/SHT_ANDROID_RELR sections do not have an associated symbol table.
6169 // For them we should not treat the value of the sh_link field as an index of
6170 // a symbol table.
6171 const Elf_Shdr *SymTab;
6172 if (Sec.sh_type != ELF::SHT_RELR && Sec.sh_type != ELF::SHT_ANDROID_RELR) {
6173 Expected<const Elf_Shdr *> SymTabOrErr = Obj.getSection(Sec.sh_link);
6174 if (!SymTabOrErr) {
6175 Warn(SymTabOrErr.takeError(), "unable to locate a symbol table for");
6176 return;
6178 SymTab = *SymTabOrErr;
6181 unsigned RelNdx = 0;
6182 const bool IsMips64EL = this->Obj.isMips64EL();
6183 switch (Sec.sh_type) {
6184 case ELF::SHT_REL:
6185 if (Expected<Elf_Rel_Range> RangeOrErr = Obj.rels(Sec)) {
6186 for (const Elf_Rel &R : *RangeOrErr)
6187 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
6188 } else {
6189 Warn(RangeOrErr.takeError());
6191 break;
6192 case ELF::SHT_RELA:
6193 if (Expected<Elf_Rela_Range> RangeOrErr = Obj.relas(Sec)) {
6194 for (const Elf_Rela &R : *RangeOrErr)
6195 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
6196 } else {
6197 Warn(RangeOrErr.takeError());
6199 break;
6200 case ELF::SHT_RELR:
6201 case ELF::SHT_ANDROID_RELR: {
6202 Expected<Elf_Relr_Range> RangeOrErr = Obj.relrs(Sec);
6203 if (!RangeOrErr) {
6204 Warn(RangeOrErr.takeError());
6205 break;
6207 if (RawRelr) {
6208 for (const Elf_Relr &R : *RangeOrErr)
6209 RelrFn(R);
6210 break;
6213 for (const Elf_Rel &R : Obj.decode_relrs(*RangeOrErr))
6214 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec,
6215 /*SymTab=*/nullptr);
6216 break;
6218 case ELF::SHT_ANDROID_REL:
6219 case ELF::SHT_ANDROID_RELA:
6220 if (Expected<std::vector<Elf_Rela>> RelasOrErr = Obj.android_relas(Sec)) {
6221 for (const Elf_Rela &R : *RelasOrErr)
6222 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
6223 } else {
6224 Warn(RelasOrErr.takeError());
6226 break;
6230 template <class ELFT>
6231 StringRef ELFDumper<ELFT>::getPrintableSectionName(const Elf_Shdr &Sec) const {
6232 StringRef Name = "<?>";
6233 if (Expected<StringRef> SecNameOrErr =
6234 Obj.getSectionName(Sec, this->WarningHandler))
6235 Name = *SecNameOrErr;
6236 else
6237 this->reportUniqueWarning("unable to get the name of " + describe(Sec) +
6238 ": " + toString(SecNameOrErr.takeError()));
6239 return Name;
6242 template <class ELFT> void GNUELFDumper<ELFT>::printDependentLibs() {
6243 bool SectionStarted = false;
6244 struct NameOffset {
6245 StringRef Name;
6246 uint64_t Offset;
6248 std::vector<NameOffset> SecEntries;
6249 NameOffset Current;
6250 auto PrintSection = [&]() {
6251 OS << "Dependent libraries section " << Current.Name << " at offset "
6252 << format_hex(Current.Offset, 1) << " contains " << SecEntries.size()
6253 << " entries:\n";
6254 for (NameOffset Entry : SecEntries)
6255 OS << " [" << format("%6" PRIx64, Entry.Offset) << "] " << Entry.Name
6256 << "\n";
6257 OS << "\n";
6258 SecEntries.clear();
6261 auto OnSectionStart = [&](const Elf_Shdr &Shdr) {
6262 if (SectionStarted)
6263 PrintSection();
6264 SectionStarted = true;
6265 Current.Offset = Shdr.sh_offset;
6266 Current.Name = this->getPrintableSectionName(Shdr);
6268 auto OnLibEntry = [&](StringRef Lib, uint64_t Offset) {
6269 SecEntries.push_back(NameOffset{Lib, Offset});
6272 this->printDependentLibsHelper(OnSectionStart, OnLibEntry);
6273 if (SectionStarted)
6274 PrintSection();
6277 template <class ELFT>
6278 SmallVector<uint32_t> ELFDumper<ELFT>::getSymbolIndexesForFunctionAddress(
6279 uint64_t SymValue, std::optional<const Elf_Shdr *> FunctionSec) {
6280 SmallVector<uint32_t> SymbolIndexes;
6281 if (!this->AddressToIndexMap) {
6282 // Populate the address to index map upon the first invocation of this
6283 // function.
6284 this->AddressToIndexMap.emplace();
6285 if (this->DotSymtabSec) {
6286 if (Expected<Elf_Sym_Range> SymsOrError =
6287 Obj.symbols(this->DotSymtabSec)) {
6288 uint32_t Index = (uint32_t)-1;
6289 for (const Elf_Sym &Sym : *SymsOrError) {
6290 ++Index;
6292 if (Sym.st_shndx == ELF::SHN_UNDEF || Sym.getType() != ELF::STT_FUNC)
6293 continue;
6295 Expected<uint64_t> SymAddrOrErr =
6296 ObjF.toSymbolRef(this->DotSymtabSec, Index).getAddress();
6297 if (!SymAddrOrErr) {
6298 std::string Name = this->getStaticSymbolName(Index);
6299 reportUniqueWarning("unable to get address of symbol '" + Name +
6300 "': " + toString(SymAddrOrErr.takeError()));
6301 return SymbolIndexes;
6304 (*this->AddressToIndexMap)[*SymAddrOrErr].push_back(Index);
6306 } else {
6307 reportUniqueWarning("unable to read the symbol table: " +
6308 toString(SymsOrError.takeError()));
6313 auto Symbols = this->AddressToIndexMap->find(SymValue);
6314 if (Symbols == this->AddressToIndexMap->end())
6315 return SymbolIndexes;
6317 for (uint32_t Index : Symbols->second) {
6318 // Check if the symbol is in the right section. FunctionSec == None
6319 // means "any section".
6320 if (FunctionSec) {
6321 const Elf_Sym &Sym = *cantFail(Obj.getSymbol(this->DotSymtabSec, Index));
6322 if (Expected<const Elf_Shdr *> SecOrErr =
6323 Obj.getSection(Sym, this->DotSymtabSec,
6324 this->getShndxTable(this->DotSymtabSec))) {
6325 if (*FunctionSec != *SecOrErr)
6326 continue;
6327 } else {
6328 std::string Name = this->getStaticSymbolName(Index);
6329 // Note: it is impossible to trigger this error currently, it is
6330 // untested.
6331 reportUniqueWarning("unable to get section of symbol '" + Name +
6332 "': " + toString(SecOrErr.takeError()));
6333 return SymbolIndexes;
6337 SymbolIndexes.push_back(Index);
6340 return SymbolIndexes;
6343 template <class ELFT>
6344 bool ELFDumper<ELFT>::printFunctionStackSize(
6345 uint64_t SymValue, std::optional<const Elf_Shdr *> FunctionSec,
6346 const Elf_Shdr &StackSizeSec, DataExtractor Data, uint64_t *Offset) {
6347 SmallVector<uint32_t> FuncSymIndexes =
6348 this->getSymbolIndexesForFunctionAddress(SymValue, FunctionSec);
6349 if (FuncSymIndexes.empty())
6350 reportUniqueWarning(
6351 "could not identify function symbol for stack size entry in " +
6352 describe(StackSizeSec));
6354 // Extract the size. The expectation is that Offset is pointing to the right
6355 // place, i.e. past the function address.
6356 Error Err = Error::success();
6357 uint64_t StackSize = Data.getULEB128(Offset, &Err);
6358 if (Err) {
6359 reportUniqueWarning("could not extract a valid stack size from " +
6360 describe(StackSizeSec) + ": " +
6361 toString(std::move(Err)));
6362 return false;
6365 if (FuncSymIndexes.empty()) {
6366 printStackSizeEntry(StackSize, {"?"});
6367 } else {
6368 SmallVector<std::string> FuncSymNames;
6369 for (uint32_t Index : FuncSymIndexes)
6370 FuncSymNames.push_back(this->getStaticSymbolName(Index));
6371 printStackSizeEntry(StackSize, FuncSymNames);
6374 return true;
6377 template <class ELFT>
6378 void GNUELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
6379 ArrayRef<std::string> FuncNames) {
6380 OS.PadToColumn(2);
6381 OS << format_decimal(Size, 11);
6382 OS.PadToColumn(18);
6384 OS << join(FuncNames.begin(), FuncNames.end(), ", ") << "\n";
6387 template <class ELFT>
6388 void ELFDumper<ELFT>::printStackSize(const Relocation<ELFT> &R,
6389 const Elf_Shdr &RelocSec, unsigned Ndx,
6390 const Elf_Shdr *SymTab,
6391 const Elf_Shdr *FunctionSec,
6392 const Elf_Shdr &StackSizeSec,
6393 const RelocationResolver &Resolver,
6394 DataExtractor Data) {
6395 // This function ignores potentially erroneous input, unless it is directly
6396 // related to stack size reporting.
6397 const Elf_Sym *Sym = nullptr;
6398 Expected<RelSymbol<ELFT>> TargetOrErr = this->getRelocationTarget(R, SymTab);
6399 if (!TargetOrErr)
6400 reportUniqueWarning("unable to get the target of relocation with index " +
6401 Twine(Ndx) + " in " + describe(RelocSec) + ": " +
6402 toString(TargetOrErr.takeError()));
6403 else
6404 Sym = TargetOrErr->Sym;
6406 uint64_t RelocSymValue = 0;
6407 if (Sym) {
6408 Expected<const Elf_Shdr *> SectionOrErr =
6409 this->Obj.getSection(*Sym, SymTab, this->getShndxTable(SymTab));
6410 if (!SectionOrErr) {
6411 reportUniqueWarning(
6412 "cannot identify the section for relocation symbol '" +
6413 (*TargetOrErr).Name + "': " + toString(SectionOrErr.takeError()));
6414 } else if (*SectionOrErr != FunctionSec) {
6415 reportUniqueWarning("relocation symbol '" + (*TargetOrErr).Name +
6416 "' is not in the expected section");
6417 // Pretend that the symbol is in the correct section and report its
6418 // stack size anyway.
6419 FunctionSec = *SectionOrErr;
6422 RelocSymValue = Sym->st_value;
6425 uint64_t Offset = R.Offset;
6426 if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
6427 reportUniqueWarning("found invalid relocation offset (0x" +
6428 Twine::utohexstr(Offset) + ") into " +
6429 describe(StackSizeSec) +
6430 " while trying to extract a stack size entry");
6431 return;
6434 uint64_t SymValue = Resolver(R.Type, Offset, RelocSymValue,
6435 Data.getAddress(&Offset), R.Addend.value_or(0));
6436 this->printFunctionStackSize(SymValue, FunctionSec, StackSizeSec, Data,
6437 &Offset);
6440 template <class ELFT>
6441 void ELFDumper<ELFT>::printNonRelocatableStackSizes(
6442 std::function<void()> PrintHeader) {
6443 // This function ignores potentially erroneous input, unless it is directly
6444 // related to stack size reporting.
6445 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
6446 if (this->getPrintableSectionName(Sec) != ".stack_sizes")
6447 continue;
6448 PrintHeader();
6449 ArrayRef<uint8_t> Contents =
6450 unwrapOrError(this->FileName, Obj.getSectionContents(Sec));
6451 DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
6452 uint64_t Offset = 0;
6453 while (Offset < Contents.size()) {
6454 // The function address is followed by a ULEB representing the stack
6455 // size. Check for an extra byte before we try to process the entry.
6456 if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) {
6457 reportUniqueWarning(
6458 describe(Sec) +
6459 " ended while trying to extract a stack size entry");
6460 break;
6462 uint64_t SymValue = Data.getAddress(&Offset);
6463 if (!printFunctionStackSize(SymValue, /*FunctionSec=*/std::nullopt, Sec,
6464 Data, &Offset))
6465 break;
6470 template <class ELFT>
6471 void ELFDumper<ELFT>::printRelocatableStackSizes(
6472 std::function<void()> PrintHeader) {
6473 // Build a map between stack size sections and their corresponding relocation
6474 // sections.
6475 auto IsMatch = [&](const Elf_Shdr &Sec) -> bool {
6476 StringRef SectionName;
6477 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec))
6478 SectionName = *NameOrErr;
6479 else
6480 consumeError(NameOrErr.takeError());
6482 return SectionName == ".stack_sizes";
6485 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>>
6486 StackSizeRelocMapOrErr = Obj.getSectionAndRelocations(IsMatch);
6487 if (!StackSizeRelocMapOrErr) {
6488 reportUniqueWarning("unable to get stack size map section(s): " +
6489 toString(StackSizeRelocMapOrErr.takeError()));
6490 return;
6493 for (const auto &StackSizeMapEntry : *StackSizeRelocMapOrErr) {
6494 PrintHeader();
6495 const Elf_Shdr *StackSizesELFSec = StackSizeMapEntry.first;
6496 const Elf_Shdr *RelocSec = StackSizeMapEntry.second;
6498 // Warn about stack size sections without a relocation section.
6499 if (!RelocSec) {
6500 reportWarning(createError(".stack_sizes (" + describe(*StackSizesELFSec) +
6501 ") does not have a corresponding "
6502 "relocation section"),
6503 FileName);
6504 continue;
6507 // A .stack_sizes section header's sh_link field is supposed to point
6508 // to the section that contains the functions whose stack sizes are
6509 // described in it.
6510 const Elf_Shdr *FunctionSec = unwrapOrError(
6511 this->FileName, Obj.getSection(StackSizesELFSec->sh_link));
6513 SupportsRelocation IsSupportedFn;
6514 RelocationResolver Resolver;
6515 std::tie(IsSupportedFn, Resolver) = getRelocationResolver(this->ObjF);
6516 ArrayRef<uint8_t> Contents =
6517 unwrapOrError(this->FileName, Obj.getSectionContents(*StackSizesELFSec));
6518 DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr));
6520 forEachRelocationDo(
6521 *RelocSec, /*RawRelr=*/false,
6522 [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
6523 const Elf_Shdr *SymTab) {
6524 if (!IsSupportedFn || !IsSupportedFn(R.Type)) {
6525 reportUniqueWarning(
6526 describe(*RelocSec) +
6527 " contains an unsupported relocation with index " + Twine(Ndx) +
6528 ": " + Obj.getRelocationTypeName(R.Type));
6529 return;
6532 this->printStackSize(R, *RelocSec, Ndx, SymTab, FunctionSec,
6533 *StackSizesELFSec, Resolver, Data);
6535 [](const Elf_Relr &) {
6536 llvm_unreachable("can't get here, because we only support "
6537 "SHT_REL/SHT_RELA sections");
6542 template <class ELFT>
6543 void GNUELFDumper<ELFT>::printStackSizes() {
6544 bool HeaderHasBeenPrinted = false;
6545 auto PrintHeader = [&]() {
6546 if (HeaderHasBeenPrinted)
6547 return;
6548 OS << "\nStack Sizes:\n";
6549 OS.PadToColumn(9);
6550 OS << "Size";
6551 OS.PadToColumn(18);
6552 OS << "Functions\n";
6553 HeaderHasBeenPrinted = true;
6556 // For non-relocatable objects, look directly for sections whose name starts
6557 // with .stack_sizes and process the contents.
6558 if (this->Obj.getHeader().e_type == ELF::ET_REL)
6559 this->printRelocatableStackSizes(PrintHeader);
6560 else
6561 this->printNonRelocatableStackSizes(PrintHeader);
6564 template <class ELFT>
6565 void GNUELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
6566 size_t Bias = ELFT::Is64Bits ? 8 : 0;
6567 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
6568 OS.PadToColumn(2);
6569 OS << format_hex_no_prefix(Parser.getGotAddress(E), 8 + Bias);
6570 OS.PadToColumn(11 + Bias);
6571 OS << format_decimal(Parser.getGotOffset(E), 6) << "(gp)";
6572 OS.PadToColumn(22 + Bias);
6573 OS << format_hex_no_prefix(*E, 8 + Bias);
6574 OS.PadToColumn(31 + 2 * Bias);
6575 OS << Purpose << "\n";
6578 OS << (Parser.IsStatic ? "Static GOT:\n" : "Primary GOT:\n");
6579 OS << " Canonical gp value: "
6580 << format_hex_no_prefix(Parser.getGp(), 8 + Bias) << "\n\n";
6582 OS << " Reserved entries:\n";
6583 if (ELFT::Is64Bits)
6584 OS << " Address Access Initial Purpose\n";
6585 else
6586 OS << " Address Access Initial Purpose\n";
6587 PrintEntry(Parser.getGotLazyResolver(), "Lazy resolver");
6588 if (Parser.getGotModulePointer())
6589 PrintEntry(Parser.getGotModulePointer(), "Module pointer (GNU extension)");
6591 if (!Parser.getLocalEntries().empty()) {
6592 OS << "\n";
6593 OS << " Local entries:\n";
6594 if (ELFT::Is64Bits)
6595 OS << " Address Access Initial\n";
6596 else
6597 OS << " Address Access Initial\n";
6598 for (auto &E : Parser.getLocalEntries())
6599 PrintEntry(&E, "");
6602 if (Parser.IsStatic)
6603 return;
6605 if (!Parser.getGlobalEntries().empty()) {
6606 OS << "\n";
6607 OS << " Global entries:\n";
6608 if (ELFT::Is64Bits)
6609 OS << " Address Access Initial Sym.Val."
6610 << " Type Ndx Name\n";
6611 else
6612 OS << " Address Access Initial Sym.Val. Type Ndx Name\n";
6614 DataRegion<Elf_Word> ShndxTable(
6615 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6616 for (auto &E : Parser.getGlobalEntries()) {
6617 const Elf_Sym &Sym = *Parser.getGotSym(&E);
6618 const Elf_Sym &FirstSym = this->dynamic_symbols()[0];
6619 std::string SymName = this->getFullSymbolName(
6620 Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
6622 OS.PadToColumn(2);
6623 OS << to_string(format_hex_no_prefix(Parser.getGotAddress(&E), 8 + Bias));
6624 OS.PadToColumn(11 + Bias);
6625 OS << to_string(format_decimal(Parser.getGotOffset(&E), 6)) + "(gp)";
6626 OS.PadToColumn(22 + Bias);
6627 OS << to_string(format_hex_no_prefix(E, 8 + Bias));
6628 OS.PadToColumn(31 + 2 * Bias);
6629 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
6630 OS.PadToColumn(40 + 3 * Bias);
6631 OS << enumToString(Sym.getType(), ArrayRef(ElfSymbolTypes));
6632 OS.PadToColumn(48 + 3 * Bias);
6633 OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
6634 ShndxTable);
6635 OS.PadToColumn(52 + 3 * Bias);
6636 OS << SymName << "\n";
6640 if (!Parser.getOtherEntries().empty())
6641 OS << "\n Number of TLS and multi-GOT entries "
6642 << Parser.getOtherEntries().size() << "\n";
6645 template <class ELFT>
6646 void GNUELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
6647 size_t Bias = ELFT::Is64Bits ? 8 : 0;
6648 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
6649 OS.PadToColumn(2);
6650 OS << format_hex_no_prefix(Parser.getPltAddress(E), 8 + Bias);
6651 OS.PadToColumn(11 + Bias);
6652 OS << format_hex_no_prefix(*E, 8 + Bias);
6653 OS.PadToColumn(20 + 2 * Bias);
6654 OS << Purpose << "\n";
6657 OS << "PLT GOT:\n\n";
6659 OS << " Reserved entries:\n";
6660 OS << " Address Initial Purpose\n";
6661 PrintEntry(Parser.getPltLazyResolver(), "PLT lazy resolver");
6662 if (Parser.getPltModulePointer())
6663 PrintEntry(Parser.getPltModulePointer(), "Module pointer");
6665 if (!Parser.getPltEntries().empty()) {
6666 OS << "\n";
6667 OS << " Entries:\n";
6668 OS << " Address Initial Sym.Val. Type Ndx Name\n";
6669 DataRegion<Elf_Word> ShndxTable(
6670 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
6671 for (auto &E : Parser.getPltEntries()) {
6672 const Elf_Sym &Sym = *Parser.getPltSym(&E);
6673 const Elf_Sym &FirstSym = *cantFail(
6674 this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
6675 std::string SymName = this->getFullSymbolName(
6676 Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
6678 OS.PadToColumn(2);
6679 OS << to_string(format_hex_no_prefix(Parser.getPltAddress(&E), 8 + Bias));
6680 OS.PadToColumn(11 + Bias);
6681 OS << to_string(format_hex_no_prefix(E, 8 + Bias));
6682 OS.PadToColumn(20 + 2 * Bias);
6683 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
6684 OS.PadToColumn(29 + 3 * Bias);
6685 OS << enumToString(Sym.getType(), ArrayRef(ElfSymbolTypes));
6686 OS.PadToColumn(37 + 3 * Bias);
6687 OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(),
6688 ShndxTable);
6689 OS.PadToColumn(41 + 3 * Bias);
6690 OS << SymName << "\n";
6695 template <class ELFT>
6696 Expected<const Elf_Mips_ABIFlags<ELFT> *>
6697 getMipsAbiFlagsSection(const ELFDumper<ELFT> &Dumper) {
6698 const typename ELFT::Shdr *Sec = Dumper.findSectionByName(".MIPS.abiflags");
6699 if (Sec == nullptr)
6700 return nullptr;
6702 constexpr StringRef ErrPrefix = "unable to read the .MIPS.abiflags section: ";
6703 Expected<ArrayRef<uint8_t>> DataOrErr =
6704 Dumper.getElfObject().getELFFile().getSectionContents(*Sec);
6705 if (!DataOrErr)
6706 return createError(ErrPrefix + toString(DataOrErr.takeError()));
6708 if (DataOrErr->size() != sizeof(Elf_Mips_ABIFlags<ELFT>))
6709 return createError(ErrPrefix + "it has a wrong size (" +
6710 Twine(DataOrErr->size()) + ")");
6711 return reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(DataOrErr->data());
6714 template <class ELFT> void GNUELFDumper<ELFT>::printMipsABIFlags() {
6715 const Elf_Mips_ABIFlags<ELFT> *Flags = nullptr;
6716 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
6717 getMipsAbiFlagsSection(*this))
6718 Flags = *SecOrErr;
6719 else
6720 this->reportUniqueWarning(SecOrErr.takeError());
6721 if (!Flags)
6722 return;
6724 OS << "MIPS ABI Flags Version: " << Flags->version << "\n\n";
6725 OS << "ISA: MIPS" << int(Flags->isa_level);
6726 if (Flags->isa_rev > 1)
6727 OS << "r" << int(Flags->isa_rev);
6728 OS << "\n";
6729 OS << "GPR size: " << getMipsRegisterSize(Flags->gpr_size) << "\n";
6730 OS << "CPR1 size: " << getMipsRegisterSize(Flags->cpr1_size) << "\n";
6731 OS << "CPR2 size: " << getMipsRegisterSize(Flags->cpr2_size) << "\n";
6732 OS << "FP ABI: " << enumToString(Flags->fp_abi, ArrayRef(ElfMipsFpABIType))
6733 << "\n";
6734 OS << "ISA Extension: "
6735 << enumToString(Flags->isa_ext, ArrayRef(ElfMipsISAExtType)) << "\n";
6736 if (Flags->ases == 0)
6737 OS << "ASEs: None\n";
6738 else
6739 // FIXME: Print each flag on a separate line.
6740 OS << "ASEs: " << printFlags(Flags->ases, ArrayRef(ElfMipsASEFlags))
6741 << "\n";
6742 OS << "FLAGS 1: " << format_hex_no_prefix(Flags->flags1, 8, false) << "\n";
6743 OS << "FLAGS 2: " << format_hex_no_prefix(Flags->flags2, 8, false) << "\n";
6744 OS << "\n";
6747 template <class ELFT> void LLVMELFDumper<ELFT>::printFileHeaders() {
6748 const Elf_Ehdr &E = this->Obj.getHeader();
6750 DictScope D(W, "ElfHeader");
6752 DictScope D(W, "Ident");
6753 W.printBinary("Magic",
6754 ArrayRef<unsigned char>(E.e_ident).slice(ELF::EI_MAG0, 4));
6755 W.printEnum("Class", E.e_ident[ELF::EI_CLASS], ArrayRef(ElfClass));
6756 W.printEnum("DataEncoding", E.e_ident[ELF::EI_DATA],
6757 ArrayRef(ElfDataEncoding));
6758 W.printNumber("FileVersion", E.e_ident[ELF::EI_VERSION]);
6760 auto OSABI = ArrayRef(ElfOSABI);
6761 if (E.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH &&
6762 E.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) {
6763 switch (E.e_machine) {
6764 case ELF::EM_AMDGPU:
6765 OSABI = ArrayRef(AMDGPUElfOSABI);
6766 break;
6767 case ELF::EM_ARM:
6768 OSABI = ArrayRef(ARMElfOSABI);
6769 break;
6770 case ELF::EM_TI_C6000:
6771 OSABI = ArrayRef(C6000ElfOSABI);
6772 break;
6775 W.printEnum("OS/ABI", E.e_ident[ELF::EI_OSABI], OSABI);
6776 W.printNumber("ABIVersion", E.e_ident[ELF::EI_ABIVERSION]);
6777 W.printBinary("Unused",
6778 ArrayRef<unsigned char>(E.e_ident).slice(ELF::EI_PAD));
6781 std::string TypeStr;
6782 if (const EnumEntry<unsigned> *Ent = getObjectFileEnumEntry(E.e_type)) {
6783 TypeStr = Ent->Name.str();
6784 } else {
6785 if (E.e_type >= ET_LOPROC)
6786 TypeStr = "Processor Specific";
6787 else if (E.e_type >= ET_LOOS)
6788 TypeStr = "OS Specific";
6789 else
6790 TypeStr = "Unknown";
6792 W.printString("Type", TypeStr + " (0x" + utohexstr(E.e_type) + ")");
6794 W.printEnum("Machine", E.e_machine, ArrayRef(ElfMachineType));
6795 W.printNumber("Version", E.e_version);
6796 W.printHex("Entry", E.e_entry);
6797 W.printHex("ProgramHeaderOffset", E.e_phoff);
6798 W.printHex("SectionHeaderOffset", E.e_shoff);
6799 if (E.e_machine == EM_MIPS)
6800 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderMipsFlags),
6801 unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
6802 unsigned(ELF::EF_MIPS_MACH));
6803 else if (E.e_machine == EM_AMDGPU) {
6804 switch (E.e_ident[ELF::EI_ABIVERSION]) {
6805 default:
6806 W.printHex("Flags", E.e_flags);
6807 break;
6808 case 0:
6809 // ELFOSABI_AMDGPU_PAL, ELFOSABI_AMDGPU_MESA3D support *_V3 flags.
6810 [[fallthrough]];
6811 case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
6812 W.printFlags("Flags", E.e_flags,
6813 ArrayRef(ElfHeaderAMDGPUFlagsABIVersion3),
6814 unsigned(ELF::EF_AMDGPU_MACH));
6815 break;
6816 case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
6817 case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
6818 W.printFlags("Flags", E.e_flags,
6819 ArrayRef(ElfHeaderAMDGPUFlagsABIVersion4),
6820 unsigned(ELF::EF_AMDGPU_MACH),
6821 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
6822 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
6823 break;
6825 } else if (E.e_machine == EM_RISCV)
6826 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderRISCVFlags));
6827 else if (E.e_machine == EM_AVR)
6828 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderAVRFlags),
6829 unsigned(ELF::EF_AVR_ARCH_MASK));
6830 else if (E.e_machine == EM_LOONGARCH)
6831 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderLoongArchFlags),
6832 unsigned(ELF::EF_LOONGARCH_ABI_MODIFIER_MASK),
6833 unsigned(ELF::EF_LOONGARCH_OBJABI_MASK));
6834 else if (E.e_machine == EM_XTENSA)
6835 W.printFlags("Flags", E.e_flags, ArrayRef(ElfHeaderXtensaFlags),
6836 unsigned(ELF::EF_XTENSA_MACH));
6837 else
6838 W.printFlags("Flags", E.e_flags);
6839 W.printNumber("HeaderSize", E.e_ehsize);
6840 W.printNumber("ProgramHeaderEntrySize", E.e_phentsize);
6841 W.printNumber("ProgramHeaderCount", E.e_phnum);
6842 W.printNumber("SectionHeaderEntrySize", E.e_shentsize);
6843 W.printString("SectionHeaderCount",
6844 getSectionHeadersNumString(this->Obj, this->FileName));
6845 W.printString("StringTableSectionIndex",
6846 getSectionHeaderTableIndexString(this->Obj, this->FileName));
6850 template <class ELFT> void LLVMELFDumper<ELFT>::printGroupSections() {
6851 DictScope Lists(W, "Groups");
6852 std::vector<GroupSection> V = this->getGroups();
6853 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V);
6854 for (const GroupSection &G : V) {
6855 DictScope D(W, "Group");
6856 W.printNumber("Name", G.Name, G.ShName);
6857 W.printNumber("Index", G.Index);
6858 W.printNumber("Link", G.Link);
6859 W.printNumber("Info", G.Info);
6860 W.printHex("Type", getGroupType(G.Type), G.Type);
6861 W.printString("Signature", G.Signature);
6863 ListScope L(W, getGroupSectionHeaderName());
6864 for (const GroupMember &GM : G.Members) {
6865 const GroupSection *MainGroup = Map[GM.Index];
6866 if (MainGroup != &G)
6867 this->reportUniqueWarning(
6868 "section with index " + Twine(GM.Index) +
6869 ", included in the group section with index " +
6870 Twine(MainGroup->Index) +
6871 ", was also found in the group section with index " +
6872 Twine(G.Index));
6873 printSectionGroupMembers(GM.Name, GM.Index);
6877 if (V.empty())
6878 printEmptyGroupMessage();
6881 template <class ELFT>
6882 std::string LLVMELFDumper<ELFT>::getGroupSectionHeaderName() const {
6883 return "Section(s) in group";
6886 template <class ELFT>
6887 void LLVMELFDumper<ELFT>::printSectionGroupMembers(StringRef Name,
6888 uint64_t Idx) const {
6889 W.startLine() << Name << " (" << Idx << ")\n";
6892 template <class ELFT> void LLVMELFDumper<ELFT>::printRelocations() {
6893 ListScope D(W, "Relocations");
6895 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6896 if (!isRelocationSec<ELFT>(Sec))
6897 continue;
6899 StringRef Name = this->getPrintableSectionName(Sec);
6900 unsigned SecNdx = &Sec - &cantFail(this->Obj.sections()).front();
6901 printRelocationSectionInfo(Sec, Name, SecNdx);
6905 template <class ELFT>
6906 void LLVMELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) {
6907 W.startLine() << W.hex(R) << "\n";
6910 template <class ELFT>
6911 void LLVMELFDumper<ELFT>::printExpandedRelRelaReloc(const Relocation<ELFT> &R,
6912 StringRef SymbolName,
6913 StringRef RelocName) {
6914 DictScope Group(W, "Relocation");
6915 W.printHex("Offset", R.Offset);
6916 W.printNumber("Type", RelocName, R.Type);
6917 W.printNumber("Symbol", !SymbolName.empty() ? SymbolName : "-", R.Symbol);
6918 if (R.Addend)
6919 W.printHex("Addend", (uintX_t)*R.Addend);
6922 template <class ELFT>
6923 void LLVMELFDumper<ELFT>::printDefaultRelRelaReloc(const Relocation<ELFT> &R,
6924 StringRef SymbolName,
6925 StringRef RelocName) {
6926 raw_ostream &OS = W.startLine();
6927 OS << W.hex(R.Offset) << " " << RelocName << " "
6928 << (!SymbolName.empty() ? SymbolName : "-");
6929 if (R.Addend)
6930 OS << " " << W.hex((uintX_t)*R.Addend);
6931 OS << "\n";
6934 template <class ELFT>
6935 void LLVMELFDumper<ELFT>::printRelocationSectionInfo(const Elf_Shdr &Sec,
6936 StringRef Name,
6937 const unsigned SecNdx) {
6938 DictScope D(W, (Twine("Section (") + Twine(SecNdx) + ") " + Name).str());
6939 this->printRelocationsHelper(Sec);
6942 template <class ELFT> void LLVMELFDumper<ELFT>::printEmptyGroupMessage() const {
6943 W.startLine() << "There are no group sections in the file.\n";
6946 template <class ELFT>
6947 void LLVMELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
6948 const RelSymbol<ELFT> &RelSym) {
6949 StringRef SymbolName = RelSym.Name;
6950 SmallString<32> RelocName;
6951 this->Obj.getRelocationTypeName(R.Type, RelocName);
6953 if (opts::ExpandRelocs) {
6954 printExpandedRelRelaReloc(R, SymbolName, RelocName);
6955 } else {
6956 printDefaultRelRelaReloc(R, SymbolName, RelocName);
6960 template <class ELFT> void LLVMELFDumper<ELFT>::printSectionHeaders() {
6961 ListScope SectionsD(W, "Sections");
6963 int SectionIndex = -1;
6964 std::vector<EnumEntry<unsigned>> FlagsList =
6965 getSectionFlagsForTarget(this->Obj.getHeader().e_ident[ELF::EI_OSABI],
6966 this->Obj.getHeader().e_machine);
6967 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
6968 DictScope SectionD(W, "Section");
6969 W.printNumber("Index", ++SectionIndex);
6970 W.printNumber("Name", this->getPrintableSectionName(Sec), Sec.sh_name);
6971 W.printHex("Type",
6972 object::getELFSectionTypeName(this->Obj.getHeader().e_machine,
6973 Sec.sh_type),
6974 Sec.sh_type);
6975 W.printFlags("Flags", Sec.sh_flags, ArrayRef(FlagsList));
6976 W.printHex("Address", Sec.sh_addr);
6977 W.printHex("Offset", Sec.sh_offset);
6978 W.printNumber("Size", Sec.sh_size);
6979 W.printNumber("Link", Sec.sh_link);
6980 W.printNumber("Info", Sec.sh_info);
6981 W.printNumber("AddressAlignment", Sec.sh_addralign);
6982 W.printNumber("EntrySize", Sec.sh_entsize);
6984 if (opts::SectionRelocations) {
6985 ListScope D(W, "Relocations");
6986 this->printRelocationsHelper(Sec);
6989 if (opts::SectionSymbols) {
6990 ListScope D(W, "Symbols");
6991 if (this->DotSymtabSec) {
6992 StringRef StrTable = unwrapOrError(
6993 this->FileName,
6994 this->Obj.getStringTableForSymtab(*this->DotSymtabSec));
6995 ArrayRef<Elf_Word> ShndxTable = this->getShndxTable(this->DotSymtabSec);
6997 typename ELFT::SymRange Symbols = unwrapOrError(
6998 this->FileName, this->Obj.symbols(this->DotSymtabSec));
6999 for (const Elf_Sym &Sym : Symbols) {
7000 const Elf_Shdr *SymSec = unwrapOrError(
7001 this->FileName,
7002 this->Obj.getSection(Sym, this->DotSymtabSec, ShndxTable));
7003 if (SymSec == &Sec)
7004 printSymbol(Sym, &Sym - &Symbols[0], ShndxTable, StrTable, false,
7005 false);
7010 if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) {
7011 ArrayRef<uint8_t> Data =
7012 unwrapOrError(this->FileName, this->Obj.getSectionContents(Sec));
7013 W.printBinaryBlock(
7014 "SectionData",
7015 StringRef(reinterpret_cast<const char *>(Data.data()), Data.size()));
7020 template <class ELFT>
7021 void LLVMELFDumper<ELFT>::printSymbolSection(
7022 const Elf_Sym &Symbol, unsigned SymIndex,
7023 DataRegion<Elf_Word> ShndxTable) const {
7024 auto GetSectionSpecialType = [&]() -> std::optional<StringRef> {
7025 if (Symbol.isUndefined())
7026 return StringRef("Undefined");
7027 if (Symbol.isProcessorSpecific())
7028 return StringRef("Processor Specific");
7029 if (Symbol.isOSSpecific())
7030 return StringRef("Operating System Specific");
7031 if (Symbol.isAbsolute())
7032 return StringRef("Absolute");
7033 if (Symbol.isCommon())
7034 return StringRef("Common");
7035 if (Symbol.isReserved() && Symbol.st_shndx != SHN_XINDEX)
7036 return StringRef("Reserved");
7037 return std::nullopt;
7040 if (std::optional<StringRef> Type = GetSectionSpecialType()) {
7041 W.printHex("Section", *Type, Symbol.st_shndx);
7042 return;
7045 Expected<unsigned> SectionIndex =
7046 this->getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
7047 if (!SectionIndex) {
7048 assert(Symbol.st_shndx == SHN_XINDEX &&
7049 "getSymbolSectionIndex should only fail due to an invalid "
7050 "SHT_SYMTAB_SHNDX table/reference");
7051 this->reportUniqueWarning(SectionIndex.takeError());
7052 W.printHex("Section", "Reserved", SHN_XINDEX);
7053 return;
7056 Expected<StringRef> SectionName =
7057 this->getSymbolSectionName(Symbol, *SectionIndex);
7058 if (!SectionName) {
7059 // Don't report an invalid section name if the section headers are missing.
7060 // In such situations, all sections will be "invalid".
7061 if (!this->ObjF.sections().empty())
7062 this->reportUniqueWarning(SectionName.takeError());
7063 else
7064 consumeError(SectionName.takeError());
7065 W.printHex("Section", "<?>", *SectionIndex);
7066 } else {
7067 W.printHex("Section", *SectionName, *SectionIndex);
7071 template <class ELFT>
7072 void LLVMELFDumper<ELFT>::printSymbolOtherField(const Elf_Sym &Symbol) const {
7073 std::vector<EnumEntry<unsigned>> SymOtherFlags =
7074 this->getOtherFlagsFromSymbol(this->Obj.getHeader(), Symbol);
7075 W.printFlags("Other", Symbol.st_other, ArrayRef(SymOtherFlags), 0x3u);
7078 template <class ELFT>
7079 void LLVMELFDumper<ELFT>::printZeroSymbolOtherField(
7080 const Elf_Sym &Symbol) const {
7081 assert(Symbol.st_other == 0 && "non-zero Other Field");
7082 // Usually st_other flag is zero. Do not pollute the output
7083 // by flags enumeration in that case.
7084 W.printNumber("Other", 0);
7087 template <class ELFT>
7088 void LLVMELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
7089 DataRegion<Elf_Word> ShndxTable,
7090 std::optional<StringRef> StrTable,
7091 bool IsDynamic,
7092 bool /*NonVisibilityBitsUsed*/) const {
7093 std::string FullSymbolName = this->getFullSymbolName(
7094 Symbol, SymIndex, ShndxTable, StrTable, IsDynamic);
7095 unsigned char SymbolType = Symbol.getType();
7097 DictScope D(W, "Symbol");
7098 W.printNumber("Name", FullSymbolName, Symbol.st_name);
7099 W.printHex("Value", Symbol.st_value);
7100 W.printNumber("Size", Symbol.st_size);
7101 W.printEnum("Binding", Symbol.getBinding(), ArrayRef(ElfSymbolBindings));
7102 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
7103 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
7104 W.printEnum("Type", SymbolType, ArrayRef(AMDGPUSymbolTypes));
7105 else
7106 W.printEnum("Type", SymbolType, ArrayRef(ElfSymbolTypes));
7107 if (Symbol.st_other == 0)
7108 printZeroSymbolOtherField(Symbol);
7109 else
7110 printSymbolOtherField(Symbol);
7111 printSymbolSection(Symbol, SymIndex, ShndxTable);
7114 template <class ELFT>
7115 void LLVMELFDumper<ELFT>::printSymbols(bool PrintSymbols,
7116 bool PrintDynamicSymbols) {
7117 if (PrintSymbols) {
7118 ListScope Group(W, "Symbols");
7119 this->printSymbolsHelper(false);
7121 if (PrintDynamicSymbols) {
7122 ListScope Group(W, "DynamicSymbols");
7123 this->printSymbolsHelper(true);
7127 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicTable() {
7128 Elf_Dyn_Range Table = this->dynamic_table();
7129 if (Table.empty())
7130 return;
7132 W.startLine() << "DynamicSection [ (" << Table.size() << " entries)\n";
7134 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table);
7135 // The "Name/Value" column should be indented from the "Type" column by N
7136 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
7137 // space (1) = -3.
7138 W.startLine() << " Tag" << std::string(ELFT::Is64Bits ? 16 : 8, ' ')
7139 << "Type" << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
7141 std::string ValueFmt = "%-" + std::to_string(MaxTagSize) + "s ";
7142 for (auto Entry : Table) {
7143 uintX_t Tag = Entry.getTag();
7144 std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
7145 W.startLine() << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10, true)
7146 << " "
7147 << format(ValueFmt.c_str(),
7148 this->Obj.getDynamicTagAsString(Tag).c_str())
7149 << Value << "\n";
7151 W.startLine() << "]\n";
7154 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicRelocations() {
7155 W.startLine() << "Dynamic Relocations {\n";
7156 W.indent();
7157 this->printDynamicRelocationsHelper();
7158 W.unindent();
7159 W.startLine() << "}\n";
7162 template <class ELFT>
7163 void LLVMELFDumper<ELFT>::printProgramHeaders(
7164 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
7165 if (PrintProgramHeaders)
7166 printProgramHeaders();
7167 if (PrintSectionMapping == cl::BOU_TRUE)
7168 printSectionMapping();
7171 template <class ELFT> void LLVMELFDumper<ELFT>::printProgramHeaders() {
7172 ListScope L(W, "ProgramHeaders");
7174 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
7175 if (!PhdrsOrErr) {
7176 this->reportUniqueWarning("unable to dump program headers: " +
7177 toString(PhdrsOrErr.takeError()));
7178 return;
7181 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
7182 DictScope P(W, "ProgramHeader");
7183 StringRef Type =
7184 segmentTypeToString(this->Obj.getHeader().e_machine, Phdr.p_type);
7186 W.printHex("Type", Type.empty() ? "Unknown" : Type, Phdr.p_type);
7187 W.printHex("Offset", Phdr.p_offset);
7188 W.printHex("VirtualAddress", Phdr.p_vaddr);
7189 W.printHex("PhysicalAddress", Phdr.p_paddr);
7190 W.printNumber("FileSize", Phdr.p_filesz);
7191 W.printNumber("MemSize", Phdr.p_memsz);
7192 W.printFlags("Flags", Phdr.p_flags, ArrayRef(ElfSegmentFlags));
7193 W.printNumber("Alignment", Phdr.p_align);
7197 template <class ELFT>
7198 void LLVMELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
7199 ListScope SS(W, "VersionSymbols");
7200 if (!Sec)
7201 return;
7203 StringRef StrTable;
7204 ArrayRef<Elf_Sym> Syms;
7205 const Elf_Shdr *SymTabSec;
7206 Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
7207 this->getVersionTable(*Sec, &Syms, &StrTable, &SymTabSec);
7208 if (!VerTableOrErr) {
7209 this->reportUniqueWarning(VerTableOrErr.takeError());
7210 return;
7213 if (StrTable.empty() || Syms.empty() || Syms.size() != VerTableOrErr->size())
7214 return;
7216 ArrayRef<Elf_Word> ShNdxTable = this->getShndxTable(SymTabSec);
7217 for (size_t I = 0, E = Syms.size(); I < E; ++I) {
7218 DictScope S(W, "Symbol");
7219 W.printNumber("Version", (*VerTableOrErr)[I].vs_index & VERSYM_VERSION);
7220 W.printString("Name",
7221 this->getFullSymbolName(Syms[I], I, ShNdxTable, StrTable,
7222 /*IsDynamic=*/true));
7226 const EnumEntry<unsigned> SymVersionFlags[] = {
7227 {"Base", "BASE", VER_FLG_BASE},
7228 {"Weak", "WEAK", VER_FLG_WEAK},
7229 {"Info", "INFO", VER_FLG_INFO}};
7231 template <class ELFT>
7232 void LLVMELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
7233 ListScope SD(W, "VersionDefinitions");
7234 if (!Sec)
7235 return;
7237 Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
7238 if (!V) {
7239 this->reportUniqueWarning(V.takeError());
7240 return;
7243 for (const VerDef &D : *V) {
7244 DictScope Def(W, "Definition");
7245 W.printNumber("Version", D.Version);
7246 W.printFlags("Flags", D.Flags, ArrayRef(SymVersionFlags));
7247 W.printNumber("Index", D.Ndx);
7248 W.printNumber("Hash", D.Hash);
7249 W.printString("Name", D.Name.c_str());
7250 W.printList(
7251 "Predecessors", D.AuxV,
7252 [](raw_ostream &OS, const VerdAux &Aux) { OS << Aux.Name.c_str(); });
7256 template <class ELFT>
7257 void LLVMELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
7258 ListScope SD(W, "VersionRequirements");
7259 if (!Sec)
7260 return;
7262 Expected<std::vector<VerNeed>> V =
7263 this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
7264 if (!V) {
7265 this->reportUniqueWarning(V.takeError());
7266 return;
7269 for (const VerNeed &VN : *V) {
7270 DictScope Entry(W, "Dependency");
7271 W.printNumber("Version", VN.Version);
7272 W.printNumber("Count", VN.Cnt);
7273 W.printString("FileName", VN.File.c_str());
7275 ListScope L(W, "Entries");
7276 for (const VernAux &Aux : VN.AuxV) {
7277 DictScope Entry(W, "Entry");
7278 W.printNumber("Hash", Aux.Hash);
7279 W.printFlags("Flags", Aux.Flags, ArrayRef(SymVersionFlags));
7280 W.printNumber("Index", Aux.Other);
7281 W.printString("Name", Aux.Name.c_str());
7286 template <class ELFT>
7287 void LLVMELFDumper<ELFT>::printHashHistogramStats(size_t NBucket,
7288 size_t MaxChain,
7289 size_t TotalSyms,
7290 ArrayRef<size_t> Count,
7291 bool IsGnu) const {
7292 StringRef HistName = IsGnu ? "GnuHashHistogram" : "HashHistogram";
7293 StringRef BucketName = IsGnu ? "Bucket" : "Chain";
7294 StringRef ListName = IsGnu ? "Buckets" : "Chains";
7295 DictScope Outer(W, HistName);
7296 W.printNumber("TotalBuckets", NBucket);
7297 ListScope Buckets(W, ListName);
7298 size_t CumulativeNonZero = 0;
7299 for (size_t I = 0; I < MaxChain; ++I) {
7300 CumulativeNonZero += Count[I] * I;
7301 DictScope Bucket(W, BucketName);
7302 W.printNumber("Length", I);
7303 W.printNumber("Count", Count[I]);
7304 W.printNumber("Percentage", (float)(Count[I] * 100.0) / NBucket);
7305 W.printNumber("Coverage", (float)(CumulativeNonZero * 100.0) / TotalSyms);
7309 // Returns true if rel/rela section exists, and populates SymbolIndices.
7310 // Otherwise returns false.
7311 template <class ELFT>
7312 static bool getSymbolIndices(const typename ELFT::Shdr *CGRelSection,
7313 const ELFFile<ELFT> &Obj,
7314 const LLVMELFDumper<ELFT> *Dumper,
7315 SmallVector<uint32_t, 128> &SymbolIndices) {
7316 if (!CGRelSection) {
7317 Dumper->reportUniqueWarning(
7318 "relocation section for a call graph section doesn't exist");
7319 return false;
7322 if (CGRelSection->sh_type == SHT_REL) {
7323 typename ELFT::RelRange CGProfileRel;
7324 Expected<typename ELFT::RelRange> CGProfileRelOrError =
7325 Obj.rels(*CGRelSection);
7326 if (!CGProfileRelOrError) {
7327 Dumper->reportUniqueWarning("unable to load relocations for "
7328 "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
7329 toString(CGProfileRelOrError.takeError()));
7330 return false;
7333 CGProfileRel = *CGProfileRelOrError;
7334 for (const typename ELFT::Rel &Rel : CGProfileRel)
7335 SymbolIndices.push_back(Rel.getSymbol(Obj.isMips64EL()));
7336 } else {
7337 // MC unconditionally produces SHT_REL, but GNU strip/objcopy may convert
7338 // the format to SHT_RELA
7339 // (https://sourceware.org/bugzilla/show_bug.cgi?id=28035)
7340 typename ELFT::RelaRange CGProfileRela;
7341 Expected<typename ELFT::RelaRange> CGProfileRelaOrError =
7342 Obj.relas(*CGRelSection);
7343 if (!CGProfileRelaOrError) {
7344 Dumper->reportUniqueWarning("unable to load relocations for "
7345 "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
7346 toString(CGProfileRelaOrError.takeError()));
7347 return false;
7350 CGProfileRela = *CGProfileRelaOrError;
7351 for (const typename ELFT::Rela &Rela : CGProfileRela)
7352 SymbolIndices.push_back(Rela.getSymbol(Obj.isMips64EL()));
7355 return true;
7358 template <class ELFT> void LLVMELFDumper<ELFT>::printCGProfile() {
7359 auto IsMatch = [](const Elf_Shdr &Sec) -> bool {
7360 return Sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE;
7363 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SecToRelocMapOrErr =
7364 this->Obj.getSectionAndRelocations(IsMatch);
7365 if (!SecToRelocMapOrErr) {
7366 this->reportUniqueWarning("unable to get CG Profile section(s): " +
7367 toString(SecToRelocMapOrErr.takeError()));
7368 return;
7371 for (const auto &CGMapEntry : *SecToRelocMapOrErr) {
7372 const Elf_Shdr *CGSection = CGMapEntry.first;
7373 const Elf_Shdr *CGRelSection = CGMapEntry.second;
7375 Expected<ArrayRef<Elf_CGProfile>> CGProfileOrErr =
7376 this->Obj.template getSectionContentsAsArray<Elf_CGProfile>(*CGSection);
7377 if (!CGProfileOrErr) {
7378 this->reportUniqueWarning(
7379 "unable to load the SHT_LLVM_CALL_GRAPH_PROFILE section: " +
7380 toString(CGProfileOrErr.takeError()));
7381 return;
7384 SmallVector<uint32_t, 128> SymbolIndices;
7385 bool UseReloc =
7386 getSymbolIndices<ELFT>(CGRelSection, this->Obj, this, SymbolIndices);
7387 if (UseReloc && SymbolIndices.size() != CGProfileOrErr->size() * 2) {
7388 this->reportUniqueWarning(
7389 "number of from/to pairs does not match number of frequencies");
7390 UseReloc = false;
7393 ListScope L(W, "CGProfile");
7394 for (uint32_t I = 0, Size = CGProfileOrErr->size(); I != Size; ++I) {
7395 const Elf_CGProfile &CGPE = (*CGProfileOrErr)[I];
7396 DictScope D(W, "CGProfileEntry");
7397 if (UseReloc) {
7398 uint32_t From = SymbolIndices[I * 2];
7399 uint32_t To = SymbolIndices[I * 2 + 1];
7400 W.printNumber("From", this->getStaticSymbolName(From), From);
7401 W.printNumber("To", this->getStaticSymbolName(To), To);
7403 W.printNumber("Weight", CGPE.cgp_weight);
7408 template <class ELFT> void LLVMELFDumper<ELFT>::printBBAddrMaps() {
7409 bool IsRelocatable = this->Obj.getHeader().e_type == ELF::ET_REL;
7410 using Elf_Shdr = typename ELFT::Shdr;
7411 auto IsMatch = [](const Elf_Shdr &Sec) -> bool {
7412 return Sec.sh_type == ELF::SHT_LLVM_BB_ADDR_MAP ||
7413 Sec.sh_type == ELF::SHT_LLVM_BB_ADDR_MAP_V0;
7415 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SecRelocMapOrErr =
7416 this->Obj.getSectionAndRelocations(IsMatch);
7417 if (!SecRelocMapOrErr) {
7418 this->reportUniqueWarning(
7419 "failed to get SHT_LLVM_BB_ADDR_MAP section(s): " +
7420 toString(SecRelocMapOrErr.takeError()));
7421 return;
7423 for (auto const &[Sec, RelocSec] : *SecRelocMapOrErr) {
7424 std::optional<const Elf_Shdr *> FunctionSec;
7425 if (IsRelocatable)
7426 FunctionSec =
7427 unwrapOrError(this->FileName, this->Obj.getSection(Sec->sh_link));
7428 ListScope L(W, "BBAddrMap");
7429 if (IsRelocatable && !RelocSec) {
7430 this->reportUniqueWarning("unable to get relocation section for " +
7431 this->describe(*Sec));
7432 continue;
7434 Expected<std::vector<BBAddrMap>> BBAddrMapOrErr =
7435 this->Obj.decodeBBAddrMap(*Sec, RelocSec);
7436 if (!BBAddrMapOrErr) {
7437 this->reportUniqueWarning("unable to dump " + this->describe(*Sec) +
7438 ": " + toString(BBAddrMapOrErr.takeError()));
7439 continue;
7441 for (const BBAddrMap &AM : *BBAddrMapOrErr) {
7442 DictScope D(W, "Function");
7443 W.printHex("At", AM.Addr);
7444 SmallVector<uint32_t> FuncSymIndex =
7445 this->getSymbolIndexesForFunctionAddress(AM.Addr, FunctionSec);
7446 std::string FuncName = "<?>";
7447 if (FuncSymIndex.empty())
7448 this->reportUniqueWarning(
7449 "could not identify function symbol for address (0x" +
7450 Twine::utohexstr(AM.Addr) + ") in " + this->describe(*Sec));
7451 else
7452 FuncName = this->getStaticSymbolName(FuncSymIndex.front());
7453 W.printString("Name", FuncName);
7455 ListScope L(W, "BB entries");
7456 for (const BBAddrMap::BBEntry &BBE : AM.BBEntries) {
7457 DictScope L(W);
7458 W.printNumber("ID", BBE.ID);
7459 W.printHex("Offset", BBE.Offset);
7460 W.printHex("Size", BBE.Size);
7461 W.printBoolean("HasReturn", BBE.hasReturn());
7462 W.printBoolean("HasTailCall", BBE.hasTailCall());
7463 W.printBoolean("IsEHPad", BBE.isEHPad());
7464 W.printBoolean("CanFallThrough", BBE.canFallThrough());
7470 template <class ELFT> void LLVMELFDumper<ELFT>::printAddrsig() {
7471 ListScope L(W, "Addrsig");
7472 if (!this->DotAddrsigSec)
7473 return;
7475 Expected<std::vector<uint64_t>> SymsOrErr =
7476 decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
7477 if (!SymsOrErr) {
7478 this->reportUniqueWarning(SymsOrErr.takeError());
7479 return;
7482 for (uint64_t Sym : *SymsOrErr)
7483 W.printNumber("Sym", this->getStaticSymbolName(Sym), Sym);
7486 template <typename ELFT>
7487 static bool printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
7488 ScopedPrinter &W) {
7489 // Return true if we were able to pretty-print the note, false otherwise.
7490 switch (NoteType) {
7491 default:
7492 return false;
7493 case ELF::NT_GNU_ABI_TAG: {
7494 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
7495 if (!AbiTag.IsValid) {
7496 W.printString("ABI", "<corrupt GNU_ABI_TAG>");
7497 return false;
7498 } else {
7499 W.printString("OS", AbiTag.OSName);
7500 W.printString("ABI", AbiTag.ABI);
7502 break;
7504 case ELF::NT_GNU_BUILD_ID: {
7505 W.printString("Build ID", getGNUBuildId(Desc));
7506 break;
7508 case ELF::NT_GNU_GOLD_VERSION:
7509 W.printString("Version", getDescAsStringRef(Desc));
7510 break;
7511 case ELF::NT_GNU_PROPERTY_TYPE_0:
7512 ListScope D(W, "Property");
7513 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc))
7514 W.printString(Property);
7515 break;
7517 return true;
7520 static bool printAndroidNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
7521 ScopedPrinter &W) {
7522 // Return true if we were able to pretty-print the note, false otherwise.
7523 AndroidNoteProperties Props = getAndroidNoteProperties(NoteType, Desc);
7524 if (Props.empty())
7525 return false;
7526 for (const auto &KV : Props)
7527 W.printString(KV.first, KV.second);
7528 return true;
7531 template <class ELFT>
7532 void LLVMELFDumper<ELFT>::printMemtag(
7533 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
7534 const ArrayRef<uint8_t> AndroidNoteDesc,
7535 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) {
7537 ListScope L(W, "Memtag Dynamic Entries:");
7538 if (DynamicEntries.empty())
7539 W.printString("< none found >");
7540 for (const auto &DynamicEntryKV : DynamicEntries)
7541 W.printString(DynamicEntryKV.first, DynamicEntryKV.second);
7544 if (!AndroidNoteDesc.empty()) {
7545 ListScope L(W, "Memtag Android Note:");
7546 printAndroidNoteLLVMStyle(ELF::NT_ANDROID_TYPE_MEMTAG, AndroidNoteDesc, W);
7549 if (Descriptors.empty())
7550 return;
7553 ListScope L(W, "Memtag Global Descriptors:");
7554 for (const auto &[Addr, BytesToTag] : Descriptors) {
7555 W.printHex("0x" + utohexstr(Addr), BytesToTag);
7560 template <typename ELFT>
7561 static bool printLLVMOMPOFFLOADNoteLLVMStyle(uint32_t NoteType,
7562 ArrayRef<uint8_t> Desc,
7563 ScopedPrinter &W) {
7564 switch (NoteType) {
7565 default:
7566 return false;
7567 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
7568 W.printString("Version", getDescAsStringRef(Desc));
7569 break;
7570 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
7571 W.printString("Producer", getDescAsStringRef(Desc));
7572 break;
7573 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
7574 W.printString("Producer version", getDescAsStringRef(Desc));
7575 break;
7577 return true;
7580 static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) {
7581 W.printNumber("Page Size", Note.PageSize);
7582 for (const CoreFileMapping &Mapping : Note.Mappings) {
7583 ListScope D(W, "Mapping");
7584 W.printHex("Start", Mapping.Start);
7585 W.printHex("End", Mapping.End);
7586 W.printHex("Offset", Mapping.Offset);
7587 W.printString("Filename", Mapping.Filename);
7591 template <class ELFT> void LLVMELFDumper<ELFT>::printNotes() {
7592 ListScope L(W, "Notes");
7594 std::unique_ptr<DictScope> NoteScope;
7595 size_t Align = 0;
7596 auto StartNotes = [&](std::optional<StringRef> SecName,
7597 const typename ELFT::Off Offset,
7598 const typename ELFT::Addr Size, size_t Al) {
7599 Align = std::max<size_t>(Al, 4);
7600 NoteScope = std::make_unique<DictScope>(W, "NoteSection");
7601 W.printString("Name", SecName ? *SecName : "<?>");
7602 W.printHex("Offset", Offset);
7603 W.printHex("Size", Size);
7606 auto EndNotes = [&] { NoteScope.reset(); };
7608 auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
7609 DictScope D2(W, "Note");
7610 StringRef Name = Note.getName();
7611 ArrayRef<uint8_t> Descriptor = Note.getDesc(Align);
7612 Elf_Word Type = Note.getType();
7614 // Print the note owner/type.
7615 W.printString("Owner", Name);
7616 W.printHex("Data size", Descriptor.size());
7618 StringRef NoteType =
7619 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
7620 if (!NoteType.empty())
7621 W.printString("Type", NoteType);
7622 else
7623 W.printString("Type",
7624 "Unknown (" + to_string(format_hex(Type, 10)) + ")");
7626 // Print the description, or fallback to printing raw bytes for unknown
7627 // owners/if we fail to pretty-print the contents.
7628 if (Name == "GNU") {
7629 if (printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W))
7630 return Error::success();
7631 } else if (Name == "FreeBSD") {
7632 if (std::optional<FreeBSDNote> N =
7633 getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
7634 W.printString(N->Type, N->Value);
7635 return Error::success();
7637 } else if (Name == "AMD") {
7638 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
7639 if (!N.Type.empty()) {
7640 W.printString(N.Type, N.Value);
7641 return Error::success();
7643 } else if (Name == "AMDGPU") {
7644 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
7645 if (!N.Type.empty()) {
7646 W.printString(N.Type, N.Value);
7647 return Error::success();
7649 } else if (Name == "LLVMOMPOFFLOAD") {
7650 if (printLLVMOMPOFFLOADNoteLLVMStyle<ELFT>(Type, Descriptor, W))
7651 return Error::success();
7652 } else if (Name == "CORE") {
7653 if (Type == ELF::NT_FILE) {
7654 DataExtractor DescExtractor(Descriptor,
7655 ELFT::TargetEndianness == support::little,
7656 sizeof(Elf_Addr));
7657 if (Expected<CoreNote> N = readCoreNote(DescExtractor)) {
7658 printCoreNoteLLVMStyle(*N, W);
7659 return Error::success();
7660 } else {
7661 return N.takeError();
7664 } else if (Name == "Android") {
7665 if (printAndroidNoteLLVMStyle(Type, Descriptor, W))
7666 return Error::success();
7668 if (!Descriptor.empty()) {
7669 W.printBinaryBlock("Description data", Descriptor);
7671 return Error::success();
7674 processNotesHelper(*this, /*StartNotesFn=*/StartNotes,
7675 /*ProcessNoteFn=*/ProcessNote, /*FinishNotesFn=*/EndNotes);
7678 template <class ELFT> void LLVMELFDumper<ELFT>::printELFLinkerOptions() {
7679 ListScope L(W, "LinkerOptions");
7681 unsigned I = -1;
7682 for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) {
7683 ++I;
7684 if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS)
7685 continue;
7687 Expected<ArrayRef<uint8_t>> ContentsOrErr =
7688 this->Obj.getSectionContents(Shdr);
7689 if (!ContentsOrErr) {
7690 this->reportUniqueWarning("unable to read the content of the "
7691 "SHT_LLVM_LINKER_OPTIONS section: " +
7692 toString(ContentsOrErr.takeError()));
7693 continue;
7695 if (ContentsOrErr->empty())
7696 continue;
7698 if (ContentsOrErr->back() != 0) {
7699 this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " +
7700 Twine(I) +
7701 " is broken: the "
7702 "content is not null-terminated");
7703 continue;
7706 SmallVector<StringRef, 16> Strings;
7707 toStringRef(ContentsOrErr->drop_back()).split(Strings, '\0');
7708 if (Strings.size() % 2 != 0) {
7709 this->reportUniqueWarning(
7710 "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) +
7711 " is broken: an incomplete "
7712 "key-value pair was found. The last possible key was: \"" +
7713 Strings.back() + "\"");
7714 continue;
7717 for (size_t I = 0; I < Strings.size(); I += 2)
7718 W.printString(Strings[I], Strings[I + 1]);
7722 template <class ELFT> void LLVMELFDumper<ELFT>::printDependentLibs() {
7723 ListScope L(W, "DependentLibs");
7724 this->printDependentLibsHelper(
7725 [](const Elf_Shdr &) {},
7726 [this](StringRef Lib, uint64_t) { W.printString(Lib); });
7729 template <class ELFT> void LLVMELFDumper<ELFT>::printStackSizes() {
7730 ListScope L(W, "StackSizes");
7731 if (this->Obj.getHeader().e_type == ELF::ET_REL)
7732 this->printRelocatableStackSizes([]() {});
7733 else
7734 this->printNonRelocatableStackSizes([]() {});
7737 template <class ELFT>
7738 void LLVMELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
7739 ArrayRef<std::string> FuncNames) {
7740 DictScope D(W, "Entry");
7741 W.printList("Functions", FuncNames);
7742 W.printHex("Size", Size);
7745 template <class ELFT>
7746 void LLVMELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
7747 auto PrintEntry = [&](const Elf_Addr *E) {
7748 W.printHex("Address", Parser.getGotAddress(E));
7749 W.printNumber("Access", Parser.getGotOffset(E));
7750 W.printHex("Initial", *E);
7753 DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT");
7755 W.printHex("Canonical gp value", Parser.getGp());
7757 ListScope RS(W, "Reserved entries");
7759 DictScope D(W, "Entry");
7760 PrintEntry(Parser.getGotLazyResolver());
7761 W.printString("Purpose", StringRef("Lazy resolver"));
7764 if (Parser.getGotModulePointer()) {
7765 DictScope D(W, "Entry");
7766 PrintEntry(Parser.getGotModulePointer());
7767 W.printString("Purpose", StringRef("Module pointer (GNU extension)"));
7771 ListScope LS(W, "Local entries");
7772 for (auto &E : Parser.getLocalEntries()) {
7773 DictScope D(W, "Entry");
7774 PrintEntry(&E);
7778 if (Parser.IsStatic)
7779 return;
7782 ListScope GS(W, "Global entries");
7783 for (auto &E : Parser.getGlobalEntries()) {
7784 DictScope D(W, "Entry");
7786 PrintEntry(&E);
7788 const Elf_Sym &Sym = *Parser.getGotSym(&E);
7789 W.printHex("Value", Sym.st_value);
7790 W.printEnum("Type", Sym.getType(), ArrayRef(ElfSymbolTypes));
7792 const unsigned SymIndex = &Sym - this->dynamic_symbols().begin();
7793 DataRegion<Elf_Word> ShndxTable(
7794 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
7795 printSymbolSection(Sym, SymIndex, ShndxTable);
7797 std::string SymName = this->getFullSymbolName(
7798 Sym, SymIndex, ShndxTable, this->DynamicStringTable, true);
7799 W.printNumber("Name", SymName, Sym.st_name);
7803 W.printNumber("Number of TLS and multi-GOT entries",
7804 uint64_t(Parser.getOtherEntries().size()));
7807 template <class ELFT>
7808 void LLVMELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
7809 auto PrintEntry = [&](const Elf_Addr *E) {
7810 W.printHex("Address", Parser.getPltAddress(E));
7811 W.printHex("Initial", *E);
7814 DictScope GS(W, "PLT GOT");
7817 ListScope RS(W, "Reserved entries");
7819 DictScope D(W, "Entry");
7820 PrintEntry(Parser.getPltLazyResolver());
7821 W.printString("Purpose", StringRef("PLT lazy resolver"));
7824 if (auto E = Parser.getPltModulePointer()) {
7825 DictScope D(W, "Entry");
7826 PrintEntry(E);
7827 W.printString("Purpose", StringRef("Module pointer"));
7831 ListScope LS(W, "Entries");
7832 DataRegion<Elf_Word> ShndxTable(
7833 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
7834 for (auto &E : Parser.getPltEntries()) {
7835 DictScope D(W, "Entry");
7836 PrintEntry(&E);
7838 const Elf_Sym &Sym = *Parser.getPltSym(&E);
7839 W.printHex("Value", Sym.st_value);
7840 W.printEnum("Type", Sym.getType(), ArrayRef(ElfSymbolTypes));
7841 printSymbolSection(Sym, &Sym - this->dynamic_symbols().begin(),
7842 ShndxTable);
7844 const Elf_Sym *FirstSym = cantFail(
7845 this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
7846 std::string SymName = this->getFullSymbolName(
7847 Sym, &Sym - FirstSym, ShndxTable, Parser.getPltStrTable(), true);
7848 W.printNumber("Name", SymName, Sym.st_name);
7853 template <class ELFT> void LLVMELFDumper<ELFT>::printMipsABIFlags() {
7854 const Elf_Mips_ABIFlags<ELFT> *Flags;
7855 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
7856 getMipsAbiFlagsSection(*this)) {
7857 Flags = *SecOrErr;
7858 if (!Flags) {
7859 W.startLine() << "There is no .MIPS.abiflags section in the file.\n";
7860 return;
7862 } else {
7863 this->reportUniqueWarning(SecOrErr.takeError());
7864 return;
7867 raw_ostream &OS = W.getOStream();
7868 DictScope GS(W, "MIPS ABI Flags");
7870 W.printNumber("Version", Flags->version);
7871 W.startLine() << "ISA: ";
7872 if (Flags->isa_rev <= 1)
7873 OS << format("MIPS%u", Flags->isa_level);
7874 else
7875 OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev);
7876 OS << "\n";
7877 W.printEnum("ISA Extension", Flags->isa_ext, ArrayRef(ElfMipsISAExtType));
7878 W.printFlags("ASEs", Flags->ases, ArrayRef(ElfMipsASEFlags));
7879 W.printEnum("FP ABI", Flags->fp_abi, ArrayRef(ElfMipsFpABIType));
7880 W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size));
7881 W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size));
7882 W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size));
7883 W.printFlags("Flags 1", Flags->flags1, ArrayRef(ElfMipsFlags1));
7884 W.printHex("Flags 2", Flags->flags2);
7887 template <class ELFT>
7888 void JSONELFDumper<ELFT>::printFileSummary(StringRef FileStr, ObjectFile &Obj,
7889 ArrayRef<std::string> InputFilenames,
7890 const Archive *A) {
7891 FileScope = std::make_unique<DictScope>(this->W);
7892 DictScope D(this->W, "FileSummary");
7893 this->W.printString("File", FileStr);
7894 this->W.printString("Format", Obj.getFileFormatName());
7895 this->W.printString("Arch", Triple::getArchTypeName(Obj.getArch()));
7896 this->W.printString(
7897 "AddressSize",
7898 std::string(formatv("{0}bit", 8 * Obj.getBytesInAddress())));
7899 this->printLoadName();
7902 template <class ELFT>
7903 void JSONELFDumper<ELFT>::printZeroSymbolOtherField(
7904 const Elf_Sym &Symbol) const {
7905 // We want the JSON format to be uniform, since it is machine readable, so
7906 // always print the `Other` field the same way.
7907 this->printSymbolOtherField(Symbol);
7910 template <class ELFT>
7911 void JSONELFDumper<ELFT>::printDefaultRelRelaReloc(const Relocation<ELFT> &R,
7912 StringRef SymbolName,
7913 StringRef RelocName) {
7914 this->printExpandedRelRelaReloc(R, SymbolName, RelocName);
7917 template <class ELFT>
7918 void JSONELFDumper<ELFT>::printRelocationSectionInfo(const Elf_Shdr &Sec,
7919 StringRef Name,
7920 const unsigned SecNdx) {
7921 DictScope Group(this->W);
7922 this->W.printNumber("SectionIndex", SecNdx);
7923 ListScope D(this->W, "Relocs");
7924 this->printRelocationsHelper(Sec);
7927 template <class ELFT>
7928 std::string JSONELFDumper<ELFT>::getGroupSectionHeaderName() const {
7929 return "GroupSections";
7932 template <class ELFT>
7933 void JSONELFDumper<ELFT>::printSectionGroupMembers(StringRef Name,
7934 uint64_t Idx) const {
7935 DictScope Grp(this->W);
7936 this->W.printString("Name", Name);
7937 this->W.printNumber("Index", Idx);
7940 template <class ELFT> void JSONELFDumper<ELFT>::printEmptyGroupMessage() const {
7941 // JSON output does not need to print anything for empty groups