1 //===- ELFDumper.cpp - ELF-specific dumper --------------------------------===//
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
7 //===----------------------------------------------------------------------===//
10 /// This file implements the ELF-specific dumper for llvm-readobj.
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"
71 #include <system_error>
75 using namespace llvm::object
;
78 #define LLVM_READOBJ_ENUM_CASE(ns, enum) \
82 #define ENUM_ENT(enum, altName) \
83 { #enum, altName, ELF::enum }
85 #define ENUM_ENT_1(enum) \
86 { #enum, #enum, ELF::enum }
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
;
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.
112 /// Size of each entity in the region.
113 uint64_t EntSize
= 0;
115 /// Owner object. Used for error reporting.
117 /// Dumper used for error reporting.
118 const ObjDumper
*Dumper
;
119 /// Error prefix. Used for error reporting to provide more information.
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
);
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
)};
149 if (!Context
.empty())
150 Msg
+= Context
+ " has ";
152 Msg
+= ("invalid " + SizePrintName
+ " (0x" + Twine::utohexstr(Size
) + ")")
154 if (!EntSizePrintName
.empty())
156 (" or " + EntSizePrintName
+ " (0x" + Twine::utohexstr(EntSize
) + ")")
159 Dumper
->reportUniqueWarning(Msg
);
160 return {Start
, Start
};
169 struct GroupSection
{
171 std::string Signature
;
177 std::vector
<GroupMember
> Members
;
189 template <class ELFT
> class Relocation
{
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
) {
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
)
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
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
)
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
>();
257 while (Size
< Table
.size())
258 if (Table
[Size
++].getTag() == DT_NULL
)
261 return Table
.slice(0, Size
);
264 Elf_Sym_Range
dynamic_symbols() const {
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
; }
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;
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
*)>
298 llvm::function_ref
<void(const Elf_Relr
&)> RelrFn
);
300 virtual void printSymtabMessage(const Elf_Shdr
*Symtab
, size_t Offset
,
301 bool NonVisibilityBitsUsed
,
302 bool ExtraSymInfo
) const {};
303 virtual void printSymbol(const Elf_Sym
&Symbol
, unsigned SymIndex
,
304 DataRegion
<Elf_Word
> ShndxTable
,
305 std::optional
<StringRef
> StrTable
, bool IsDynamic
,
306 bool NonVisibilityBitsUsed
,
307 bool ExtraSymInfo
) const = 0;
309 virtual void printMipsABIFlags() = 0;
310 virtual void printMipsGOT(const MipsGOTParser
<ELFT
> &Parser
) = 0;
311 virtual void printMipsPLT(const MipsGOTParser
<ELFT
> &Parser
) = 0;
313 virtual void printMemtag(
314 const ArrayRef
<std::pair
<std::string
, std::string
>> DynamicEntries
,
315 const ArrayRef
<uint8_t> AndroidNoteDesc
,
316 const ArrayRef
<std::pair
<uint64_t, uint64_t>> Descriptors
) = 0;
318 virtual void printHashHistogram(const Elf_Hash
&HashTable
) const;
319 virtual void printGnuHashHistogram(const Elf_GnuHash
&GnuHashTable
) const;
320 virtual void printHashHistogramStats(size_t NBucket
, size_t MaxChain
,
321 size_t TotalSyms
, ArrayRef
<size_t> Count
,
322 bool IsGnu
) const = 0;
324 Expected
<ArrayRef
<Elf_Versym
>>
325 getVersionTable(const Elf_Shdr
&Sec
, ArrayRef
<Elf_Sym
> *SymTab
,
326 StringRef
*StrTab
, const Elf_Shdr
**SymTabSec
) const;
327 StringRef
getPrintableSectionName(const Elf_Shdr
&Sec
) const;
329 std::vector
<GroupSection
> getGroups();
331 // Returns the function symbol index for the given address. Matches the
332 // symbol's section with FunctionSec when specified.
333 // Returns std::nullopt if no function symbol can be found for the address or
334 // in case it is not defined in the specified section.
335 SmallVector
<uint32_t> getSymbolIndexesForFunctionAddress(
336 uint64_t SymValue
, std::optional
<const Elf_Shdr
*> FunctionSec
);
337 bool printFunctionStackSize(uint64_t SymValue
,
338 std::optional
<const Elf_Shdr
*> FunctionSec
,
339 const Elf_Shdr
&StackSizeSec
, DataExtractor Data
,
341 void printStackSize(const Relocation
<ELFT
> &R
, const Elf_Shdr
&RelocSec
,
342 unsigned Ndx
, const Elf_Shdr
*SymTab
,
343 const Elf_Shdr
*FunctionSec
, const Elf_Shdr
&StackSizeSec
,
344 const RelocationResolver
&Resolver
, DataExtractor Data
);
345 virtual void printStackSizeEntry(uint64_t Size
,
346 ArrayRef
<std::string
> FuncNames
) = 0;
348 void printRelocatableStackSizes(std::function
<void()> PrintHeader
);
349 void printNonRelocatableStackSizes(std::function
<void()> PrintHeader
);
351 const object::ELFObjectFile
<ELFT
> &ObjF
;
352 const ELFFile
<ELFT
> &Obj
;
355 Expected
<DynRegionInfo
> createDRI(uint64_t Offset
, uint64_t Size
,
357 if (Offset
+ Size
< Offset
|| Offset
+ Size
> Obj
.getBufSize())
358 return createError("offset (0x" + Twine::utohexstr(Offset
) +
359 ") + size (0x" + Twine::utohexstr(Size
) +
360 ") is greater than the file size (0x" +
361 Twine::utohexstr(Obj
.getBufSize()) + ")");
362 return DynRegionInfo(ObjF
, *this, Obj
.base() + Offset
, Size
, EntSize
);
365 void printAttributes(unsigned, std::unique_ptr
<ELFAttributeParser
>,
367 void printMipsReginfo();
368 void printMipsOptions();
370 std::pair
<const Elf_Phdr
*, const Elf_Shdr
*> findDynamic();
371 void loadDynamicTable();
372 void parseDynamicTable();
374 Expected
<StringRef
> getSymbolVersion(const Elf_Sym
&Sym
,
375 bool &IsDefault
) const;
376 Expected
<SmallVector
<std::optional
<VersionEntry
>, 0> *> getVersionMap() const;
378 DynRegionInfo DynRelRegion
;
379 DynRegionInfo DynRelaRegion
;
380 DynRegionInfo DynRelrRegion
;
381 DynRegionInfo DynPLTRelRegion
;
382 std::optional
<DynRegionInfo
> DynSymRegion
;
383 DynRegionInfo DynSymTabShndxRegion
;
384 DynRegionInfo DynamicTable
;
385 StringRef DynamicStringTable
;
386 const Elf_Hash
*HashTable
= nullptr;
387 const Elf_GnuHash
*GnuHashTable
= nullptr;
388 const Elf_Shdr
*DotSymtabSec
= nullptr;
389 const Elf_Shdr
*DotDynsymSec
= nullptr;
390 const Elf_Shdr
*DotAddrsigSec
= nullptr;
391 DenseMap
<const Elf_Shdr
*, ArrayRef
<Elf_Word
>> ShndxTables
;
392 std::optional
<uint64_t> SONameOffset
;
393 std::optional
<DenseMap
<uint64_t, std::vector
<uint32_t>>> AddressToIndexMap
;
395 const Elf_Shdr
*SymbolVersionSection
= nullptr; // .gnu.version
396 const Elf_Shdr
*SymbolVersionNeedSection
= nullptr; // .gnu.version_r
397 const Elf_Shdr
*SymbolVersionDefSection
= nullptr; // .gnu.version_d
399 std::string
getFullSymbolName(const Elf_Sym
&Symbol
, unsigned SymIndex
,
400 DataRegion
<Elf_Word
> ShndxTable
,
401 std::optional
<StringRef
> StrTable
,
402 bool IsDynamic
) const;
404 getSymbolSectionIndex(const Elf_Sym
&Symbol
, unsigned SymIndex
,
405 DataRegion
<Elf_Word
> ShndxTable
) const;
406 Expected
<StringRef
> getSymbolSectionName(const Elf_Sym
&Symbol
,
407 unsigned SectionIndex
) const;
408 std::string
getStaticSymbolName(uint32_t Index
) const;
409 StringRef
getDynamicString(uint64_t Value
) const;
411 void printSymbolsHelper(bool IsDynamic
, bool ExtraSymInfo
) const;
412 std::string
getDynamicEntry(uint64_t Type
, uint64_t Value
) const;
414 Expected
<RelSymbol
<ELFT
>> getRelocationTarget(const Relocation
<ELFT
> &R
,
415 const Elf_Shdr
*SymTab
) const;
417 ArrayRef
<Elf_Word
> getShndxTable(const Elf_Shdr
*Symtab
) const;
420 mutable SmallVector
<std::optional
<VersionEntry
>, 0> VersionMap
;
423 template <class ELFT
>
424 std::string ELFDumper
<ELFT
>::describe(const Elf_Shdr
&Sec
) const {
425 return ::describe(Obj
, Sec
);
430 template <class ELFT
> struct SymtabLink
{
431 typename
ELFT::SymRange Symbols
;
432 StringRef StringTable
;
433 const typename
ELFT::Shdr
*SymTab
;
436 // Returns the linked symbol table, symbols and associated string table for a
438 template <class ELFT
>
439 Expected
<SymtabLink
<ELFT
>> getLinkAsSymtab(const ELFFile
<ELFT
> &Obj
,
440 const typename
ELFT::Shdr
&Sec
,
441 unsigned ExpectedType
) {
442 Expected
<const typename
ELFT::Shdr
*> SymtabOrErr
=
443 Obj
.getSection(Sec
.sh_link
);
445 return createError("invalid section linked to " + describe(Obj
, Sec
) +
446 ": " + toString(SymtabOrErr
.takeError()));
448 if ((*SymtabOrErr
)->sh_type
!= ExpectedType
)
450 "invalid section linked to " + describe(Obj
, Sec
) + ": expected " +
451 object::getELFSectionTypeName(Obj
.getHeader().e_machine
, ExpectedType
) +
453 object::getELFSectionTypeName(Obj
.getHeader().e_machine
,
454 (*SymtabOrErr
)->sh_type
));
456 Expected
<StringRef
> StrTabOrErr
= Obj
.getLinkAsStrtab(**SymtabOrErr
);
459 "can't get a string table for the symbol table linked to " +
460 describe(Obj
, Sec
) + ": " + toString(StrTabOrErr
.takeError()));
462 Expected
<typename
ELFT::SymRange
> SymsOrErr
= Obj
.symbols(*SymtabOrErr
);
464 return createError("unable to read symbols from the " + describe(Obj
, Sec
) +
465 ": " + toString(SymsOrErr
.takeError()));
467 return SymtabLink
<ELFT
>{*SymsOrErr
, *StrTabOrErr
, *SymtabOrErr
};
472 template <class ELFT
>
473 Expected
<ArrayRef
<typename
ELFT::Versym
>>
474 ELFDumper
<ELFT
>::getVersionTable(const Elf_Shdr
&Sec
, ArrayRef
<Elf_Sym
> *SymTab
,
476 const Elf_Shdr
**SymTabSec
) const {
477 assert((!SymTab
&& !StrTab
&& !SymTabSec
) || (SymTab
&& StrTab
&& SymTabSec
));
478 if (reinterpret_cast<uintptr_t>(Obj
.base() + Sec
.sh_offset
) %
481 return createError("the " + describe(Sec
) + " is misaligned");
483 Expected
<ArrayRef
<Elf_Versym
>> VersionsOrErr
=
484 Obj
.template getSectionContentsAsArray
<Elf_Versym
>(Sec
);
486 return createError("cannot read content of " + describe(Sec
) + ": " +
487 toString(VersionsOrErr
.takeError()));
489 Expected
<SymtabLink
<ELFT
>> SymTabOrErr
=
490 getLinkAsSymtab(Obj
, Sec
, SHT_DYNSYM
);
492 reportUniqueWarning(SymTabOrErr
.takeError());
493 return *VersionsOrErr
;
496 if (SymTabOrErr
->Symbols
.size() != VersionsOrErr
->size())
497 reportUniqueWarning(describe(Sec
) + ": the number of entries (" +
498 Twine(VersionsOrErr
->size()) +
499 ") does not match the number of symbols (" +
500 Twine(SymTabOrErr
->Symbols
.size()) +
501 ") in the symbol table with index " +
505 *SymTab
= SymTabOrErr
->Symbols
;
506 *StrTab
= SymTabOrErr
->StringTable
;
507 *SymTabSec
= SymTabOrErr
->SymTab
;
509 return *VersionsOrErr
;
512 template <class ELFT
>
513 void ELFDumper
<ELFT
>::printSymbolsHelper(bool IsDynamic
,
514 bool ExtraSymInfo
) const {
515 std::optional
<StringRef
> StrTable
;
517 Elf_Sym_Range
Syms(nullptr, nullptr);
518 const Elf_Shdr
*SymtabSec
= IsDynamic
? DotDynsymSec
: DotSymtabSec
;
521 StrTable
= DynamicStringTable
;
522 Syms
= dynamic_symbols();
523 Entries
= Syms
.size();
524 } else if (DotSymtabSec
) {
525 if (Expected
<StringRef
> StrTableOrErr
=
526 Obj
.getStringTableForSymtab(*DotSymtabSec
))
527 StrTable
= *StrTableOrErr
;
530 "unable to get the string table for the SHT_SYMTAB section: " +
531 toString(StrTableOrErr
.takeError()));
533 if (Expected
<Elf_Sym_Range
> SymsOrErr
= Obj
.symbols(DotSymtabSec
))
537 "unable to read symbols from the SHT_SYMTAB section: " +
538 toString(SymsOrErr
.takeError()));
539 Entries
= DotSymtabSec
->getEntityCount();
544 // The st_other field has 2 logical parts. The first two bits hold the symbol
545 // visibility (STV_*) and the remainder hold other platform-specific values.
546 bool NonVisibilityBitsUsed
=
547 llvm::any_of(Syms
, [](const Elf_Sym
&S
) { return S
.st_other
& ~0x3; });
549 DataRegion
<Elf_Word
> ShndxTable
=
550 IsDynamic
? DataRegion
<Elf_Word
>(
551 (const Elf_Word
*)this->DynSymTabShndxRegion
.Addr
,
552 this->getElfObject().getELFFile().end())
553 : DataRegion
<Elf_Word
>(this->getShndxTable(SymtabSec
));
555 printSymtabMessage(SymtabSec
, Entries
, NonVisibilityBitsUsed
, ExtraSymInfo
);
556 for (const Elf_Sym
&Sym
: Syms
)
557 printSymbol(Sym
, &Sym
- Syms
.begin(), ShndxTable
, StrTable
, IsDynamic
,
558 NonVisibilityBitsUsed
, ExtraSymInfo
);
561 template <typename ELFT
> class GNUELFDumper
: public ELFDumper
<ELFT
> {
562 formatted_raw_ostream
&OS
;
565 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT
)
567 GNUELFDumper(const object::ELFObjectFile
<ELFT
> &ObjF
, ScopedPrinter
&Writer
)
568 : ELFDumper
<ELFT
>(ObjF
, Writer
),
569 OS(static_cast<formatted_raw_ostream
&>(Writer
.getOStream())) {
570 assert(&this->W
.getOStream() == &llvm::fouts());
573 void printFileSummary(StringRef FileStr
, ObjectFile
&Obj
,
574 ArrayRef
<std::string
> InputFilenames
,
575 const Archive
*A
) override
;
576 void printFileHeaders() override
;
577 void printGroupSections() override
;
578 void printRelocations() override
;
579 void printSectionHeaders() override
;
580 void printSymbols(bool PrintSymbols
, bool PrintDynamicSymbols
,
581 bool ExtraSymInfo
) override
;
582 void printHashSymbols() override
;
583 void printSectionDetails() override
;
584 void printDependentLibs() override
;
585 void printDynamicTable() override
;
586 void printDynamicRelocations() override
;
587 void printSymtabMessage(const Elf_Shdr
*Symtab
, size_t Offset
,
588 bool NonVisibilityBitsUsed
,
589 bool ExtraSymInfo
) const override
;
590 void printProgramHeaders(bool PrintProgramHeaders
,
591 cl::boolOrDefault PrintSectionMapping
) override
;
592 void printVersionSymbolSection(const Elf_Shdr
*Sec
) override
;
593 void printVersionDefinitionSection(const Elf_Shdr
*Sec
) override
;
594 void printVersionDependencySection(const Elf_Shdr
*Sec
) override
;
595 void printCGProfile() override
;
596 void printBBAddrMaps() override
;
597 void printAddrsig() override
;
598 void printNotes() override
;
599 void printELFLinkerOptions() override
;
600 void printStackSizes() override
;
602 const ArrayRef
<std::pair
<std::string
, std::string
>> DynamicEntries
,
603 const ArrayRef
<uint8_t> AndroidNoteDesc
,
604 const ArrayRef
<std::pair
<uint64_t, uint64_t>> Descriptors
) override
;
605 void printHashHistogramStats(size_t NBucket
, size_t MaxChain
,
606 size_t TotalSyms
, ArrayRef
<size_t> Count
,
607 bool IsGnu
) const override
;
610 void printHashTableSymbols(const Elf_Hash
&HashTable
);
611 void printGnuHashTableSymbols(const Elf_GnuHash
&GnuHashTable
);
617 Field(StringRef S
, unsigned Col
) : Str(std::string(S
)), Column(Col
) {}
618 Field(unsigned Col
) : Column(Col
) {}
621 template <typename T
, typename TEnum
>
622 std::string
printFlags(T Value
, ArrayRef
<EnumEntry
<TEnum
>> EnumValues
,
623 TEnum EnumMask1
= {}, TEnum EnumMask2
= {},
624 TEnum EnumMask3
= {}) const {
626 for (const EnumEntry
<TEnum
> &Flag
: EnumValues
) {
631 if (Flag
.Value
& EnumMask1
)
632 EnumMask
= EnumMask1
;
633 else if (Flag
.Value
& EnumMask2
)
634 EnumMask
= EnumMask2
;
635 else if (Flag
.Value
& EnumMask3
)
636 EnumMask
= EnumMask3
;
637 bool IsEnum
= (Flag
.Value
& EnumMask
) != 0;
638 if ((!IsEnum
&& (Value
& Flag
.Value
) == Flag
.Value
) ||
639 (IsEnum
&& (Value
& EnumMask
) == Flag
.Value
)) {
648 formatted_raw_ostream
&printField(struct Field F
) const {
650 OS
.PadToColumn(F
.Column
);
655 void printHashedSymbol(const Elf_Sym
*Sym
, unsigned SymIndex
,
656 DataRegion
<Elf_Word
> ShndxTable
, StringRef StrTable
,
658 void printRelrReloc(const Elf_Relr
&R
) override
;
659 void printRelRelaReloc(const Relocation
<ELFT
> &R
,
660 const RelSymbol
<ELFT
> &RelSym
) override
;
661 void printSymbol(const Elf_Sym
&Symbol
, unsigned SymIndex
,
662 DataRegion
<Elf_Word
> ShndxTable
,
663 std::optional
<StringRef
> StrTable
, bool IsDynamic
,
664 bool NonVisibilityBitsUsed
,
665 bool ExtraSymInfo
) const override
;
666 void printDynamicRelocHeader(unsigned Type
, StringRef Name
,
667 const DynRegionInfo
&Reg
) override
;
669 std::string
getSymbolSectionNdx(const Elf_Sym
&Symbol
, unsigned SymIndex
,
670 DataRegion
<Elf_Word
> ShndxTable
,
671 bool ExtraSymInfo
= false) const;
672 void printProgramHeaders() override
;
673 void printSectionMapping() override
;
674 void printGNUVersionSectionProlog(const typename
ELFT::Shdr
&Sec
,
675 const Twine
&Label
, unsigned EntriesNum
);
677 void printStackSizeEntry(uint64_t Size
,
678 ArrayRef
<std::string
> FuncNames
) override
;
680 void printMipsGOT(const MipsGOTParser
<ELFT
> &Parser
) override
;
681 void printMipsPLT(const MipsGOTParser
<ELFT
> &Parser
) override
;
682 void printMipsABIFlags() override
;
685 template <typename ELFT
> class LLVMELFDumper
: public ELFDumper
<ELFT
> {
687 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT
)
689 LLVMELFDumper(const object::ELFObjectFile
<ELFT
> &ObjF
, ScopedPrinter
&Writer
)
690 : ELFDumper
<ELFT
>(ObjF
, Writer
), W(Writer
) {}
692 void printFileHeaders() override
;
693 void printGroupSections() override
;
694 void printRelocations() override
;
695 void printSectionHeaders() override
;
696 void printSymbols(bool PrintSymbols
, bool PrintDynamicSymbols
,
697 bool ExtraSymInfo
) override
;
698 void printDependentLibs() override
;
699 void printDynamicTable() override
;
700 void printDynamicRelocations() override
;
701 void printProgramHeaders(bool PrintProgramHeaders
,
702 cl::boolOrDefault PrintSectionMapping
) override
;
703 void printVersionSymbolSection(const Elf_Shdr
*Sec
) override
;
704 void printVersionDefinitionSection(const Elf_Shdr
*Sec
) override
;
705 void printVersionDependencySection(const Elf_Shdr
*Sec
) override
;
706 void printCGProfile() override
;
707 void printBBAddrMaps() override
;
708 void printAddrsig() override
;
709 void printNotes() override
;
710 void printELFLinkerOptions() override
;
711 void printStackSizes() override
;
713 const ArrayRef
<std::pair
<std::string
, std::string
>> DynamicEntries
,
714 const ArrayRef
<uint8_t> AndroidNoteDesc
,
715 const ArrayRef
<std::pair
<uint64_t, uint64_t>> Descriptors
) override
;
716 void printSymbolSection(const Elf_Sym
&Symbol
, unsigned SymIndex
,
717 DataRegion
<Elf_Word
> ShndxTable
) const;
718 void printHashHistogramStats(size_t NBucket
, size_t MaxChain
,
719 size_t TotalSyms
, ArrayRef
<size_t> Count
,
720 bool IsGnu
) const override
;
723 void printRelrReloc(const Elf_Relr
&R
) override
;
724 void printRelRelaReloc(const Relocation
<ELFT
> &R
,
725 const RelSymbol
<ELFT
> &RelSym
) override
;
727 void printSymbol(const Elf_Sym
&Symbol
, unsigned SymIndex
,
728 DataRegion
<Elf_Word
> ShndxTable
,
729 std::optional
<StringRef
> StrTable
, bool IsDynamic
,
730 bool /*NonVisibilityBitsUsed*/,
731 bool /*ExtraSymInfo*/) const override
;
732 void printProgramHeaders() override
;
733 void printSectionMapping() override
{}
734 void printStackSizeEntry(uint64_t Size
,
735 ArrayRef
<std::string
> FuncNames
) override
;
737 void printMipsGOT(const MipsGOTParser
<ELFT
> &Parser
) override
;
738 void printMipsPLT(const MipsGOTParser
<ELFT
> &Parser
) override
;
739 void printMipsABIFlags() override
;
740 virtual void printZeroSymbolOtherField(const Elf_Sym
&Symbol
) const;
743 virtual std::string
getGroupSectionHeaderName() const;
744 void printSymbolOtherField(const Elf_Sym
&Symbol
) const;
745 virtual void printExpandedRelRelaReloc(const Relocation
<ELFT
> &R
,
746 StringRef SymbolName
,
747 StringRef RelocName
);
748 virtual void printDefaultRelRelaReloc(const Relocation
<ELFT
> &R
,
749 StringRef SymbolName
,
750 StringRef RelocName
);
751 virtual void printRelocationSectionInfo(const Elf_Shdr
&Sec
, StringRef Name
,
752 const unsigned SecNdx
);
753 virtual void printSectionGroupMembers(StringRef Name
, uint64_t Idx
) const;
754 virtual void printEmptyGroupMessage() const;
759 // JSONELFDumper shares most of the same implementation as LLVMELFDumper except
760 // it uses a JSONScopedPrinter.
761 template <typename ELFT
> class JSONELFDumper
: public LLVMELFDumper
<ELFT
> {
763 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT
)
765 JSONELFDumper(const object::ELFObjectFile
<ELFT
> &ObjF
, ScopedPrinter
&Writer
)
766 : LLVMELFDumper
<ELFT
>(ObjF
, Writer
) {}
768 std::string
getGroupSectionHeaderName() const override
;
770 void printFileSummary(StringRef FileStr
, ObjectFile
&Obj
,
771 ArrayRef
<std::string
> InputFilenames
,
772 const Archive
*A
) override
;
773 virtual void printZeroSymbolOtherField(const Elf_Sym
&Symbol
) const override
;
775 void printDefaultRelRelaReloc(const Relocation
<ELFT
> &R
,
776 StringRef SymbolName
,
777 StringRef RelocName
) override
;
779 void printRelocationSectionInfo(const Elf_Shdr
&Sec
, StringRef Name
,
780 const unsigned SecNdx
) override
;
782 void printSectionGroupMembers(StringRef Name
, uint64_t Idx
) const override
;
784 void printEmptyGroupMessage() const override
;
787 std::unique_ptr
<DictScope
> FileScope
;
790 } // end anonymous namespace
794 template <class ELFT
>
795 static std::unique_ptr
<ObjDumper
>
796 createELFDumper(const ELFObjectFile
<ELFT
> &Obj
, ScopedPrinter
&Writer
) {
797 if (opts::Output
== opts::GNU
)
798 return std::make_unique
<GNUELFDumper
<ELFT
>>(Obj
, Writer
);
799 else if (opts::Output
== opts::JSON
)
800 return std::make_unique
<JSONELFDumper
<ELFT
>>(Obj
, Writer
);
801 return std::make_unique
<LLVMELFDumper
<ELFT
>>(Obj
, Writer
);
804 std::unique_ptr
<ObjDumper
> createELFDumper(const object::ELFObjectFileBase
&Obj
,
805 ScopedPrinter
&Writer
) {
806 // Little-endian 32-bit
807 if (const ELF32LEObjectFile
*ELFObj
= dyn_cast
<ELF32LEObjectFile
>(&Obj
))
808 return createELFDumper(*ELFObj
, Writer
);
811 if (const ELF32BEObjectFile
*ELFObj
= dyn_cast
<ELF32BEObjectFile
>(&Obj
))
812 return createELFDumper(*ELFObj
, Writer
);
814 // Little-endian 64-bit
815 if (const ELF64LEObjectFile
*ELFObj
= dyn_cast
<ELF64LEObjectFile
>(&Obj
))
816 return createELFDumper(*ELFObj
, Writer
);
819 return createELFDumper(*cast
<ELF64BEObjectFile
>(&Obj
), Writer
);
822 } // end namespace llvm
824 template <class ELFT
>
825 Expected
<SmallVector
<std::optional
<VersionEntry
>, 0> *>
826 ELFDumper
<ELFT
>::getVersionMap() const {
827 // If the VersionMap has already been loaded or if there is no dynamic symtab
828 // or version table, there is nothing to do.
829 if (!VersionMap
.empty() || !DynSymRegion
|| !SymbolVersionSection
)
832 Expected
<SmallVector
<std::optional
<VersionEntry
>, 0>> MapOrErr
=
833 Obj
.loadVersionMap(SymbolVersionNeedSection
, SymbolVersionDefSection
);
835 VersionMap
= *MapOrErr
;
837 return MapOrErr
.takeError();
842 template <typename ELFT
>
843 Expected
<StringRef
> ELFDumper
<ELFT
>::getSymbolVersion(const Elf_Sym
&Sym
,
844 bool &IsDefault
) const {
845 // This is a dynamic symbol. Look in the GNU symbol version table.
846 if (!SymbolVersionSection
) {
852 assert(DynSymRegion
&& "DynSymRegion has not been initialised");
853 // Determine the position in the symbol table of this entry.
854 size_t EntryIndex
= (reinterpret_cast<uintptr_t>(&Sym
) -
855 reinterpret_cast<uintptr_t>(DynSymRegion
->Addr
)) /
858 // Get the corresponding version index entry.
859 Expected
<const Elf_Versym
*> EntryOrErr
=
860 Obj
.template getEntry
<Elf_Versym
>(*SymbolVersionSection
, EntryIndex
);
862 return EntryOrErr
.takeError();
864 unsigned Version
= (*EntryOrErr
)->vs_index
;
865 if (Version
== VER_NDX_LOCAL
|| Version
== VER_NDX_GLOBAL
) {
870 Expected
<SmallVector
<std::optional
<VersionEntry
>, 0> *> MapOrErr
=
873 return MapOrErr
.takeError();
875 return Obj
.getSymbolVersionByIndex(Version
, IsDefault
, **MapOrErr
,
876 Sym
.st_shndx
== ELF::SHN_UNDEF
);
879 template <typename ELFT
>
880 Expected
<RelSymbol
<ELFT
>>
881 ELFDumper
<ELFT
>::getRelocationTarget(const Relocation
<ELFT
> &R
,
882 const Elf_Shdr
*SymTab
) const {
884 return RelSymbol
<ELFT
>(nullptr, "");
886 Expected
<const Elf_Sym
*> SymOrErr
=
887 Obj
.template getEntry
<Elf_Sym
>(*SymTab
, R
.Symbol
);
889 return createError("unable to read an entry with index " + Twine(R
.Symbol
) +
890 " from " + describe(*SymTab
) + ": " +
891 toString(SymOrErr
.takeError()));
892 const Elf_Sym
*Sym
= *SymOrErr
;
894 return RelSymbol
<ELFT
>(nullptr, "");
896 Expected
<StringRef
> StrTableOrErr
= Obj
.getStringTableForSymtab(*SymTab
);
898 return StrTableOrErr
.takeError();
900 const Elf_Sym
*FirstSym
=
901 cantFail(Obj
.template getEntry
<Elf_Sym
>(*SymTab
, 0));
902 std::string SymbolName
=
903 getFullSymbolName(*Sym
, Sym
- FirstSym
, getShndxTable(SymTab
),
904 *StrTableOrErr
, SymTab
->sh_type
== SHT_DYNSYM
);
905 return RelSymbol
<ELFT
>(Sym
, SymbolName
);
908 template <typename ELFT
>
909 ArrayRef
<typename
ELFT::Word
>
910 ELFDumper
<ELFT
>::getShndxTable(const Elf_Shdr
*Symtab
) const {
912 auto It
= ShndxTables
.find(Symtab
);
913 if (It
!= ShndxTables
.end())
919 static std::string
maybeDemangle(StringRef Name
) {
920 return opts::Demangle
? demangle(Name
) : Name
.str();
923 template <typename ELFT
>
924 std::string ELFDumper
<ELFT
>::getStaticSymbolName(uint32_t Index
) const {
925 auto Warn
= [&](Error E
) -> std::string
{
926 reportUniqueWarning("unable to read the name of symbol with index " +
927 Twine(Index
) + ": " + toString(std::move(E
)));
931 Expected
<const typename
ELFT::Sym
*> SymOrErr
=
932 Obj
.getSymbol(DotSymtabSec
, Index
);
934 return Warn(SymOrErr
.takeError());
936 Expected
<StringRef
> StrTabOrErr
= Obj
.getStringTableForSymtab(*DotSymtabSec
);
938 return Warn(StrTabOrErr
.takeError());
940 Expected
<StringRef
> NameOrErr
= (*SymOrErr
)->getName(*StrTabOrErr
);
942 return Warn(NameOrErr
.takeError());
943 return maybeDemangle(*NameOrErr
);
946 template <typename ELFT
>
947 std::string ELFDumper
<ELFT
>::getFullSymbolName(
948 const Elf_Sym
&Symbol
, unsigned SymIndex
, DataRegion
<Elf_Word
> ShndxTable
,
949 std::optional
<StringRef
> StrTable
, bool IsDynamic
) const {
953 std::string SymbolName
;
954 if (Expected
<StringRef
> NameOrErr
= Symbol
.getName(*StrTable
)) {
955 SymbolName
= maybeDemangle(*NameOrErr
);
957 reportUniqueWarning(NameOrErr
.takeError());
961 if (SymbolName
.empty() && Symbol
.getType() == ELF::STT_SECTION
) {
962 Expected
<unsigned> SectionIndex
=
963 getSymbolSectionIndex(Symbol
, SymIndex
, ShndxTable
);
965 reportUniqueWarning(SectionIndex
.takeError());
968 Expected
<StringRef
> NameOrErr
= getSymbolSectionName(Symbol
, *SectionIndex
);
970 reportUniqueWarning(NameOrErr
.takeError());
971 return ("<section " + Twine(*SectionIndex
) + ">").str();
973 return std::string(*NameOrErr
);
980 Expected
<StringRef
> VersionOrErr
= getSymbolVersion(Symbol
, IsDefault
);
982 reportUniqueWarning(VersionOrErr
.takeError());
983 return SymbolName
+ "@<corrupt>";
986 if (!VersionOrErr
->empty()) {
987 SymbolName
+= (IsDefault
? "@@" : "@");
988 SymbolName
+= *VersionOrErr
;
993 template <typename ELFT
>
995 ELFDumper
<ELFT
>::getSymbolSectionIndex(const Elf_Sym
&Symbol
, unsigned SymIndex
,
996 DataRegion
<Elf_Word
> ShndxTable
) const {
997 unsigned Ndx
= Symbol
.st_shndx
;
998 if (Ndx
== SHN_XINDEX
)
999 return object::getExtendedSymbolTableIndex
<ELFT
>(Symbol
, SymIndex
,
1001 if (Ndx
!= SHN_UNDEF
&& Ndx
< SHN_LORESERVE
)
1004 auto CreateErr
= [&](const Twine
&Name
,
1005 std::optional
<unsigned> Offset
= std::nullopt
) {
1008 Desc
= (Name
+ "+0x" + Twine::utohexstr(*Offset
)).str();
1012 "unable to get section index for symbol with st_shndx = 0x" +
1013 Twine::utohexstr(Ndx
) + " (" + Desc
+ ")");
1016 if (Ndx
>= ELF::SHN_LOPROC
&& Ndx
<= ELF::SHN_HIPROC
)
1017 return CreateErr("SHN_LOPROC", Ndx
- ELF::SHN_LOPROC
);
1018 if (Ndx
>= ELF::SHN_LOOS
&& Ndx
<= ELF::SHN_HIOS
)
1019 return CreateErr("SHN_LOOS", Ndx
- ELF::SHN_LOOS
);
1020 if (Ndx
== ELF::SHN_UNDEF
)
1021 return CreateErr("SHN_UNDEF");
1022 if (Ndx
== ELF::SHN_ABS
)
1023 return CreateErr("SHN_ABS");
1024 if (Ndx
== ELF::SHN_COMMON
)
1025 return CreateErr("SHN_COMMON");
1026 return CreateErr("SHN_LORESERVE", Ndx
- SHN_LORESERVE
);
1029 template <typename ELFT
>
1031 ELFDumper
<ELFT
>::getSymbolSectionName(const Elf_Sym
&Symbol
,
1032 unsigned SectionIndex
) const {
1033 Expected
<const Elf_Shdr
*> SecOrErr
= Obj
.getSection(SectionIndex
);
1035 return SecOrErr
.takeError();
1036 return Obj
.getSectionName(**SecOrErr
);
1039 template <class ELFO
>
1040 static const typename
ELFO::Elf_Shdr
*
1041 findNotEmptySectionByAddress(const ELFO
&Obj
, StringRef FileName
,
1043 for (const typename
ELFO::Elf_Shdr
&Shdr
: cantFail(Obj
.sections()))
1044 if (Shdr
.sh_addr
== Addr
&& Shdr
.sh_size
> 0)
1049 const EnumEntry
<unsigned> ElfClass
[] = {
1050 {"None", "none", ELF::ELFCLASSNONE
},
1051 {"32-bit", "ELF32", ELF::ELFCLASS32
},
1052 {"64-bit", "ELF64", ELF::ELFCLASS64
},
1055 const EnumEntry
<unsigned> ElfDataEncoding
[] = {
1056 {"None", "none", ELF::ELFDATANONE
},
1057 {"LittleEndian", "2's complement, little endian", ELF::ELFDATA2LSB
},
1058 {"BigEndian", "2's complement, big endian", ELF::ELFDATA2MSB
},
1061 const EnumEntry
<unsigned> ElfObjectFileType
[] = {
1062 {"None", "NONE (none)", ELF::ET_NONE
},
1063 {"Relocatable", "REL (Relocatable file)", ELF::ET_REL
},
1064 {"Executable", "EXEC (Executable file)", ELF::ET_EXEC
},
1065 {"SharedObject", "DYN (Shared object file)", ELF::ET_DYN
},
1066 {"Core", "CORE (Core file)", ELF::ET_CORE
},
1069 const EnumEntry
<unsigned> ElfOSABI
[] = {
1070 {"SystemV", "UNIX - System V", ELF::ELFOSABI_NONE
},
1071 {"HPUX", "UNIX - HP-UX", ELF::ELFOSABI_HPUX
},
1072 {"NetBSD", "UNIX - NetBSD", ELF::ELFOSABI_NETBSD
},
1073 {"GNU/Linux", "UNIX - GNU", ELF::ELFOSABI_LINUX
},
1074 {"GNU/Hurd", "GNU/Hurd", ELF::ELFOSABI_HURD
},
1075 {"Solaris", "UNIX - Solaris", ELF::ELFOSABI_SOLARIS
},
1076 {"AIX", "UNIX - AIX", ELF::ELFOSABI_AIX
},
1077 {"IRIX", "UNIX - IRIX", ELF::ELFOSABI_IRIX
},
1078 {"FreeBSD", "UNIX - FreeBSD", ELF::ELFOSABI_FREEBSD
},
1079 {"TRU64", "UNIX - TRU64", ELF::ELFOSABI_TRU64
},
1080 {"Modesto", "Novell - Modesto", ELF::ELFOSABI_MODESTO
},
1081 {"OpenBSD", "UNIX - OpenBSD", ELF::ELFOSABI_OPENBSD
},
1082 {"OpenVMS", "VMS - OpenVMS", ELF::ELFOSABI_OPENVMS
},
1083 {"NSK", "HP - Non-Stop Kernel", ELF::ELFOSABI_NSK
},
1084 {"AROS", "AROS", ELF::ELFOSABI_AROS
},
1085 {"FenixOS", "FenixOS", ELF::ELFOSABI_FENIXOS
},
1086 {"CloudABI", "CloudABI", ELF::ELFOSABI_CLOUDABI
},
1087 {"Standalone", "Standalone App", ELF::ELFOSABI_STANDALONE
}
1090 const EnumEntry
<unsigned> AMDGPUElfOSABI
[] = {
1091 {"AMDGPU_HSA", "AMDGPU - HSA", ELF::ELFOSABI_AMDGPU_HSA
},
1092 {"AMDGPU_PAL", "AMDGPU - PAL", ELF::ELFOSABI_AMDGPU_PAL
},
1093 {"AMDGPU_MESA3D", "AMDGPU - MESA3D", ELF::ELFOSABI_AMDGPU_MESA3D
}
1096 const EnumEntry
<unsigned> ARMElfOSABI
[] = {
1097 {"ARM", "ARM", ELF::ELFOSABI_ARM
}
1100 const EnumEntry
<unsigned> C6000ElfOSABI
[] = {
1101 {"C6000_ELFABI", "Bare-metal C6000", ELF::ELFOSABI_C6000_ELFABI
},
1102 {"C6000_LINUX", "Linux C6000", ELF::ELFOSABI_C6000_LINUX
}
1105 const EnumEntry
<unsigned> ElfMachineType
[] = {
1106 ENUM_ENT(EM_NONE
, "None"),
1107 ENUM_ENT(EM_M32
, "WE32100"),
1108 ENUM_ENT(EM_SPARC
, "Sparc"),
1109 ENUM_ENT(EM_386
, "Intel 80386"),
1110 ENUM_ENT(EM_68K
, "MC68000"),
1111 ENUM_ENT(EM_88K
, "MC88000"),
1112 ENUM_ENT(EM_IAMCU
, "EM_IAMCU"),
1113 ENUM_ENT(EM_860
, "Intel 80860"),
1114 ENUM_ENT(EM_MIPS
, "MIPS R3000"),
1115 ENUM_ENT(EM_S370
, "IBM System/370"),
1116 ENUM_ENT(EM_MIPS_RS3_LE
, "MIPS R3000 little-endian"),
1117 ENUM_ENT(EM_PARISC
, "HPPA"),
1118 ENUM_ENT(EM_VPP500
, "Fujitsu VPP500"),
1119 ENUM_ENT(EM_SPARC32PLUS
, "Sparc v8+"),
1120 ENUM_ENT(EM_960
, "Intel 80960"),
1121 ENUM_ENT(EM_PPC
, "PowerPC"),
1122 ENUM_ENT(EM_PPC64
, "PowerPC64"),
1123 ENUM_ENT(EM_S390
, "IBM S/390"),
1124 ENUM_ENT(EM_SPU
, "SPU"),
1125 ENUM_ENT(EM_V800
, "NEC V800 series"),
1126 ENUM_ENT(EM_FR20
, "Fujistsu FR20"),
1127 ENUM_ENT(EM_RH32
, "TRW RH-32"),
1128 ENUM_ENT(EM_RCE
, "Motorola RCE"),
1129 ENUM_ENT(EM_ARM
, "ARM"),
1130 ENUM_ENT(EM_ALPHA
, "EM_ALPHA"),
1131 ENUM_ENT(EM_SH
, "Hitachi SH"),
1132 ENUM_ENT(EM_SPARCV9
, "Sparc v9"),
1133 ENUM_ENT(EM_TRICORE
, "Siemens Tricore"),
1134 ENUM_ENT(EM_ARC
, "ARC"),
1135 ENUM_ENT(EM_H8_300
, "Hitachi H8/300"),
1136 ENUM_ENT(EM_H8_300H
, "Hitachi H8/300H"),
1137 ENUM_ENT(EM_H8S
, "Hitachi H8S"),
1138 ENUM_ENT(EM_H8_500
, "Hitachi H8/500"),
1139 ENUM_ENT(EM_IA_64
, "Intel IA-64"),
1140 ENUM_ENT(EM_MIPS_X
, "Stanford MIPS-X"),
1141 ENUM_ENT(EM_COLDFIRE
, "Motorola Coldfire"),
1142 ENUM_ENT(EM_68HC12
, "Motorola MC68HC12 Microcontroller"),
1143 ENUM_ENT(EM_MMA
, "Fujitsu Multimedia Accelerator"),
1144 ENUM_ENT(EM_PCP
, "Siemens PCP"),
1145 ENUM_ENT(EM_NCPU
, "Sony nCPU embedded RISC processor"),
1146 ENUM_ENT(EM_NDR1
, "Denso NDR1 microprocesspr"),
1147 ENUM_ENT(EM_STARCORE
, "Motorola Star*Core processor"),
1148 ENUM_ENT(EM_ME16
, "Toyota ME16 processor"),
1149 ENUM_ENT(EM_ST100
, "STMicroelectronics ST100 processor"),
1150 ENUM_ENT(EM_TINYJ
, "Advanced Logic Corp. TinyJ embedded processor"),
1151 ENUM_ENT(EM_X86_64
, "Advanced Micro Devices X86-64"),
1152 ENUM_ENT(EM_PDSP
, "Sony DSP processor"),
1153 ENUM_ENT(EM_PDP10
, "Digital Equipment Corp. PDP-10"),
1154 ENUM_ENT(EM_PDP11
, "Digital Equipment Corp. PDP-11"),
1155 ENUM_ENT(EM_FX66
, "Siemens FX66 microcontroller"),
1156 ENUM_ENT(EM_ST9PLUS
, "STMicroelectronics ST9+ 8/16 bit microcontroller"),
1157 ENUM_ENT(EM_ST7
, "STMicroelectronics ST7 8-bit microcontroller"),
1158 ENUM_ENT(EM_68HC16
, "Motorola MC68HC16 Microcontroller"),
1159 ENUM_ENT(EM_68HC11
, "Motorola MC68HC11 Microcontroller"),
1160 ENUM_ENT(EM_68HC08
, "Motorola MC68HC08 Microcontroller"),
1161 ENUM_ENT(EM_68HC05
, "Motorola MC68HC05 Microcontroller"),
1162 ENUM_ENT(EM_SVX
, "Silicon Graphics SVx"),
1163 ENUM_ENT(EM_ST19
, "STMicroelectronics ST19 8-bit microcontroller"),
1164 ENUM_ENT(EM_VAX
, "Digital VAX"),
1165 ENUM_ENT(EM_CRIS
, "Axis Communications 32-bit embedded processor"),
1166 ENUM_ENT(EM_JAVELIN
, "Infineon Technologies 32-bit embedded cpu"),
1167 ENUM_ENT(EM_FIREPATH
, "Element 14 64-bit DSP processor"),
1168 ENUM_ENT(EM_ZSP
, "LSI Logic's 16-bit DSP processor"),
1169 ENUM_ENT(EM_MMIX
, "Donald Knuth's educational 64-bit processor"),
1170 ENUM_ENT(EM_HUANY
, "Harvard Universitys's machine-independent object format"),
1171 ENUM_ENT(EM_PRISM
, "Vitesse Prism"),
1172 ENUM_ENT(EM_AVR
, "Atmel AVR 8-bit microcontroller"),
1173 ENUM_ENT(EM_FR30
, "Fujitsu FR30"),
1174 ENUM_ENT(EM_D10V
, "Mitsubishi D10V"),
1175 ENUM_ENT(EM_D30V
, "Mitsubishi D30V"),
1176 ENUM_ENT(EM_V850
, "NEC v850"),
1177 ENUM_ENT(EM_M32R
, "Renesas M32R (formerly Mitsubishi M32r)"),
1178 ENUM_ENT(EM_MN10300
, "Matsushita MN10300"),
1179 ENUM_ENT(EM_MN10200
, "Matsushita MN10200"),
1180 ENUM_ENT(EM_PJ
, "picoJava"),
1181 ENUM_ENT(EM_OPENRISC
, "OpenRISC 32-bit embedded processor"),
1182 ENUM_ENT(EM_ARC_COMPACT
, "EM_ARC_COMPACT"),
1183 ENUM_ENT(EM_XTENSA
, "Tensilica Xtensa Processor"),
1184 ENUM_ENT(EM_VIDEOCORE
, "Alphamosaic VideoCore processor"),
1185 ENUM_ENT(EM_TMM_GPP
, "Thompson Multimedia General Purpose Processor"),
1186 ENUM_ENT(EM_NS32K
, "National Semiconductor 32000 series"),
1187 ENUM_ENT(EM_TPC
, "Tenor Network TPC processor"),
1188 ENUM_ENT(EM_SNP1K
, "EM_SNP1K"),
1189 ENUM_ENT(EM_ST200
, "STMicroelectronics ST200 microcontroller"),
1190 ENUM_ENT(EM_IP2K
, "Ubicom IP2xxx 8-bit microcontrollers"),
1191 ENUM_ENT(EM_MAX
, "MAX Processor"),
1192 ENUM_ENT(EM_CR
, "National Semiconductor CompactRISC"),
1193 ENUM_ENT(EM_F2MC16
, "Fujitsu F2MC16"),
1194 ENUM_ENT(EM_MSP430
, "Texas Instruments msp430 microcontroller"),
1195 ENUM_ENT(EM_BLACKFIN
, "Analog Devices Blackfin"),
1196 ENUM_ENT(EM_SE_C33
, "S1C33 Family of Seiko Epson processors"),
1197 ENUM_ENT(EM_SEP
, "Sharp embedded microprocessor"),
1198 ENUM_ENT(EM_ARCA
, "Arca RISC microprocessor"),
1199 ENUM_ENT(EM_UNICORE
, "Unicore"),
1200 ENUM_ENT(EM_EXCESS
, "eXcess 16/32/64-bit configurable embedded CPU"),
1201 ENUM_ENT(EM_DXP
, "Icera Semiconductor Inc. Deep Execution Processor"),
1202 ENUM_ENT(EM_ALTERA_NIOS2
, "Altera Nios"),
1203 ENUM_ENT(EM_CRX
, "National Semiconductor CRX microprocessor"),
1204 ENUM_ENT(EM_XGATE
, "Motorola XGATE embedded processor"),
1205 ENUM_ENT(EM_C166
, "Infineon Technologies xc16x"),
1206 ENUM_ENT(EM_M16C
, "Renesas M16C"),
1207 ENUM_ENT(EM_DSPIC30F
, "Microchip Technology dsPIC30F Digital Signal Controller"),
1208 ENUM_ENT(EM_CE
, "Freescale Communication Engine RISC core"),
1209 ENUM_ENT(EM_M32C
, "Renesas M32C"),
1210 ENUM_ENT(EM_TSK3000
, "Altium TSK3000 core"),
1211 ENUM_ENT(EM_RS08
, "Freescale RS08 embedded processor"),
1212 ENUM_ENT(EM_SHARC
, "EM_SHARC"),
1213 ENUM_ENT(EM_ECOG2
, "Cyan Technology eCOG2 microprocessor"),
1214 ENUM_ENT(EM_SCORE7
, "SUNPLUS S+Core"),
1215 ENUM_ENT(EM_DSP24
, "New Japan Radio (NJR) 24-bit DSP Processor"),
1216 ENUM_ENT(EM_VIDEOCORE3
, "Broadcom VideoCore III processor"),
1217 ENUM_ENT(EM_LATTICEMICO32
, "Lattice Mico32"),
1218 ENUM_ENT(EM_SE_C17
, "Seiko Epson C17 family"),
1219 ENUM_ENT(EM_TI_C6000
, "Texas Instruments TMS320C6000 DSP family"),
1220 ENUM_ENT(EM_TI_C2000
, "Texas Instruments TMS320C2000 DSP family"),
1221 ENUM_ENT(EM_TI_C5500
, "Texas Instruments TMS320C55x DSP family"),
1222 ENUM_ENT(EM_MMDSP_PLUS
, "STMicroelectronics 64bit VLIW Data Signal Processor"),
1223 ENUM_ENT(EM_CYPRESS_M8C
, "Cypress M8C microprocessor"),
1224 ENUM_ENT(EM_R32C
, "Renesas R32C series microprocessors"),
1225 ENUM_ENT(EM_TRIMEDIA
, "NXP Semiconductors TriMedia architecture family"),
1226 ENUM_ENT(EM_HEXAGON
, "Qualcomm Hexagon"),
1227 ENUM_ENT(EM_8051
, "Intel 8051 and variants"),
1228 ENUM_ENT(EM_STXP7X
, "STMicroelectronics STxP7x family"),
1229 ENUM_ENT(EM_NDS32
, "Andes Technology compact code size embedded RISC processor family"),
1230 ENUM_ENT(EM_ECOG1
, "Cyan Technology eCOG1 microprocessor"),
1231 // FIXME: Following EM_ECOG1X definitions is dead code since EM_ECOG1X has
1232 // an identical number to EM_ECOG1.
1233 ENUM_ENT(EM_ECOG1X
, "Cyan Technology eCOG1X family"),
1234 ENUM_ENT(EM_MAXQ30
, "Dallas Semiconductor MAXQ30 Core microcontrollers"),
1235 ENUM_ENT(EM_XIMO16
, "New Japan Radio (NJR) 16-bit DSP Processor"),
1236 ENUM_ENT(EM_MANIK
, "M2000 Reconfigurable RISC Microprocessor"),
1237 ENUM_ENT(EM_CRAYNV2
, "Cray Inc. NV2 vector architecture"),
1238 ENUM_ENT(EM_RX
, "Renesas RX"),
1239 ENUM_ENT(EM_METAG
, "Imagination Technologies Meta processor architecture"),
1240 ENUM_ENT(EM_MCST_ELBRUS
, "MCST Elbrus general purpose hardware architecture"),
1241 ENUM_ENT(EM_ECOG16
, "Cyan Technology eCOG16 family"),
1242 ENUM_ENT(EM_CR16
, "National Semiconductor CompactRISC 16-bit processor"),
1243 ENUM_ENT(EM_ETPU
, "Freescale Extended Time Processing Unit"),
1244 ENUM_ENT(EM_SLE9X
, "Infineon Technologies SLE9X core"),
1245 ENUM_ENT(EM_L10M
, "EM_L10M"),
1246 ENUM_ENT(EM_K10M
, "EM_K10M"),
1247 ENUM_ENT(EM_AARCH64
, "AArch64"),
1248 ENUM_ENT(EM_AVR32
, "Atmel Corporation 32-bit microprocessor family"),
1249 ENUM_ENT(EM_STM8
, "STMicroeletronics STM8 8-bit microcontroller"),
1250 ENUM_ENT(EM_TILE64
, "Tilera TILE64 multicore architecture family"),
1251 ENUM_ENT(EM_TILEPRO
, "Tilera TILEPro multicore architecture family"),
1252 ENUM_ENT(EM_MICROBLAZE
, "Xilinx MicroBlaze 32-bit RISC soft processor core"),
1253 ENUM_ENT(EM_CUDA
, "NVIDIA CUDA architecture"),
1254 ENUM_ENT(EM_TILEGX
, "Tilera TILE-Gx multicore architecture family"),
1255 ENUM_ENT(EM_CLOUDSHIELD
, "EM_CLOUDSHIELD"),
1256 ENUM_ENT(EM_COREA_1ST
, "EM_COREA_1ST"),
1257 ENUM_ENT(EM_COREA_2ND
, "EM_COREA_2ND"),
1258 ENUM_ENT(EM_ARC_COMPACT2
, "EM_ARC_COMPACT2"),
1259 ENUM_ENT(EM_OPEN8
, "EM_OPEN8"),
1260 ENUM_ENT(EM_RL78
, "Renesas RL78"),
1261 ENUM_ENT(EM_VIDEOCORE5
, "Broadcom VideoCore V processor"),
1262 ENUM_ENT(EM_78KOR
, "EM_78KOR"),
1263 ENUM_ENT(EM_56800EX
, "EM_56800EX"),
1264 ENUM_ENT(EM_AMDGPU
, "EM_AMDGPU"),
1265 ENUM_ENT(EM_RISCV
, "RISC-V"),
1266 ENUM_ENT(EM_LANAI
, "EM_LANAI"),
1267 ENUM_ENT(EM_BPF
, "EM_BPF"),
1268 ENUM_ENT(EM_VE
, "NEC SX-Aurora Vector Engine"),
1269 ENUM_ENT(EM_LOONGARCH
, "LoongArch"),
1272 const EnumEntry
<unsigned> ElfSymbolBindings
[] = {
1273 {"Local", "LOCAL", ELF::STB_LOCAL
},
1274 {"Global", "GLOBAL", ELF::STB_GLOBAL
},
1275 {"Weak", "WEAK", ELF::STB_WEAK
},
1276 {"Unique", "UNIQUE", ELF::STB_GNU_UNIQUE
}};
1278 const EnumEntry
<unsigned> ElfSymbolVisibilities
[] = {
1279 {"DEFAULT", "DEFAULT", ELF::STV_DEFAULT
},
1280 {"INTERNAL", "INTERNAL", ELF::STV_INTERNAL
},
1281 {"HIDDEN", "HIDDEN", ELF::STV_HIDDEN
},
1282 {"PROTECTED", "PROTECTED", ELF::STV_PROTECTED
}};
1284 const EnumEntry
<unsigned> AMDGPUSymbolTypes
[] = {
1285 { "AMDGPU_HSA_KERNEL", ELF::STT_AMDGPU_HSA_KERNEL
}
1288 static const char *getGroupType(uint32_t Flag
) {
1289 if (Flag
& ELF::GRP_COMDAT
)
1295 const EnumEntry
<unsigned> ElfSectionFlags
[] = {
1296 ENUM_ENT(SHF_WRITE
, "W"),
1297 ENUM_ENT(SHF_ALLOC
, "A"),
1298 ENUM_ENT(SHF_EXECINSTR
, "X"),
1299 ENUM_ENT(SHF_MERGE
, "M"),
1300 ENUM_ENT(SHF_STRINGS
, "S"),
1301 ENUM_ENT(SHF_INFO_LINK
, "I"),
1302 ENUM_ENT(SHF_LINK_ORDER
, "L"),
1303 ENUM_ENT(SHF_OS_NONCONFORMING
, "O"),
1304 ENUM_ENT(SHF_GROUP
, "G"),
1305 ENUM_ENT(SHF_TLS
, "T"),
1306 ENUM_ENT(SHF_COMPRESSED
, "C"),
1307 ENUM_ENT(SHF_EXCLUDE
, "E"),
1310 const EnumEntry
<unsigned> ElfGNUSectionFlags
[] = {
1311 ENUM_ENT(SHF_GNU_RETAIN
, "R")
1314 const EnumEntry
<unsigned> ElfSolarisSectionFlags
[] = {
1315 ENUM_ENT(SHF_SUNW_NODISCARD
, "R")
1318 const EnumEntry
<unsigned> ElfXCoreSectionFlags
[] = {
1319 ENUM_ENT(XCORE_SHF_CP_SECTION
, ""),
1320 ENUM_ENT(XCORE_SHF_DP_SECTION
, "")
1323 const EnumEntry
<unsigned> ElfARMSectionFlags
[] = {
1324 ENUM_ENT(SHF_ARM_PURECODE
, "y")
1327 const EnumEntry
<unsigned> ElfHexagonSectionFlags
[] = {
1328 ENUM_ENT(SHF_HEX_GPREL
, "")
1331 const EnumEntry
<unsigned> ElfMipsSectionFlags
[] = {
1332 ENUM_ENT(SHF_MIPS_NODUPES
, ""),
1333 ENUM_ENT(SHF_MIPS_NAMES
, ""),
1334 ENUM_ENT(SHF_MIPS_LOCAL
, ""),
1335 ENUM_ENT(SHF_MIPS_NOSTRIP
, ""),
1336 ENUM_ENT(SHF_MIPS_GPREL
, ""),
1337 ENUM_ENT(SHF_MIPS_MERGE
, ""),
1338 ENUM_ENT(SHF_MIPS_ADDR
, ""),
1339 ENUM_ENT(SHF_MIPS_STRING
, "")
1342 const EnumEntry
<unsigned> ElfX86_64SectionFlags
[] = {
1343 ENUM_ENT(SHF_X86_64_LARGE
, "l")
1346 static std::vector
<EnumEntry
<unsigned>>
1347 getSectionFlagsForTarget(unsigned EOSAbi
, unsigned EMachine
) {
1348 std::vector
<EnumEntry
<unsigned>> Ret(std::begin(ElfSectionFlags
),
1349 std::end(ElfSectionFlags
));
1351 case ELFOSABI_SOLARIS
:
1352 Ret
.insert(Ret
.end(), std::begin(ElfSolarisSectionFlags
),
1353 std::end(ElfSolarisSectionFlags
));
1356 Ret
.insert(Ret
.end(), std::begin(ElfGNUSectionFlags
),
1357 std::end(ElfGNUSectionFlags
));
1362 Ret
.insert(Ret
.end(), std::begin(ElfARMSectionFlags
),
1363 std::end(ElfARMSectionFlags
));
1366 Ret
.insert(Ret
.end(), std::begin(ElfHexagonSectionFlags
),
1367 std::end(ElfHexagonSectionFlags
));
1370 Ret
.insert(Ret
.end(), std::begin(ElfMipsSectionFlags
),
1371 std::end(ElfMipsSectionFlags
));
1374 Ret
.insert(Ret
.end(), std::begin(ElfX86_64SectionFlags
),
1375 std::end(ElfX86_64SectionFlags
));
1378 Ret
.insert(Ret
.end(), std::begin(ElfXCoreSectionFlags
),
1379 std::end(ElfXCoreSectionFlags
));
1387 static std::string
getGNUFlags(unsigned EOSAbi
, unsigned EMachine
,
1389 // Here we are trying to build the flags string in the same way as GNU does.
1390 // It is not that straightforward. Imagine we have sh_flags == 0x90000000.
1391 // SHF_EXCLUDE ("E") has a value of 0x80000000 and SHF_MASKPROC is 0xf0000000.
1392 // GNU readelf will not print "E" or "Ep" in this case, but will print just
1393 // "p". It only will print "E" when no other processor flag is set.
1395 bool HasUnknownFlag
= false;
1396 bool HasOSFlag
= false;
1397 bool HasProcFlag
= false;
1398 std::vector
<EnumEntry
<unsigned>> FlagsList
=
1399 getSectionFlagsForTarget(EOSAbi
, EMachine
);
1401 // Take the least significant bit as a flag.
1402 uint64_t Flag
= Flags
& -Flags
;
1405 // Find the flag in the known flags list.
1406 auto I
= llvm::find_if(FlagsList
, [=](const EnumEntry
<unsigned> &E
) {
1407 // Flags with empty names are not printed in GNU style output.
1408 return E
.Value
== Flag
&& !E
.AltName
.empty();
1410 if (I
!= FlagsList
.end()) {
1415 // If we did not find a matching regular flag, then we deal with an OS
1416 // specific flag, processor specific flag or an unknown flag.
1417 if (Flag
& ELF::SHF_MASKOS
) {
1419 Flags
&= ~ELF::SHF_MASKOS
;
1420 } else if (Flag
& ELF::SHF_MASKPROC
) {
1422 // Mask off all the processor-specific bits. This removes the SHF_EXCLUDE
1423 // bit if set so that it doesn't also get printed.
1424 Flags
&= ~ELF::SHF_MASKPROC
;
1426 HasUnknownFlag
= true;
1430 // "o", "p" and "x" are printed last.
1440 static StringRef
segmentTypeToString(unsigned Arch
, unsigned Type
) {
1441 // Check potentially overlapped processor-specific program header type.
1444 switch (Type
) { LLVM_READOBJ_ENUM_CASE(ELF
, PT_ARM_EXIDX
); }
1447 case ELF::EM_MIPS_RS3_LE
:
1449 LLVM_READOBJ_ENUM_CASE(ELF
, PT_MIPS_REGINFO
);
1450 LLVM_READOBJ_ENUM_CASE(ELF
, PT_MIPS_RTPROC
);
1451 LLVM_READOBJ_ENUM_CASE(ELF
, PT_MIPS_OPTIONS
);
1452 LLVM_READOBJ_ENUM_CASE(ELF
, PT_MIPS_ABIFLAGS
);
1456 switch (Type
) { LLVM_READOBJ_ENUM_CASE(ELF
, PT_RISCV_ATTRIBUTES
); }
1460 LLVM_READOBJ_ENUM_CASE(ELF
, PT_NULL
);
1461 LLVM_READOBJ_ENUM_CASE(ELF
, PT_LOAD
);
1462 LLVM_READOBJ_ENUM_CASE(ELF
, PT_DYNAMIC
);
1463 LLVM_READOBJ_ENUM_CASE(ELF
, PT_INTERP
);
1464 LLVM_READOBJ_ENUM_CASE(ELF
, PT_NOTE
);
1465 LLVM_READOBJ_ENUM_CASE(ELF
, PT_SHLIB
);
1466 LLVM_READOBJ_ENUM_CASE(ELF
, PT_PHDR
);
1467 LLVM_READOBJ_ENUM_CASE(ELF
, PT_TLS
);
1469 LLVM_READOBJ_ENUM_CASE(ELF
, PT_GNU_EH_FRAME
);
1470 LLVM_READOBJ_ENUM_CASE(ELF
, PT_SUNW_UNWIND
);
1472 LLVM_READOBJ_ENUM_CASE(ELF
, PT_GNU_STACK
);
1473 LLVM_READOBJ_ENUM_CASE(ELF
, PT_GNU_RELRO
);
1474 LLVM_READOBJ_ENUM_CASE(ELF
, PT_GNU_PROPERTY
);
1476 LLVM_READOBJ_ENUM_CASE(ELF
, PT_OPENBSD_MUTABLE
);
1477 LLVM_READOBJ_ENUM_CASE(ELF
, PT_OPENBSD_RANDOMIZE
);
1478 LLVM_READOBJ_ENUM_CASE(ELF
, PT_OPENBSD_WXNEEDED
);
1479 LLVM_READOBJ_ENUM_CASE(ELF
, PT_OPENBSD_NOBTCFI
);
1480 LLVM_READOBJ_ENUM_CASE(ELF
, PT_OPENBSD_BOOTDATA
);
1486 static std::string
getGNUPtType(unsigned Arch
, unsigned Type
) {
1487 StringRef Seg
= segmentTypeToString(Arch
, Type
);
1489 return std::string("<unknown>: ") + to_string(format_hex(Type
, 1));
1491 // E.g. "PT_ARM_EXIDX" -> "EXIDX".
1492 if (Seg
.consume_front("PT_ARM_"))
1495 // E.g. "PT_MIPS_REGINFO" -> "REGINFO".
1496 if (Seg
.consume_front("PT_MIPS_"))
1499 // E.g. "PT_RISCV_ATTRIBUTES"
1500 if (Seg
.consume_front("PT_RISCV_"))
1503 // E.g. "PT_LOAD" -> "LOAD".
1504 assert(Seg
.startswith("PT_"));
1505 return Seg
.drop_front(3).str();
1508 const EnumEntry
<unsigned> ElfSegmentFlags
[] = {
1509 LLVM_READOBJ_ENUM_ENT(ELF
, PF_X
),
1510 LLVM_READOBJ_ENUM_ENT(ELF
, PF_W
),
1511 LLVM_READOBJ_ENUM_ENT(ELF
, PF_R
)
1514 const EnumEntry
<unsigned> ElfHeaderMipsFlags
[] = {
1515 ENUM_ENT(EF_MIPS_NOREORDER
, "noreorder"),
1516 ENUM_ENT(EF_MIPS_PIC
, "pic"),
1517 ENUM_ENT(EF_MIPS_CPIC
, "cpic"),
1518 ENUM_ENT(EF_MIPS_ABI2
, "abi2"),
1519 ENUM_ENT(EF_MIPS_32BITMODE
, "32bitmode"),
1520 ENUM_ENT(EF_MIPS_FP64
, "fp64"),
1521 ENUM_ENT(EF_MIPS_NAN2008
, "nan2008"),
1522 ENUM_ENT(EF_MIPS_ABI_O32
, "o32"),
1523 ENUM_ENT(EF_MIPS_ABI_O64
, "o64"),
1524 ENUM_ENT(EF_MIPS_ABI_EABI32
, "eabi32"),
1525 ENUM_ENT(EF_MIPS_ABI_EABI64
, "eabi64"),
1526 ENUM_ENT(EF_MIPS_MACH_3900
, "3900"),
1527 ENUM_ENT(EF_MIPS_MACH_4010
, "4010"),
1528 ENUM_ENT(EF_MIPS_MACH_4100
, "4100"),
1529 ENUM_ENT(EF_MIPS_MACH_4650
, "4650"),
1530 ENUM_ENT(EF_MIPS_MACH_4120
, "4120"),
1531 ENUM_ENT(EF_MIPS_MACH_4111
, "4111"),
1532 ENUM_ENT(EF_MIPS_MACH_SB1
, "sb1"),
1533 ENUM_ENT(EF_MIPS_MACH_OCTEON
, "octeon"),
1534 ENUM_ENT(EF_MIPS_MACH_XLR
, "xlr"),
1535 ENUM_ENT(EF_MIPS_MACH_OCTEON2
, "octeon2"),
1536 ENUM_ENT(EF_MIPS_MACH_OCTEON3
, "octeon3"),
1537 ENUM_ENT(EF_MIPS_MACH_5400
, "5400"),
1538 ENUM_ENT(EF_MIPS_MACH_5900
, "5900"),
1539 ENUM_ENT(EF_MIPS_MACH_5500
, "5500"),
1540 ENUM_ENT(EF_MIPS_MACH_9000
, "9000"),
1541 ENUM_ENT(EF_MIPS_MACH_LS2E
, "loongson-2e"),
1542 ENUM_ENT(EF_MIPS_MACH_LS2F
, "loongson-2f"),
1543 ENUM_ENT(EF_MIPS_MACH_LS3A
, "loongson-3a"),
1544 ENUM_ENT(EF_MIPS_MICROMIPS
, "micromips"),
1545 ENUM_ENT(EF_MIPS_ARCH_ASE_M16
, "mips16"),
1546 ENUM_ENT(EF_MIPS_ARCH_ASE_MDMX
, "mdmx"),
1547 ENUM_ENT(EF_MIPS_ARCH_1
, "mips1"),
1548 ENUM_ENT(EF_MIPS_ARCH_2
, "mips2"),
1549 ENUM_ENT(EF_MIPS_ARCH_3
, "mips3"),
1550 ENUM_ENT(EF_MIPS_ARCH_4
, "mips4"),
1551 ENUM_ENT(EF_MIPS_ARCH_5
, "mips5"),
1552 ENUM_ENT(EF_MIPS_ARCH_32
, "mips32"),
1553 ENUM_ENT(EF_MIPS_ARCH_64
, "mips64"),
1554 ENUM_ENT(EF_MIPS_ARCH_32R2
, "mips32r2"),
1555 ENUM_ENT(EF_MIPS_ARCH_64R2
, "mips64r2"),
1556 ENUM_ENT(EF_MIPS_ARCH_32R6
, "mips32r6"),
1557 ENUM_ENT(EF_MIPS_ARCH_64R6
, "mips64r6")
1560 const EnumEntry
<unsigned> ElfHeaderAMDGPUFlagsABIVersion3
[] = {
1561 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_NONE
),
1562 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_R600
),
1563 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_R630
),
1564 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_RS880
),
1565 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_RV670
),
1566 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_RV710
),
1567 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_RV730
),
1568 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_RV770
),
1569 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_CEDAR
),
1570 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_CYPRESS
),
1571 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_JUNIPER
),
1572 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_REDWOOD
),
1573 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_SUMO
),
1574 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_BARTS
),
1575 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_CAICOS
),
1576 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_CAYMAN
),
1577 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_TURKS
),
1578 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX600
),
1579 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX601
),
1580 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX602
),
1581 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX700
),
1582 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX701
),
1583 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX702
),
1584 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX703
),
1585 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX704
),
1586 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX705
),
1587 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX801
),
1588 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX802
),
1589 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX803
),
1590 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX805
),
1591 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX810
),
1592 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX900
),
1593 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX902
),
1594 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX904
),
1595 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX906
),
1596 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX908
),
1597 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX909
),
1598 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX90A
),
1599 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX90C
),
1600 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX940
),
1601 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX941
),
1602 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX942
),
1603 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1010
),
1604 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1011
),
1605 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1012
),
1606 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1013
),
1607 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1030
),
1608 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1031
),
1609 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1032
),
1610 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1033
),
1611 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1034
),
1612 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1035
),
1613 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1036
),
1614 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1100
),
1615 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1101
),
1616 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1102
),
1617 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1103
),
1618 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1150
),
1619 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1151
),
1620 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_FEATURE_XNACK_V3
),
1621 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_FEATURE_SRAMECC_V3
)
1624 const EnumEntry
<unsigned> ElfHeaderAMDGPUFlagsABIVersion4
[] = {
1625 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_NONE
),
1626 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_R600
),
1627 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_R630
),
1628 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_RS880
),
1629 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_RV670
),
1630 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_RV710
),
1631 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_RV730
),
1632 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_RV770
),
1633 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_CEDAR
),
1634 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_CYPRESS
),
1635 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_JUNIPER
),
1636 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_REDWOOD
),
1637 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_SUMO
),
1638 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_BARTS
),
1639 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_CAICOS
),
1640 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_CAYMAN
),
1641 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_R600_TURKS
),
1642 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX600
),
1643 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX601
),
1644 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX602
),
1645 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX700
),
1646 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX701
),
1647 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX702
),
1648 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX703
),
1649 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX704
),
1650 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX705
),
1651 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX801
),
1652 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX802
),
1653 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX803
),
1654 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX805
),
1655 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX810
),
1656 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX900
),
1657 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX902
),
1658 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX904
),
1659 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX906
),
1660 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX908
),
1661 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX909
),
1662 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX90A
),
1663 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX90C
),
1664 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX940
),
1665 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX941
),
1666 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX942
),
1667 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1010
),
1668 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1011
),
1669 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1012
),
1670 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1013
),
1671 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1030
),
1672 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1031
),
1673 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1032
),
1674 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1033
),
1675 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1034
),
1676 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1035
),
1677 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1036
),
1678 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1100
),
1679 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1101
),
1680 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1102
),
1681 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1103
),
1682 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1150
),
1683 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_MACH_AMDGCN_GFX1151
),
1684 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_FEATURE_XNACK_ANY_V4
),
1685 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_FEATURE_XNACK_OFF_V4
),
1686 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_FEATURE_XNACK_ON_V4
),
1687 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_FEATURE_SRAMECC_ANY_V4
),
1688 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_FEATURE_SRAMECC_OFF_V4
),
1689 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AMDGPU_FEATURE_SRAMECC_ON_V4
)
1692 const EnumEntry
<unsigned> ElfHeaderRISCVFlags
[] = {
1693 ENUM_ENT(EF_RISCV_RVC
, "RVC"),
1694 ENUM_ENT(EF_RISCV_FLOAT_ABI_SINGLE
, "single-float ABI"),
1695 ENUM_ENT(EF_RISCV_FLOAT_ABI_DOUBLE
, "double-float ABI"),
1696 ENUM_ENT(EF_RISCV_FLOAT_ABI_QUAD
, "quad-float ABI"),
1697 ENUM_ENT(EF_RISCV_RVE
, "RVE"),
1698 ENUM_ENT(EF_RISCV_TSO
, "TSO"),
1701 const EnumEntry
<unsigned> ElfHeaderAVRFlags
[] = {
1702 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_AVR1
),
1703 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_AVR2
),
1704 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_AVR25
),
1705 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_AVR3
),
1706 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_AVR31
),
1707 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_AVR35
),
1708 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_AVR4
),
1709 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_AVR5
),
1710 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_AVR51
),
1711 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_AVR6
),
1712 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_AVRTINY
),
1713 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_XMEGA1
),
1714 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_XMEGA2
),
1715 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_XMEGA3
),
1716 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_XMEGA4
),
1717 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_XMEGA5
),
1718 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_XMEGA6
),
1719 LLVM_READOBJ_ENUM_ENT(ELF
, EF_AVR_ARCH_XMEGA7
),
1720 ENUM_ENT(EF_AVR_LINKRELAX_PREPARED
, "relaxable"),
1723 const EnumEntry
<unsigned> ElfHeaderLoongArchFlags
[] = {
1724 ENUM_ENT(EF_LOONGARCH_ABI_SOFT_FLOAT
, "SOFT-FLOAT"),
1725 ENUM_ENT(EF_LOONGARCH_ABI_SINGLE_FLOAT
, "SINGLE-FLOAT"),
1726 ENUM_ENT(EF_LOONGARCH_ABI_DOUBLE_FLOAT
, "DOUBLE-FLOAT"),
1727 ENUM_ENT(EF_LOONGARCH_OBJABI_V0
, "OBJ-v0"),
1728 ENUM_ENT(EF_LOONGARCH_OBJABI_V1
, "OBJ-v1"),
1731 static const EnumEntry
<unsigned> ElfHeaderXtensaFlags
[] = {
1732 LLVM_READOBJ_ENUM_ENT(ELF
, EF_XTENSA_MACH_NONE
),
1733 LLVM_READOBJ_ENUM_ENT(ELF
, EF_XTENSA_XT_INSN
),
1734 LLVM_READOBJ_ENUM_ENT(ELF
, EF_XTENSA_XT_LIT
)
1737 const EnumEntry
<unsigned> ElfSymOtherFlags
[] = {
1738 LLVM_READOBJ_ENUM_ENT(ELF
, STV_INTERNAL
),
1739 LLVM_READOBJ_ENUM_ENT(ELF
, STV_HIDDEN
),
1740 LLVM_READOBJ_ENUM_ENT(ELF
, STV_PROTECTED
)
1743 const EnumEntry
<unsigned> ElfMipsSymOtherFlags
[] = {
1744 LLVM_READOBJ_ENUM_ENT(ELF
, STO_MIPS_OPTIONAL
),
1745 LLVM_READOBJ_ENUM_ENT(ELF
, STO_MIPS_PLT
),
1746 LLVM_READOBJ_ENUM_ENT(ELF
, STO_MIPS_PIC
),
1747 LLVM_READOBJ_ENUM_ENT(ELF
, STO_MIPS_MICROMIPS
)
1750 const EnumEntry
<unsigned> ElfAArch64SymOtherFlags
[] = {
1751 LLVM_READOBJ_ENUM_ENT(ELF
, STO_AARCH64_VARIANT_PCS
)
1754 const EnumEntry
<unsigned> ElfMips16SymOtherFlags
[] = {
1755 LLVM_READOBJ_ENUM_ENT(ELF
, STO_MIPS_OPTIONAL
),
1756 LLVM_READOBJ_ENUM_ENT(ELF
, STO_MIPS_PLT
),
1757 LLVM_READOBJ_ENUM_ENT(ELF
, STO_MIPS_MIPS16
)
1760 const EnumEntry
<unsigned> ElfRISCVSymOtherFlags
[] = {
1761 LLVM_READOBJ_ENUM_ENT(ELF
, STO_RISCV_VARIANT_CC
)};
1763 static const char *getElfMipsOptionsOdkType(unsigned Odk
) {
1765 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_NULL
);
1766 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_REGINFO
);
1767 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_EXCEPTIONS
);
1768 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_PAD
);
1769 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_HWPATCH
);
1770 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_FILL
);
1771 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_TAGS
);
1772 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_HWAND
);
1773 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_HWOR
);
1774 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_GP_GROUP
);
1775 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_IDENT
);
1776 LLVM_READOBJ_ENUM_CASE(ELF
, ODK_PAGESIZE
);
1782 template <typename ELFT
>
1783 std::pair
<const typename
ELFT::Phdr
*, const typename
ELFT::Shdr
*>
1784 ELFDumper
<ELFT
>::findDynamic() {
1785 // Try to locate the PT_DYNAMIC header.
1786 const Elf_Phdr
*DynamicPhdr
= nullptr;
1787 if (Expected
<ArrayRef
<Elf_Phdr
>> PhdrsOrErr
= Obj
.program_headers()) {
1788 for (const Elf_Phdr
&Phdr
: *PhdrsOrErr
) {
1789 if (Phdr
.p_type
!= ELF::PT_DYNAMIC
)
1791 DynamicPhdr
= &Phdr
;
1795 reportUniqueWarning(
1796 "unable to read program headers to locate the PT_DYNAMIC segment: " +
1797 toString(PhdrsOrErr
.takeError()));
1800 // Try to locate the .dynamic section in the sections header table.
1801 const Elf_Shdr
*DynamicSec
= nullptr;
1802 for (const Elf_Shdr
&Sec
: cantFail(Obj
.sections())) {
1803 if (Sec
.sh_type
!= ELF::SHT_DYNAMIC
)
1809 if (DynamicPhdr
&& ((DynamicPhdr
->p_offset
+ DynamicPhdr
->p_filesz
>
1810 ObjF
.getMemoryBufferRef().getBufferSize()) ||
1811 (DynamicPhdr
->p_offset
+ DynamicPhdr
->p_filesz
<
1812 DynamicPhdr
->p_offset
))) {
1813 reportUniqueWarning(
1814 "PT_DYNAMIC segment offset (0x" +
1815 Twine::utohexstr(DynamicPhdr
->p_offset
) + ") + file size (0x" +
1816 Twine::utohexstr(DynamicPhdr
->p_filesz
) +
1817 ") exceeds the size of the file (0x" +
1818 Twine::utohexstr(ObjF
.getMemoryBufferRef().getBufferSize()) + ")");
1819 // Don't use the broken dynamic header.
1820 DynamicPhdr
= nullptr;
1823 if (DynamicPhdr
&& DynamicSec
) {
1824 if (DynamicSec
->sh_addr
+ DynamicSec
->sh_size
>
1825 DynamicPhdr
->p_vaddr
+ DynamicPhdr
->p_memsz
||
1826 DynamicSec
->sh_addr
< DynamicPhdr
->p_vaddr
)
1827 reportUniqueWarning(describe(*DynamicSec
) +
1828 " is not contained within the "
1829 "PT_DYNAMIC segment");
1831 if (DynamicSec
->sh_addr
!= DynamicPhdr
->p_vaddr
)
1832 reportUniqueWarning(describe(*DynamicSec
) + " is not at the start of "
1833 "PT_DYNAMIC segment");
1836 return std::make_pair(DynamicPhdr
, DynamicSec
);
1839 template <typename ELFT
>
1840 void ELFDumper
<ELFT
>::loadDynamicTable() {
1841 const Elf_Phdr
*DynamicPhdr
;
1842 const Elf_Shdr
*DynamicSec
;
1843 std::tie(DynamicPhdr
, DynamicSec
) = findDynamic();
1844 if (!DynamicPhdr
&& !DynamicSec
)
1847 DynRegionInfo
FromPhdr(ObjF
, *this);
1848 bool IsPhdrTableValid
= false;
1850 // Use cantFail(), because p_offset/p_filesz fields of a PT_DYNAMIC are
1851 // validated in findDynamic() and so createDRI() is not expected to fail.
1852 FromPhdr
= cantFail(createDRI(DynamicPhdr
->p_offset
, DynamicPhdr
->p_filesz
,
1854 FromPhdr
.SizePrintName
= "PT_DYNAMIC size";
1855 FromPhdr
.EntSizePrintName
= "";
1856 IsPhdrTableValid
= !FromPhdr
.template getAsArrayRef
<Elf_Dyn
>().empty();
1859 // Locate the dynamic table described in a section header.
1860 // Ignore sh_entsize and use the expected value for entry size explicitly.
1861 // This allows us to dump dynamic sections with a broken sh_entsize
1863 DynRegionInfo
FromSec(ObjF
, *this);
1864 bool IsSecTableValid
= false;
1866 Expected
<DynRegionInfo
> RegOrErr
=
1867 createDRI(DynamicSec
->sh_offset
, DynamicSec
->sh_size
, sizeof(Elf_Dyn
));
1869 FromSec
= *RegOrErr
;
1870 FromSec
.Context
= describe(*DynamicSec
);
1871 FromSec
.EntSizePrintName
= "";
1872 IsSecTableValid
= !FromSec
.template getAsArrayRef
<Elf_Dyn
>().empty();
1874 reportUniqueWarning("unable to read the dynamic table from " +
1875 describe(*DynamicSec
) + ": " +
1876 toString(RegOrErr
.takeError()));
1880 // When we only have information from one of the SHT_DYNAMIC section header or
1881 // PT_DYNAMIC program header, just use that.
1882 if (!DynamicPhdr
|| !DynamicSec
) {
1883 if ((DynamicPhdr
&& IsPhdrTableValid
) || (DynamicSec
&& IsSecTableValid
)) {
1884 DynamicTable
= DynamicPhdr
? FromPhdr
: FromSec
;
1885 parseDynamicTable();
1887 reportUniqueWarning("no valid dynamic table was found");
1892 // At this point we have tables found from the section header and from the
1893 // dynamic segment. Usually they match, but we have to do sanity checks to
1896 if (FromPhdr
.Addr
!= FromSec
.Addr
)
1897 reportUniqueWarning("SHT_DYNAMIC section header and PT_DYNAMIC "
1898 "program header disagree about "
1899 "the location of the dynamic table");
1901 if (!IsPhdrTableValid
&& !IsSecTableValid
) {
1902 reportUniqueWarning("no valid dynamic table was found");
1906 // Information in the PT_DYNAMIC program header has priority over the
1907 // information in a section header.
1908 if (IsPhdrTableValid
) {
1909 if (!IsSecTableValid
)
1910 reportUniqueWarning(
1911 "SHT_DYNAMIC dynamic table is invalid: PT_DYNAMIC will be used");
1912 DynamicTable
= FromPhdr
;
1914 reportUniqueWarning(
1915 "PT_DYNAMIC dynamic table is invalid: SHT_DYNAMIC will be used");
1916 DynamicTable
= FromSec
;
1919 parseDynamicTable();
1922 template <typename ELFT
>
1923 ELFDumper
<ELFT
>::ELFDumper(const object::ELFObjectFile
<ELFT
> &O
,
1924 ScopedPrinter
&Writer
)
1925 : ObjDumper(Writer
, O
.getFileName()), ObjF(O
), Obj(O
.getELFFile()),
1926 FileName(O
.getFileName()), DynRelRegion(O
, *this),
1927 DynRelaRegion(O
, *this), DynRelrRegion(O
, *this),
1928 DynPLTRelRegion(O
, *this), DynSymTabShndxRegion(O
, *this),
1929 DynamicTable(O
, *this) {
1930 if (!O
.IsContentValid())
1933 typename
ELFT::ShdrRange Sections
= cantFail(Obj
.sections());
1934 for (const Elf_Shdr
&Sec
: Sections
) {
1935 switch (Sec
.sh_type
) {
1936 case ELF::SHT_SYMTAB
:
1938 DotSymtabSec
= &Sec
;
1940 case ELF::SHT_DYNSYM
:
1942 DotDynsymSec
= &Sec
;
1944 if (!DynSymRegion
) {
1945 Expected
<DynRegionInfo
> RegOrErr
=
1946 createDRI(Sec
.sh_offset
, Sec
.sh_size
, Sec
.sh_entsize
);
1948 DynSymRegion
= *RegOrErr
;
1949 DynSymRegion
->Context
= describe(Sec
);
1951 if (Expected
<StringRef
> E
= Obj
.getStringTableForSymtab(Sec
))
1952 DynamicStringTable
= *E
;
1954 reportUniqueWarning("unable to get the string table for the " +
1955 describe(Sec
) + ": " + toString(E
.takeError()));
1957 reportUniqueWarning("unable to read dynamic symbols from " +
1958 describe(Sec
) + ": " +
1959 toString(RegOrErr
.takeError()));
1963 case ELF::SHT_SYMTAB_SHNDX
: {
1964 uint32_t SymtabNdx
= Sec
.sh_link
;
1965 if (SymtabNdx
>= Sections
.size()) {
1966 reportUniqueWarning(
1967 "unable to get the associated symbol table for " + describe(Sec
) +
1968 ": sh_link (" + Twine(SymtabNdx
) +
1969 ") is greater than or equal to the total number of sections (" +
1970 Twine(Sections
.size()) + ")");
1974 if (Expected
<ArrayRef
<Elf_Word
>> ShndxTableOrErr
=
1975 Obj
.getSHNDXTable(Sec
)) {
1976 if (!ShndxTables
.insert({&Sections
[SymtabNdx
], *ShndxTableOrErr
})
1978 reportUniqueWarning(
1979 "multiple SHT_SYMTAB_SHNDX sections are linked to " +
1982 reportUniqueWarning(ShndxTableOrErr
.takeError());
1986 case ELF::SHT_GNU_versym
:
1987 if (!SymbolVersionSection
)
1988 SymbolVersionSection
= &Sec
;
1990 case ELF::SHT_GNU_verdef
:
1991 if (!SymbolVersionDefSection
)
1992 SymbolVersionDefSection
= &Sec
;
1994 case ELF::SHT_GNU_verneed
:
1995 if (!SymbolVersionNeedSection
)
1996 SymbolVersionNeedSection
= &Sec
;
1998 case ELF::SHT_LLVM_ADDRSIG
:
2000 DotAddrsigSec
= &Sec
;
2008 template <typename ELFT
> void ELFDumper
<ELFT
>::parseDynamicTable() {
2009 auto toMappedAddr
= [&](uint64_t Tag
, uint64_t VAddr
) -> const uint8_t * {
2010 auto MappedAddrOrError
= Obj
.toMappedAddr(VAddr
, [&](const Twine
&Msg
) {
2011 this->reportUniqueWarning(Msg
);
2012 return Error::success();
2014 if (!MappedAddrOrError
) {
2015 this->reportUniqueWarning("unable to parse DT_" +
2016 Obj
.getDynamicTagAsString(Tag
) + ": " +
2017 llvm::toString(MappedAddrOrError
.takeError()));
2020 return MappedAddrOrError
.get();
2023 const char *StringTableBegin
= nullptr;
2024 uint64_t StringTableSize
= 0;
2025 std::optional
<DynRegionInfo
> DynSymFromTable
;
2026 for (const Elf_Dyn
&Dyn
: dynamic_table()) {
2027 switch (Dyn
.d_tag
) {
2029 HashTable
= reinterpret_cast<const Elf_Hash
*>(
2030 toMappedAddr(Dyn
.getTag(), Dyn
.getPtr()));
2032 case ELF::DT_GNU_HASH
:
2033 GnuHashTable
= reinterpret_cast<const Elf_GnuHash
*>(
2034 toMappedAddr(Dyn
.getTag(), Dyn
.getPtr()));
2036 case ELF::DT_STRTAB
:
2037 StringTableBegin
= reinterpret_cast<const char *>(
2038 toMappedAddr(Dyn
.getTag(), Dyn
.getPtr()));
2041 StringTableSize
= Dyn
.getVal();
2043 case ELF::DT_SYMTAB
: {
2044 // If we can't map the DT_SYMTAB value to an address (e.g. when there are
2045 // no program headers), we ignore its value.
2046 if (const uint8_t *VA
= toMappedAddr(Dyn
.getTag(), Dyn
.getPtr())) {
2047 DynSymFromTable
.emplace(ObjF
, *this);
2048 DynSymFromTable
->Addr
= VA
;
2049 DynSymFromTable
->EntSize
= sizeof(Elf_Sym
);
2050 DynSymFromTable
->EntSizePrintName
= "";
2054 case ELF::DT_SYMENT
: {
2055 uint64_t Val
= Dyn
.getVal();
2056 if (Val
!= sizeof(Elf_Sym
))
2057 this->reportUniqueWarning("DT_SYMENT value of 0x" +
2058 Twine::utohexstr(Val
) +
2059 " is not the size of a symbol (0x" +
2060 Twine::utohexstr(sizeof(Elf_Sym
)) + ")");
2064 DynRelaRegion
.Addr
= toMappedAddr(Dyn
.getTag(), Dyn
.getPtr());
2066 case ELF::DT_RELASZ
:
2067 DynRelaRegion
.Size
= Dyn
.getVal();
2068 DynRelaRegion
.SizePrintName
= "DT_RELASZ value";
2070 case ELF::DT_RELAENT
:
2071 DynRelaRegion
.EntSize
= Dyn
.getVal();
2072 DynRelaRegion
.EntSizePrintName
= "DT_RELAENT value";
2074 case ELF::DT_SONAME
:
2075 SONameOffset
= Dyn
.getVal();
2078 DynRelRegion
.Addr
= toMappedAddr(Dyn
.getTag(), Dyn
.getPtr());
2081 DynRelRegion
.Size
= Dyn
.getVal();
2082 DynRelRegion
.SizePrintName
= "DT_RELSZ value";
2084 case ELF::DT_RELENT
:
2085 DynRelRegion
.EntSize
= Dyn
.getVal();
2086 DynRelRegion
.EntSizePrintName
= "DT_RELENT value";
2089 case ELF::DT_ANDROID_RELR
:
2090 DynRelrRegion
.Addr
= toMappedAddr(Dyn
.getTag(), Dyn
.getPtr());
2092 case ELF::DT_RELRSZ
:
2093 case ELF::DT_ANDROID_RELRSZ
:
2094 DynRelrRegion
.Size
= Dyn
.getVal();
2095 DynRelrRegion
.SizePrintName
= Dyn
.d_tag
== ELF::DT_RELRSZ
2097 : "DT_ANDROID_RELRSZ value";
2099 case ELF::DT_RELRENT
:
2100 case ELF::DT_ANDROID_RELRENT
:
2101 DynRelrRegion
.EntSize
= Dyn
.getVal();
2102 DynRelrRegion
.EntSizePrintName
= Dyn
.d_tag
== ELF::DT_RELRENT
2103 ? "DT_RELRENT value"
2104 : "DT_ANDROID_RELRENT value";
2106 case ELF::DT_PLTREL
:
2107 if (Dyn
.getVal() == DT_REL
)
2108 DynPLTRelRegion
.EntSize
= sizeof(Elf_Rel
);
2109 else if (Dyn
.getVal() == DT_RELA
)
2110 DynPLTRelRegion
.EntSize
= sizeof(Elf_Rela
);
2112 reportUniqueWarning(Twine("unknown DT_PLTREL value of ") +
2113 Twine((uint64_t)Dyn
.getVal()));
2114 DynPLTRelRegion
.EntSizePrintName
= "PLTREL entry size";
2116 case ELF::DT_JMPREL
:
2117 DynPLTRelRegion
.Addr
= toMappedAddr(Dyn
.getTag(), Dyn
.getPtr());
2119 case ELF::DT_PLTRELSZ
:
2120 DynPLTRelRegion
.Size
= Dyn
.getVal();
2121 DynPLTRelRegion
.SizePrintName
= "DT_PLTRELSZ value";
2123 case ELF::DT_SYMTAB_SHNDX
:
2124 DynSymTabShndxRegion
.Addr
= toMappedAddr(Dyn
.getTag(), Dyn
.getPtr());
2125 DynSymTabShndxRegion
.EntSize
= sizeof(Elf_Word
);
2130 if (StringTableBegin
) {
2131 const uint64_t FileSize
= Obj
.getBufSize();
2132 const uint64_t Offset
= (const uint8_t *)StringTableBegin
- Obj
.base();
2133 if (StringTableSize
> FileSize
- Offset
)
2134 reportUniqueWarning(
2135 "the dynamic string table at 0x" + Twine::utohexstr(Offset
) +
2136 " goes past the end of the file (0x" + Twine::utohexstr(FileSize
) +
2137 ") with DT_STRSZ = 0x" + Twine::utohexstr(StringTableSize
));
2139 DynamicStringTable
= StringRef(StringTableBegin
, StringTableSize
);
2142 const bool IsHashTableSupported
= getHashTableEntSize() == 4;
2144 // Often we find the information about the dynamic symbol table
2145 // location in the SHT_DYNSYM section header. However, the value in
2146 // DT_SYMTAB has priority, because it is used by dynamic loaders to
2147 // locate .dynsym at runtime. The location we find in the section header
2148 // and the location we find here should match.
2149 if (DynSymFromTable
&& DynSymFromTable
->Addr
!= DynSymRegion
->Addr
)
2150 reportUniqueWarning(
2151 createError("SHT_DYNSYM section header and DT_SYMTAB disagree about "
2152 "the location of the dynamic symbol table"));
2154 // According to the ELF gABI: "The number of symbol table entries should
2155 // equal nchain". Check to see if the DT_HASH hash table nchain value
2156 // conflicts with the number of symbols in the dynamic symbol table
2157 // according to the section header.
2158 if (HashTable
&& IsHashTableSupported
) {
2159 if (DynSymRegion
->EntSize
== 0)
2160 reportUniqueWarning("SHT_DYNSYM section has sh_entsize == 0");
2161 else if (HashTable
->nchain
!= DynSymRegion
->Size
/ DynSymRegion
->EntSize
)
2162 reportUniqueWarning(
2163 "hash table nchain (" + Twine(HashTable
->nchain
) +
2164 ") differs from symbol count derived from SHT_DYNSYM section "
2166 Twine(DynSymRegion
->Size
/ DynSymRegion
->EntSize
) + ")");
2170 // Delay the creation of the actual dynamic symbol table until now, so that
2171 // checks can always be made against the section header-based properties,
2172 // without worrying about tag order.
2173 if (DynSymFromTable
) {
2174 if (!DynSymRegion
) {
2175 DynSymRegion
= DynSymFromTable
;
2177 DynSymRegion
->Addr
= DynSymFromTable
->Addr
;
2178 DynSymRegion
->EntSize
= DynSymFromTable
->EntSize
;
2179 DynSymRegion
->EntSizePrintName
= DynSymFromTable
->EntSizePrintName
;
2183 // Derive the dynamic symbol table size from the DT_HASH hash table, if
2185 if (HashTable
&& IsHashTableSupported
&& DynSymRegion
) {
2186 const uint64_t FileSize
= Obj
.getBufSize();
2187 const uint64_t DerivedSize
=
2188 (uint64_t)HashTable
->nchain
* DynSymRegion
->EntSize
;
2189 const uint64_t Offset
= (const uint8_t *)DynSymRegion
->Addr
- Obj
.base();
2190 if (DerivedSize
> FileSize
- Offset
)
2191 reportUniqueWarning(
2192 "the size (0x" + Twine::utohexstr(DerivedSize
) +
2193 ") of the dynamic symbol table at 0x" + Twine::utohexstr(Offset
) +
2194 ", derived from the hash table, goes past the end of the file (0x" +
2195 Twine::utohexstr(FileSize
) + ") and will be ignored");
2197 DynSymRegion
->Size
= HashTable
->nchain
* DynSymRegion
->EntSize
;
2201 template <typename ELFT
> void ELFDumper
<ELFT
>::printVersionInfo() {
2202 // Dump version symbol section.
2203 printVersionSymbolSection(SymbolVersionSection
);
2205 // Dump version definition section.
2206 printVersionDefinitionSection(SymbolVersionDefSection
);
2208 // Dump version dependency section.
2209 printVersionDependencySection(SymbolVersionNeedSection
);
2212 #define LLVM_READOBJ_DT_FLAG_ENT(prefix, enum) \
2213 { #enum, prefix##_##enum }
2215 const EnumEntry
<unsigned> ElfDynamicDTFlags
[] = {
2216 LLVM_READOBJ_DT_FLAG_ENT(DF
, ORIGIN
),
2217 LLVM_READOBJ_DT_FLAG_ENT(DF
, SYMBOLIC
),
2218 LLVM_READOBJ_DT_FLAG_ENT(DF
, TEXTREL
),
2219 LLVM_READOBJ_DT_FLAG_ENT(DF
, BIND_NOW
),
2220 LLVM_READOBJ_DT_FLAG_ENT(DF
, STATIC_TLS
)
2223 const EnumEntry
<unsigned> ElfDynamicDTFlags1
[] = {
2224 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, NOW
),
2225 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, GLOBAL
),
2226 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, GROUP
),
2227 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, NODELETE
),
2228 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, LOADFLTR
),
2229 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, INITFIRST
),
2230 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, NOOPEN
),
2231 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, ORIGIN
),
2232 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, DIRECT
),
2233 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, TRANS
),
2234 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, INTERPOSE
),
2235 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, NODEFLIB
),
2236 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, NODUMP
),
2237 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, CONFALT
),
2238 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, ENDFILTEE
),
2239 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, DISPRELDNE
),
2240 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, DISPRELPND
),
2241 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, NODIRECT
),
2242 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, IGNMULDEF
),
2243 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, NOKSYMS
),
2244 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, NOHDR
),
2245 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, EDITED
),
2246 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, NORELOC
),
2247 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, SYMINTPOSE
),
2248 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, GLOBAUDIT
),
2249 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, SINGLETON
),
2250 LLVM_READOBJ_DT_FLAG_ENT(DF_1
, PIE
),
2253 const EnumEntry
<unsigned> ElfDynamicDTMipsFlags
[] = {
2254 LLVM_READOBJ_DT_FLAG_ENT(RHF
, NONE
),
2255 LLVM_READOBJ_DT_FLAG_ENT(RHF
, QUICKSTART
),
2256 LLVM_READOBJ_DT_FLAG_ENT(RHF
, NOTPOT
),
2257 LLVM_READOBJ_DT_FLAG_ENT(RHS
, NO_LIBRARY_REPLACEMENT
),
2258 LLVM_READOBJ_DT_FLAG_ENT(RHF
, NO_MOVE
),
2259 LLVM_READOBJ_DT_FLAG_ENT(RHF
, SGI_ONLY
),
2260 LLVM_READOBJ_DT_FLAG_ENT(RHF
, GUARANTEE_INIT
),
2261 LLVM_READOBJ_DT_FLAG_ENT(RHF
, DELTA_C_PLUS_PLUS
),
2262 LLVM_READOBJ_DT_FLAG_ENT(RHF
, GUARANTEE_START_INIT
),
2263 LLVM_READOBJ_DT_FLAG_ENT(RHF
, PIXIE
),
2264 LLVM_READOBJ_DT_FLAG_ENT(RHF
, DEFAULT_DELAY_LOAD
),
2265 LLVM_READOBJ_DT_FLAG_ENT(RHF
, REQUICKSTART
),
2266 LLVM_READOBJ_DT_FLAG_ENT(RHF
, REQUICKSTARTED
),
2267 LLVM_READOBJ_DT_FLAG_ENT(RHF
, CORD
),
2268 LLVM_READOBJ_DT_FLAG_ENT(RHF
, NO_UNRES_UNDEF
),
2269 LLVM_READOBJ_DT_FLAG_ENT(RHF
, RLD_ORDER_SAFE
)
2272 #undef LLVM_READOBJ_DT_FLAG_ENT
2274 template <typename T
, typename TFlag
>
2275 void printFlags(T Value
, ArrayRef
<EnumEntry
<TFlag
>> Flags
, raw_ostream
&OS
) {
2276 SmallVector
<EnumEntry
<TFlag
>, 10> SetFlags
;
2277 for (const EnumEntry
<TFlag
> &Flag
: Flags
)
2278 if (Flag
.Value
!= 0 && (Value
& Flag
.Value
) == Flag
.Value
)
2279 SetFlags
.push_back(Flag
);
2281 for (const EnumEntry
<TFlag
> &Flag
: SetFlags
)
2282 OS
<< Flag
.Name
<< " ";
2285 template <class ELFT
>
2286 const typename
ELFT::Shdr
*
2287 ELFDumper
<ELFT
>::findSectionByName(StringRef Name
) const {
2288 for (const Elf_Shdr
&Shdr
: cantFail(Obj
.sections())) {
2289 if (Expected
<StringRef
> NameOrErr
= Obj
.getSectionName(Shdr
)) {
2290 if (*NameOrErr
== Name
)
2293 reportUniqueWarning("unable to read the name of " + describe(Shdr
) +
2294 ": " + toString(NameOrErr
.takeError()));
2300 template <class ELFT
>
2301 std::string ELFDumper
<ELFT
>::getDynamicEntry(uint64_t Type
,
2302 uint64_t Value
) const {
2303 auto FormatHexValue
= [](uint64_t V
) {
2305 raw_string_ostream
OS(Str
);
2306 const char *ConvChar
=
2307 (opts::Output
== opts::GNU
) ? "0x%" PRIx64
: "0x%" PRIX64
;
2308 OS
<< format(ConvChar
, V
);
2312 auto FormatFlags
= [](uint64_t V
,
2313 llvm::ArrayRef
<llvm::EnumEntry
<unsigned int>> Array
) {
2315 raw_string_ostream
OS(Str
);
2316 printFlags(V
, Array
, OS
);
2320 // Handle custom printing of architecture specific tags
2321 switch (Obj
.getHeader().e_machine
) {
2324 case DT_AARCH64_BTI_PLT
:
2325 case DT_AARCH64_PAC_PLT
:
2326 case DT_AARCH64_VARIANT_PCS
:
2327 case DT_AARCH64_MEMTAG_GLOBALSSZ
:
2328 return std::to_string(Value
);
2329 case DT_AARCH64_MEMTAG_MODE
:
2332 return "Synchronous (0)";
2334 return "Asynchronous (1)";
2336 return (Twine("Unknown (") + Twine(Value
) + ")").str();
2338 case DT_AARCH64_MEMTAG_HEAP
:
2339 case DT_AARCH64_MEMTAG_STACK
:
2342 return "Disabled (0)";
2344 return "Enabled (1)";
2346 return (Twine("Unknown (") + Twine(Value
) + ")").str();
2348 case DT_AARCH64_MEMTAG_GLOBALS
:
2349 return (Twine("0x") + utohexstr(Value
, /*LowerCase=*/true)).str();
2356 case DT_HEXAGON_VER
:
2357 return std::to_string(Value
);
2358 case DT_HEXAGON_SYMSZ
:
2359 case DT_HEXAGON_PLT
:
2360 return FormatHexValue(Value
);
2367 case DT_MIPS_RLD_VERSION
:
2368 case DT_MIPS_LOCAL_GOTNO
:
2369 case DT_MIPS_SYMTABNO
:
2370 case DT_MIPS_UNREFEXTNO
:
2371 return std::to_string(Value
);
2372 case DT_MIPS_TIME_STAMP
:
2373 case DT_MIPS_ICHECKSUM
:
2374 case DT_MIPS_IVERSION
:
2375 case DT_MIPS_BASE_ADDRESS
:
2377 case DT_MIPS_CONFLICT
:
2378 case DT_MIPS_LIBLIST
:
2379 case DT_MIPS_CONFLICTNO
:
2380 case DT_MIPS_LIBLISTNO
:
2381 case DT_MIPS_GOTSYM
:
2382 case DT_MIPS_HIPAGENO
:
2383 case DT_MIPS_RLD_MAP
:
2384 case DT_MIPS_DELTA_CLASS
:
2385 case DT_MIPS_DELTA_CLASS_NO
:
2386 case DT_MIPS_DELTA_INSTANCE
:
2387 case DT_MIPS_DELTA_RELOC
:
2388 case DT_MIPS_DELTA_RELOC_NO
:
2389 case DT_MIPS_DELTA_SYM
:
2390 case DT_MIPS_DELTA_SYM_NO
:
2391 case DT_MIPS_DELTA_CLASSSYM
:
2392 case DT_MIPS_DELTA_CLASSSYM_NO
:
2393 case DT_MIPS_CXX_FLAGS
:
2394 case DT_MIPS_PIXIE_INIT
:
2395 case DT_MIPS_SYMBOL_LIB
:
2396 case DT_MIPS_LOCALPAGE_GOTIDX
:
2397 case DT_MIPS_LOCAL_GOTIDX
:
2398 case DT_MIPS_HIDDEN_GOTIDX
:
2399 case DT_MIPS_PROTECTED_GOTIDX
:
2400 case DT_MIPS_OPTIONS
:
2401 case DT_MIPS_INTERFACE
:
2402 case DT_MIPS_DYNSTR_ALIGN
:
2403 case DT_MIPS_INTERFACE_SIZE
:
2404 case DT_MIPS_RLD_TEXT_RESOLVE_ADDR
:
2405 case DT_MIPS_PERF_SUFFIX
:
2406 case DT_MIPS_COMPACT_SIZE
:
2407 case DT_MIPS_GP_VALUE
:
2408 case DT_MIPS_AUX_DYNAMIC
:
2409 case DT_MIPS_PLTGOT
:
2411 case DT_MIPS_RLD_MAP_REL
:
2413 return FormatHexValue(Value
);
2415 return FormatFlags(Value
, ArrayRef(ElfDynamicDTMipsFlags
));
2426 if (Value
== DT_REL
)
2428 if (Value
== DT_RELA
)
2442 case DT_PREINIT_ARRAY
:
2449 return FormatHexValue(Value
);
2454 return std::to_string(Value
);
2462 case DT_INIT_ARRAYSZ
:
2463 case DT_FINI_ARRAYSZ
:
2464 case DT_PREINIT_ARRAYSZ
:
2467 case DT_ANDROID_RELSZ
:
2468 case DT_ANDROID_RELASZ
:
2469 return std::to_string(Value
) + " (bytes)";
2477 const std::map
<uint64_t, const char *> TagNames
= {
2478 {DT_NEEDED
, "Shared library"}, {DT_SONAME
, "Library soname"},
2479 {DT_AUXILIARY
, "Auxiliary library"}, {DT_USED
, "Not needed object"},
2480 {DT_FILTER
, "Filter library"}, {DT_RPATH
, "Library rpath"},
2481 {DT_RUNPATH
, "Library runpath"},
2484 return (Twine(TagNames
.at(Type
)) + ": [" + getDynamicString(Value
) + "]")
2488 return FormatFlags(Value
, ArrayRef(ElfDynamicDTFlags
));
2490 return FormatFlags(Value
, ArrayRef(ElfDynamicDTFlags1
));
2492 return FormatHexValue(Value
);
2496 template <class ELFT
>
2497 StringRef ELFDumper
<ELFT
>::getDynamicString(uint64_t Value
) const {
2498 if (DynamicStringTable
.empty() && !DynamicStringTable
.data()) {
2499 reportUniqueWarning("string table was not found");
2503 auto WarnAndReturn
= [this](const Twine
&Msg
, uint64_t Offset
) {
2504 reportUniqueWarning("string table at offset 0x" + Twine::utohexstr(Offset
) +
2509 const uint64_t FileSize
= Obj
.getBufSize();
2510 const uint64_t Offset
=
2511 (const uint8_t *)DynamicStringTable
.data() - Obj
.base();
2512 if (DynamicStringTable
.size() > FileSize
- Offset
)
2513 return WarnAndReturn(" with size 0x" +
2514 Twine::utohexstr(DynamicStringTable
.size()) +
2515 " goes past the end of the file (0x" +
2516 Twine::utohexstr(FileSize
) + ")",
2519 if (Value
>= DynamicStringTable
.size())
2520 return WarnAndReturn(
2521 ": unable to read the string at 0x" + Twine::utohexstr(Offset
+ Value
) +
2522 ": it goes past the end of the table (0x" +
2523 Twine::utohexstr(Offset
+ DynamicStringTable
.size()) + ")",
2526 if (DynamicStringTable
.back() != '\0')
2527 return WarnAndReturn(": unable to read the string at 0x" +
2528 Twine::utohexstr(Offset
+ Value
) +
2529 ": the string table is not null-terminated",
2532 return DynamicStringTable
.data() + Value
;
2535 template <class ELFT
> void ELFDumper
<ELFT
>::printUnwindInfo() {
2536 DwarfCFIEH::PrinterContext
<ELFT
> Ctx(W
, ObjF
);
2537 Ctx
.printUnwindInformation();
2540 // The namespace is needed to fix the compilation with GCC older than 7.0+.
2542 template <> void ELFDumper
<ELF32LE
>::printUnwindInfo() {
2543 if (Obj
.getHeader().e_machine
== EM_ARM
) {
2544 ARM::EHABI::PrinterContext
<ELF32LE
> Ctx(W
, Obj
, ObjF
.getFileName(),
2546 Ctx
.PrintUnwindInformation();
2548 DwarfCFIEH::PrinterContext
<ELF32LE
> Ctx(W
, ObjF
);
2549 Ctx
.printUnwindInformation();
2553 template <class ELFT
> void ELFDumper
<ELFT
>::printNeededLibraries() {
2554 ListScope
D(W
, "NeededLibraries");
2556 std::vector
<StringRef
> Libs
;
2557 for (const auto &Entry
: dynamic_table())
2558 if (Entry
.d_tag
== ELF::DT_NEEDED
)
2559 Libs
.push_back(getDynamicString(Entry
.d_un
.d_val
));
2563 for (StringRef L
: Libs
)
2564 W
.startLine() << L
<< "\n";
2567 template <class ELFT
>
2568 static Error
checkHashTable(const ELFDumper
<ELFT
> &Dumper
,
2569 const typename
ELFT::Hash
*H
,
2570 bool *IsHeaderValid
= nullptr) {
2571 const ELFFile
<ELFT
> &Obj
= Dumper
.getElfObject().getELFFile();
2572 const uint64_t SecOffset
= (const uint8_t *)H
- Obj
.base();
2573 if (Dumper
.getHashTableEntSize() == 8) {
2574 auto It
= llvm::find_if(ElfMachineType
, [&](const EnumEntry
<unsigned> &E
) {
2575 return E
.Value
== Obj
.getHeader().e_machine
;
2578 *IsHeaderValid
= false;
2579 return createError("the hash table at 0x" + Twine::utohexstr(SecOffset
) +
2580 " is not supported: it contains non-standard 8 "
2581 "byte entries on " +
2582 It
->AltName
+ " platform");
2585 auto MakeError
= [&](const Twine
&Msg
= "") {
2586 return createError("the hash table at offset 0x" +
2587 Twine::utohexstr(SecOffset
) +
2588 " goes past the end of the file (0x" +
2589 Twine::utohexstr(Obj
.getBufSize()) + ")" + Msg
);
2592 // Each SHT_HASH section starts from two 32-bit fields: nbucket and nchain.
2593 const unsigned HeaderSize
= 2 * sizeof(typename
ELFT::Word
);
2596 *IsHeaderValid
= Obj
.getBufSize() - SecOffset
>= HeaderSize
;
2598 if (Obj
.getBufSize() - SecOffset
< HeaderSize
)
2601 if (Obj
.getBufSize() - SecOffset
- HeaderSize
<
2602 ((uint64_t)H
->nbucket
+ H
->nchain
) * sizeof(typename
ELFT::Word
))
2603 return MakeError(", nbucket = " + Twine(H
->nbucket
) +
2604 ", nchain = " + Twine(H
->nchain
));
2605 return Error::success();
2608 template <class ELFT
>
2609 static Error
checkGNUHashTable(const ELFFile
<ELFT
> &Obj
,
2610 const typename
ELFT::GnuHash
*GnuHashTable
,
2611 bool *IsHeaderValid
= nullptr) {
2612 const uint8_t *TableData
= reinterpret_cast<const uint8_t *>(GnuHashTable
);
2613 assert(TableData
>= Obj
.base() && TableData
< Obj
.base() + Obj
.getBufSize() &&
2614 "GnuHashTable must always point to a location inside the file");
2616 uint64_t TableOffset
= TableData
- Obj
.base();
2618 *IsHeaderValid
= TableOffset
+ /*Header size:*/ 16 < Obj
.getBufSize();
2619 if (TableOffset
+ 16 + (uint64_t)GnuHashTable
->nbuckets
* 4 +
2620 (uint64_t)GnuHashTable
->maskwords
* sizeof(typename
ELFT::Off
) >=
2622 return createError("unable to dump the SHT_GNU_HASH "
2624 Twine::utohexstr(TableOffset
) +
2625 ": it goes past the end of the file");
2626 return Error::success();
2629 template <typename ELFT
> void ELFDumper
<ELFT
>::printHashTable() {
2630 DictScope
D(W
, "HashTable");
2635 Error Err
= checkHashTable(*this, HashTable
, &IsHeaderValid
);
2636 if (IsHeaderValid
) {
2637 W
.printNumber("Num Buckets", HashTable
->nbucket
);
2638 W
.printNumber("Num Chains", HashTable
->nchain
);
2642 reportUniqueWarning(std::move(Err
));
2646 W
.printList("Buckets", HashTable
->buckets());
2647 W
.printList("Chains", HashTable
->chains());
2650 template <class ELFT
>
2651 static Expected
<ArrayRef
<typename
ELFT::Word
>>
2652 getGnuHashTableChains(std::optional
<DynRegionInfo
> DynSymRegion
,
2653 const typename
ELFT::GnuHash
*GnuHashTable
) {
2655 return createError("no dynamic symbol table found");
2657 ArrayRef
<typename
ELFT::Sym
> DynSymTable
=
2658 DynSymRegion
->template getAsArrayRef
<typename
ELFT::Sym
>();
2659 size_t NumSyms
= DynSymTable
.size();
2661 return createError("the dynamic symbol table is empty");
2663 if (GnuHashTable
->symndx
< NumSyms
)
2664 return GnuHashTable
->values(NumSyms
);
2666 // A normal empty GNU hash table section produced by linker might have
2667 // symndx set to the number of dynamic symbols + 1 (for the zero symbol)
2668 // and have dummy null values in the Bloom filter and in the buckets
2669 // vector (or no values at all). It happens because the value of symndx is not
2670 // important for dynamic loaders when the GNU hash table is empty. They just
2671 // skip the whole object during symbol lookup. In such cases, the symndx value
2672 // is irrelevant and we should not report a warning.
2673 ArrayRef
<typename
ELFT::Word
> Buckets
= GnuHashTable
->buckets();
2674 if (!llvm::all_of(Buckets
, [](typename
ELFT::Word V
) { return V
== 0; }))
2676 "the first hashed symbol index (" + Twine(GnuHashTable
->symndx
) +
2677 ") is greater than or equal to the number of dynamic symbols (" +
2678 Twine(NumSyms
) + ")");
2679 // There is no way to represent an array of (dynamic symbols count - symndx)
2681 return ArrayRef
<typename
ELFT::Word
>();
2684 template <typename ELFT
>
2685 void ELFDumper
<ELFT
>::printGnuHashTable() {
2686 DictScope
D(W
, "GnuHashTable");
2691 Error Err
= checkGNUHashTable
<ELFT
>(Obj
, GnuHashTable
, &IsHeaderValid
);
2692 if (IsHeaderValid
) {
2693 W
.printNumber("Num Buckets", GnuHashTable
->nbuckets
);
2694 W
.printNumber("First Hashed Symbol Index", GnuHashTable
->symndx
);
2695 W
.printNumber("Num Mask Words", GnuHashTable
->maskwords
);
2696 W
.printNumber("Shift Count", GnuHashTable
->shift2
);
2700 reportUniqueWarning(std::move(Err
));
2704 ArrayRef
<typename
ELFT::Off
> BloomFilter
= GnuHashTable
->filter();
2705 W
.printHexList("Bloom Filter", BloomFilter
);
2707 ArrayRef
<Elf_Word
> Buckets
= GnuHashTable
->buckets();
2708 W
.printList("Buckets", Buckets
);
2710 Expected
<ArrayRef
<Elf_Word
>> Chains
=
2711 getGnuHashTableChains
<ELFT
>(DynSymRegion
, GnuHashTable
);
2713 reportUniqueWarning("unable to dump 'Values' for the SHT_GNU_HASH "
2715 toString(Chains
.takeError()));
2719 W
.printHexList("Values", *Chains
);
2722 template <typename ELFT
> void ELFDumper
<ELFT
>::printHashHistograms() {
2723 // Print histogram for the .hash section.
2724 if (this->HashTable
) {
2725 if (Error E
= checkHashTable
<ELFT
>(*this, this->HashTable
))
2726 this->reportUniqueWarning(std::move(E
));
2728 printHashHistogram(*this->HashTable
);
2731 // Print histogram for the .gnu.hash section.
2732 if (this->GnuHashTable
) {
2733 if (Error E
= checkGNUHashTable
<ELFT
>(this->Obj
, this->GnuHashTable
))
2734 this->reportUniqueWarning(std::move(E
));
2736 printGnuHashHistogram(*this->GnuHashTable
);
2740 template <typename ELFT
>
2741 void ELFDumper
<ELFT
>::printHashHistogram(const Elf_Hash
&HashTable
) const {
2742 size_t NBucket
= HashTable
.nbucket
;
2743 size_t NChain
= HashTable
.nchain
;
2744 ArrayRef
<Elf_Word
> Buckets
= HashTable
.buckets();
2745 ArrayRef
<Elf_Word
> Chains
= HashTable
.chains();
2746 size_t TotalSyms
= 0;
2747 // If hash table is correct, we have at least chains with 0 length.
2748 size_t MaxChain
= 1;
2750 if (NChain
== 0 || NBucket
== 0)
2753 std::vector
<size_t> ChainLen(NBucket
, 0);
2754 // Go over all buckets and note chain lengths of each bucket (total
2755 // unique chain lengths).
2756 for (size_t B
= 0; B
< NBucket
; ++B
) {
2757 BitVector
Visited(NChain
);
2758 for (size_t C
= Buckets
[B
]; C
< NChain
; C
= Chains
[C
]) {
2759 if (C
== ELF::STN_UNDEF
)
2762 this->reportUniqueWarning(
2763 ".hash section is invalid: bucket " + Twine(C
) +
2764 ": a cycle was detected in the linked chain");
2768 if (MaxChain
<= ++ChainLen
[B
])
2771 TotalSyms
+= ChainLen
[B
];
2777 std::vector
<size_t> Count(MaxChain
, 0);
2778 // Count how long is the chain for each bucket.
2779 for (size_t B
= 0; B
< NBucket
; B
++)
2780 ++Count
[ChainLen
[B
]];
2781 // Print Number of buckets with each chain lengths and their cumulative
2782 // coverage of the symbols.
2783 printHashHistogramStats(NBucket
, MaxChain
, TotalSyms
, Count
, /*IsGnu=*/false);
2786 template <class ELFT
>
2787 void ELFDumper
<ELFT
>::printGnuHashHistogram(
2788 const Elf_GnuHash
&GnuHashTable
) const {
2789 Expected
<ArrayRef
<Elf_Word
>> ChainsOrErr
=
2790 getGnuHashTableChains
<ELFT
>(this->DynSymRegion
, &GnuHashTable
);
2792 this->reportUniqueWarning("unable to print the GNU hash table histogram: " +
2793 toString(ChainsOrErr
.takeError()));
2797 ArrayRef
<Elf_Word
> Chains
= *ChainsOrErr
;
2798 size_t Symndx
= GnuHashTable
.symndx
;
2799 size_t TotalSyms
= 0;
2800 size_t MaxChain
= 1;
2802 size_t NBucket
= GnuHashTable
.nbuckets
;
2803 if (Chains
.empty() || NBucket
== 0)
2806 ArrayRef
<Elf_Word
> Buckets
= GnuHashTable
.buckets();
2807 std::vector
<size_t> ChainLen(NBucket
, 0);
2808 for (size_t B
= 0; B
< NBucket
; ++B
) {
2812 for (size_t C
= Buckets
[B
] - Symndx
;
2813 C
< Chains
.size() && (Chains
[C
] & 1) == 0; ++C
)
2814 if (MaxChain
< ++Len
)
2824 std::vector
<size_t> Count(MaxChain
, 0);
2825 for (size_t B
= 0; B
< NBucket
; ++B
)
2826 ++Count
[ChainLen
[B
]];
2827 // Print Number of buckets with each chain lengths and their cumulative
2828 // coverage of the symbols.
2829 printHashHistogramStats(NBucket
, MaxChain
, TotalSyms
, Count
, /*IsGnu=*/true);
2832 template <typename ELFT
> void ELFDumper
<ELFT
>::printLoadName() {
2833 StringRef SOName
= "<Not found>";
2835 SOName
= getDynamicString(*SONameOffset
);
2836 W
.printString("LoadName", SOName
);
2839 template <class ELFT
> void ELFDumper
<ELFT
>::printArchSpecificInfo() {
2840 switch (Obj
.getHeader().e_machine
) {
2843 printAttributes(ELF::SHT_ARM_ATTRIBUTES
,
2844 std::make_unique
<ARMAttributeParser
>(&W
),
2845 llvm::endianness::little
);
2847 reportUniqueWarning("attribute printing not implemented for big-endian "
2852 printAttributes(ELF::SHT_RISCV_ATTRIBUTES
,
2853 std::make_unique
<RISCVAttributeParser
>(&W
),
2854 llvm::endianness::little
);
2856 reportUniqueWarning("attribute printing not implemented for big-endian "
2860 printAttributes(ELF::SHT_MSP430_ATTRIBUTES
,
2861 std::make_unique
<MSP430AttributeParser
>(&W
),
2862 llvm::endianness::little
);
2865 printMipsABIFlags();
2868 MipsGOTParser
<ELFT
> Parser(*this);
2869 if (Error E
= Parser
.findGOT(dynamic_table(), dynamic_symbols()))
2870 reportUniqueWarning(std::move(E
));
2871 else if (!Parser
.isGotEmpty())
2872 printMipsGOT(Parser
);
2874 if (Error E
= Parser
.findPLT(dynamic_table()))
2875 reportUniqueWarning(std::move(E
));
2876 else if (!Parser
.isPltEmpty())
2877 printMipsPLT(Parser
);
2885 template <class ELFT
>
2886 void ELFDumper
<ELFT
>::printAttributes(
2887 unsigned AttrShType
, std::unique_ptr
<ELFAttributeParser
> AttrParser
,
2888 llvm::endianness Endianness
) {
2889 assert((AttrShType
!= ELF::SHT_NULL
) && AttrParser
&&
2890 "Incomplete ELF attribute implementation");
2891 DictScope
BA(W
, "BuildAttributes");
2892 for (const Elf_Shdr
&Sec
: cantFail(Obj
.sections())) {
2893 if (Sec
.sh_type
!= AttrShType
)
2896 ArrayRef
<uint8_t> Contents
;
2897 if (Expected
<ArrayRef
<uint8_t>> ContentOrErr
=
2898 Obj
.getSectionContents(Sec
)) {
2899 Contents
= *ContentOrErr
;
2900 if (Contents
.empty()) {
2901 reportUniqueWarning("the " + describe(Sec
) + " is empty");
2905 reportUniqueWarning("unable to read the content of the " + describe(Sec
) +
2906 ": " + toString(ContentOrErr
.takeError()));
2910 W
.printHex("FormatVersion", Contents
[0]);
2912 if (Error E
= AttrParser
->parse(Contents
, Endianness
))
2913 reportUniqueWarning("unable to dump attributes from the " +
2914 describe(Sec
) + ": " + toString(std::move(E
)));
2920 template <class ELFT
> class MipsGOTParser
{
2922 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT
)
2923 using Entry
= typename
ELFT::Addr
;
2924 using Entries
= ArrayRef
<Entry
>;
2926 const bool IsStatic
;
2927 const ELFFile
<ELFT
> &Obj
;
2928 const ELFDumper
<ELFT
> &Dumper
;
2930 MipsGOTParser(const ELFDumper
<ELFT
> &D
);
2931 Error
findGOT(Elf_Dyn_Range DynTable
, Elf_Sym_Range DynSyms
);
2932 Error
findPLT(Elf_Dyn_Range DynTable
);
2934 bool isGotEmpty() const { return GotEntries
.empty(); }
2935 bool isPltEmpty() const { return PltEntries
.empty(); }
2937 uint64_t getGp() const;
2939 const Entry
*getGotLazyResolver() const;
2940 const Entry
*getGotModulePointer() const;
2941 const Entry
*getPltLazyResolver() const;
2942 const Entry
*getPltModulePointer() const;
2944 Entries
getLocalEntries() const;
2945 Entries
getGlobalEntries() const;
2946 Entries
getOtherEntries() const;
2947 Entries
getPltEntries() const;
2949 uint64_t getGotAddress(const Entry
* E
) const;
2950 int64_t getGotOffset(const Entry
* E
) const;
2951 const Elf_Sym
*getGotSym(const Entry
*E
) const;
2953 uint64_t getPltAddress(const Entry
* E
) const;
2954 const Elf_Sym
*getPltSym(const Entry
*E
) const;
2956 StringRef
getPltStrTable() const { return PltStrTable
; }
2957 const Elf_Shdr
*getPltSymTable() const { return PltSymTable
; }
2960 const Elf_Shdr
*GotSec
;
2964 const Elf_Shdr
*PltSec
;
2965 const Elf_Shdr
*PltRelSec
;
2966 const Elf_Shdr
*PltSymTable
;
2969 Elf_Sym_Range GotDynSyms
;
2970 StringRef PltStrTable
;
2976 } // end anonymous namespace
2978 template <class ELFT
>
2979 MipsGOTParser
<ELFT
>::MipsGOTParser(const ELFDumper
<ELFT
> &D
)
2980 : IsStatic(D
.dynamic_table().empty()), Obj(D
.getElfObject().getELFFile()),
2981 Dumper(D
), GotSec(nullptr), LocalNum(0), GlobalNum(0), PltSec(nullptr),
2982 PltRelSec(nullptr), PltSymTable(nullptr),
2983 FileName(D
.getElfObject().getFileName()) {}
2985 template <class ELFT
>
2986 Error MipsGOTParser
<ELFT
>::findGOT(Elf_Dyn_Range DynTable
,
2987 Elf_Sym_Range DynSyms
) {
2988 // See "Global Offset Table" in Chapter 5 in the following document
2989 // for detailed GOT description.
2990 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
2992 // Find static GOT secton.
2994 GotSec
= Dumper
.findSectionByName(".got");
2996 return Error::success();
2998 ArrayRef
<uint8_t> Content
=
2999 unwrapOrError(FileName
, Obj
.getSectionContents(*GotSec
));
3000 GotEntries
= Entries(reinterpret_cast<const Entry
*>(Content
.data()),
3001 Content
.size() / sizeof(Entry
));
3002 LocalNum
= GotEntries
.size();
3003 return Error::success();
3006 // Lookup dynamic table tags which define the GOT layout.
3007 std::optional
<uint64_t> DtPltGot
;
3008 std::optional
<uint64_t> DtLocalGotNum
;
3009 std::optional
<uint64_t> DtGotSym
;
3010 for (const auto &Entry
: DynTable
) {
3011 switch (Entry
.getTag()) {
3012 case ELF::DT_PLTGOT
:
3013 DtPltGot
= Entry
.getVal();
3015 case ELF::DT_MIPS_LOCAL_GOTNO
:
3016 DtLocalGotNum
= Entry
.getVal();
3018 case ELF::DT_MIPS_GOTSYM
:
3019 DtGotSym
= Entry
.getVal();
3024 if (!DtPltGot
&& !DtLocalGotNum
&& !DtGotSym
)
3025 return Error::success();
3028 return createError("cannot find PLTGOT dynamic tag");
3030 return createError("cannot find MIPS_LOCAL_GOTNO dynamic tag");
3032 return createError("cannot find MIPS_GOTSYM dynamic tag");
3034 size_t DynSymTotal
= DynSyms
.size();
3035 if (*DtGotSym
> DynSymTotal
)
3036 return createError("DT_MIPS_GOTSYM value (" + Twine(*DtGotSym
) +
3037 ") exceeds the number of dynamic symbols (" +
3038 Twine(DynSymTotal
) + ")");
3040 GotSec
= findNotEmptySectionByAddress(Obj
, FileName
, *DtPltGot
);
3042 return createError("there is no non-empty GOT section at 0x" +
3043 Twine::utohexstr(*DtPltGot
));
3045 LocalNum
= *DtLocalGotNum
;
3046 GlobalNum
= DynSymTotal
- *DtGotSym
;
3048 ArrayRef
<uint8_t> Content
=
3049 unwrapOrError(FileName
, Obj
.getSectionContents(*GotSec
));
3050 GotEntries
= Entries(reinterpret_cast<const Entry
*>(Content
.data()),
3051 Content
.size() / sizeof(Entry
));
3052 GotDynSyms
= DynSyms
.drop_front(*DtGotSym
);
3054 return Error::success();
3057 template <class ELFT
>
3058 Error MipsGOTParser
<ELFT
>::findPLT(Elf_Dyn_Range DynTable
) {
3059 // Lookup dynamic table tags which define the PLT layout.
3060 std::optional
<uint64_t> DtMipsPltGot
;
3061 std::optional
<uint64_t> DtJmpRel
;
3062 for (const auto &Entry
: DynTable
) {
3063 switch (Entry
.getTag()) {
3064 case ELF::DT_MIPS_PLTGOT
:
3065 DtMipsPltGot
= Entry
.getVal();
3067 case ELF::DT_JMPREL
:
3068 DtJmpRel
= Entry
.getVal();
3073 if (!DtMipsPltGot
&& !DtJmpRel
)
3074 return Error::success();
3076 // Find PLT section.
3078 return createError("cannot find MIPS_PLTGOT dynamic tag");
3080 return createError("cannot find JMPREL dynamic tag");
3082 PltSec
= findNotEmptySectionByAddress(Obj
, FileName
, *DtMipsPltGot
);
3084 return createError("there is no non-empty PLTGOT section at 0x" +
3085 Twine::utohexstr(*DtMipsPltGot
));
3087 PltRelSec
= findNotEmptySectionByAddress(Obj
, FileName
, *DtJmpRel
);
3089 return createError("there is no non-empty RELPLT section at 0x" +
3090 Twine::utohexstr(*DtJmpRel
));
3092 if (Expected
<ArrayRef
<uint8_t>> PltContentOrErr
=
3093 Obj
.getSectionContents(*PltSec
))
3095 Entries(reinterpret_cast<const Entry
*>(PltContentOrErr
->data()),
3096 PltContentOrErr
->size() / sizeof(Entry
));
3098 return createError("unable to read PLTGOT section content: " +
3099 toString(PltContentOrErr
.takeError()));
3101 if (Expected
<const Elf_Shdr
*> PltSymTableOrErr
=
3102 Obj
.getSection(PltRelSec
->sh_link
))
3103 PltSymTable
= *PltSymTableOrErr
;
3105 return createError("unable to get a symbol table linked to the " +
3106 describe(Obj
, *PltRelSec
) + ": " +
3107 toString(PltSymTableOrErr
.takeError()));
3109 if (Expected
<StringRef
> StrTabOrErr
=
3110 Obj
.getStringTableForSymtab(*PltSymTable
))
3111 PltStrTable
= *StrTabOrErr
;
3113 return createError("unable to get a string table for the " +
3114 describe(Obj
, *PltSymTable
) + ": " +
3115 toString(StrTabOrErr
.takeError()));
3117 return Error::success();
3120 template <class ELFT
> uint64_t MipsGOTParser
<ELFT
>::getGp() const {
3121 return GotSec
->sh_addr
+ 0x7ff0;
3124 template <class ELFT
>
3125 const typename MipsGOTParser
<ELFT
>::Entry
*
3126 MipsGOTParser
<ELFT
>::getGotLazyResolver() const {
3127 return LocalNum
> 0 ? &GotEntries
[0] : nullptr;
3130 template <class ELFT
>
3131 const typename MipsGOTParser
<ELFT
>::Entry
*
3132 MipsGOTParser
<ELFT
>::getGotModulePointer() const {
3135 const Entry
&E
= GotEntries
[1];
3136 if ((E
>> (sizeof(Entry
) * 8 - 1)) == 0)
3141 template <class ELFT
>
3142 typename MipsGOTParser
<ELFT
>::Entries
3143 MipsGOTParser
<ELFT
>::getLocalEntries() const {
3144 size_t Skip
= getGotModulePointer() ? 2 : 1;
3145 if (LocalNum
- Skip
<= 0)
3147 return GotEntries
.slice(Skip
, LocalNum
- Skip
);
3150 template <class ELFT
>
3151 typename MipsGOTParser
<ELFT
>::Entries
3152 MipsGOTParser
<ELFT
>::getGlobalEntries() const {
3155 return GotEntries
.slice(LocalNum
, GlobalNum
);
3158 template <class ELFT
>
3159 typename MipsGOTParser
<ELFT
>::Entries
3160 MipsGOTParser
<ELFT
>::getOtherEntries() const {
3161 size_t OtherNum
= GotEntries
.size() - LocalNum
- GlobalNum
;
3164 return GotEntries
.slice(LocalNum
+ GlobalNum
, OtherNum
);
3167 template <class ELFT
>
3168 uint64_t MipsGOTParser
<ELFT
>::getGotAddress(const Entry
*E
) const {
3169 int64_t Offset
= std::distance(GotEntries
.data(), E
) * sizeof(Entry
);
3170 return GotSec
->sh_addr
+ Offset
;
3173 template <class ELFT
>
3174 int64_t MipsGOTParser
<ELFT
>::getGotOffset(const Entry
*E
) const {
3175 int64_t Offset
= std::distance(GotEntries
.data(), E
) * sizeof(Entry
);
3176 return Offset
- 0x7ff0;
3179 template <class ELFT
>
3180 const typename MipsGOTParser
<ELFT
>::Elf_Sym
*
3181 MipsGOTParser
<ELFT
>::getGotSym(const Entry
*E
) const {
3182 int64_t Offset
= std::distance(GotEntries
.data(), E
);
3183 return &GotDynSyms
[Offset
- LocalNum
];
3186 template <class ELFT
>
3187 const typename MipsGOTParser
<ELFT
>::Entry
*
3188 MipsGOTParser
<ELFT
>::getPltLazyResolver() const {
3189 return PltEntries
.empty() ? nullptr : &PltEntries
[0];
3192 template <class ELFT
>
3193 const typename MipsGOTParser
<ELFT
>::Entry
*
3194 MipsGOTParser
<ELFT
>::getPltModulePointer() const {
3195 return PltEntries
.size() < 2 ? nullptr : &PltEntries
[1];
3198 template <class ELFT
>
3199 typename MipsGOTParser
<ELFT
>::Entries
3200 MipsGOTParser
<ELFT
>::getPltEntries() const {
3201 if (PltEntries
.size() <= 2)
3203 return PltEntries
.slice(2, PltEntries
.size() - 2);
3206 template <class ELFT
>
3207 uint64_t MipsGOTParser
<ELFT
>::getPltAddress(const Entry
*E
) const {
3208 int64_t Offset
= std::distance(PltEntries
.data(), E
) * sizeof(Entry
);
3209 return PltSec
->sh_addr
+ Offset
;
3212 template <class ELFT
>
3213 const typename MipsGOTParser
<ELFT
>::Elf_Sym
*
3214 MipsGOTParser
<ELFT
>::getPltSym(const Entry
*E
) const {
3215 int64_t Offset
= std::distance(getPltEntries().data(), E
);
3216 if (PltRelSec
->sh_type
== ELF::SHT_REL
) {
3217 Elf_Rel_Range Rels
= unwrapOrError(FileName
, Obj
.rels(*PltRelSec
));
3218 return unwrapOrError(FileName
,
3219 Obj
.getRelocationSymbol(Rels
[Offset
], PltSymTable
));
3221 Elf_Rela_Range Rels
= unwrapOrError(FileName
, Obj
.relas(*PltRelSec
));
3222 return unwrapOrError(FileName
,
3223 Obj
.getRelocationSymbol(Rels
[Offset
], PltSymTable
));
3227 const EnumEntry
<unsigned> ElfMipsISAExtType
[] = {
3228 {"None", Mips::AFL_EXT_NONE
},
3229 {"Broadcom SB-1", Mips::AFL_EXT_SB1
},
3230 {"Cavium Networks Octeon", Mips::AFL_EXT_OCTEON
},
3231 {"Cavium Networks Octeon2", Mips::AFL_EXT_OCTEON2
},
3232 {"Cavium Networks OcteonP", Mips::AFL_EXT_OCTEONP
},
3233 {"Cavium Networks Octeon3", Mips::AFL_EXT_OCTEON3
},
3234 {"LSI R4010", Mips::AFL_EXT_4010
},
3235 {"Loongson 2E", Mips::AFL_EXT_LOONGSON_2E
},
3236 {"Loongson 2F", Mips::AFL_EXT_LOONGSON_2F
},
3237 {"Loongson 3A", Mips::AFL_EXT_LOONGSON_3A
},
3238 {"MIPS R4650", Mips::AFL_EXT_4650
},
3239 {"MIPS R5900", Mips::AFL_EXT_5900
},
3240 {"MIPS R10000", Mips::AFL_EXT_10000
},
3241 {"NEC VR4100", Mips::AFL_EXT_4100
},
3242 {"NEC VR4111/VR4181", Mips::AFL_EXT_4111
},
3243 {"NEC VR4120", Mips::AFL_EXT_4120
},
3244 {"NEC VR5400", Mips::AFL_EXT_5400
},
3245 {"NEC VR5500", Mips::AFL_EXT_5500
},
3246 {"RMI Xlr", Mips::AFL_EXT_XLR
},
3247 {"Toshiba R3900", Mips::AFL_EXT_3900
}
3250 const EnumEntry
<unsigned> ElfMipsASEFlags
[] = {
3251 {"DSP", Mips::AFL_ASE_DSP
},
3252 {"DSPR2", Mips::AFL_ASE_DSPR2
},
3253 {"Enhanced VA Scheme", Mips::AFL_ASE_EVA
},
3254 {"MCU", Mips::AFL_ASE_MCU
},
3255 {"MDMX", Mips::AFL_ASE_MDMX
},
3256 {"MIPS-3D", Mips::AFL_ASE_MIPS3D
},
3257 {"MT", Mips::AFL_ASE_MT
},
3258 {"SmartMIPS", Mips::AFL_ASE_SMARTMIPS
},
3259 {"VZ", Mips::AFL_ASE_VIRT
},
3260 {"MSA", Mips::AFL_ASE_MSA
},
3261 {"MIPS16", Mips::AFL_ASE_MIPS16
},
3262 {"microMIPS", Mips::AFL_ASE_MICROMIPS
},
3263 {"XPA", Mips::AFL_ASE_XPA
},
3264 {"CRC", Mips::AFL_ASE_CRC
},
3265 {"GINV", Mips::AFL_ASE_GINV
},
3268 const EnumEntry
<unsigned> ElfMipsFpABIType
[] = {
3269 {"Hard or soft float", Mips::Val_GNU_MIPS_ABI_FP_ANY
},
3270 {"Hard float (double precision)", Mips::Val_GNU_MIPS_ABI_FP_DOUBLE
},
3271 {"Hard float (single precision)", Mips::Val_GNU_MIPS_ABI_FP_SINGLE
},
3272 {"Soft float", Mips::Val_GNU_MIPS_ABI_FP_SOFT
},
3273 {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)",
3274 Mips::Val_GNU_MIPS_ABI_FP_OLD_64
},
3275 {"Hard float (32-bit CPU, Any FPU)", Mips::Val_GNU_MIPS_ABI_FP_XX
},
3276 {"Hard float (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64
},
3277 {"Hard float compat (32-bit CPU, 64-bit FPU)",
3278 Mips::Val_GNU_MIPS_ABI_FP_64A
}
3281 static const EnumEntry
<unsigned> ElfMipsFlags1
[] {
3282 {"ODDSPREG", Mips::AFL_FLAGS1_ODDSPREG
},
3285 static int getMipsRegisterSize(uint8_t Flag
) {
3287 case Mips::AFL_REG_NONE
:
3289 case Mips::AFL_REG_32
:
3291 case Mips::AFL_REG_64
:
3293 case Mips::AFL_REG_128
:
3300 template <class ELFT
>
3301 static void printMipsReginfoData(ScopedPrinter
&W
,
3302 const Elf_Mips_RegInfo
<ELFT
> &Reginfo
) {
3303 W
.printHex("GP", Reginfo
.ri_gp_value
);
3304 W
.printHex("General Mask", Reginfo
.ri_gprmask
);
3305 W
.printHex("Co-Proc Mask0", Reginfo
.ri_cprmask
[0]);
3306 W
.printHex("Co-Proc Mask1", Reginfo
.ri_cprmask
[1]);
3307 W
.printHex("Co-Proc Mask2", Reginfo
.ri_cprmask
[2]);
3308 W
.printHex("Co-Proc Mask3", Reginfo
.ri_cprmask
[3]);
3311 template <class ELFT
> void ELFDumper
<ELFT
>::printMipsReginfo() {
3312 const Elf_Shdr
*RegInfoSec
= findSectionByName(".reginfo");
3314 W
.startLine() << "There is no .reginfo section in the file.\n";
3318 Expected
<ArrayRef
<uint8_t>> ContentsOrErr
=
3319 Obj
.getSectionContents(*RegInfoSec
);
3320 if (!ContentsOrErr
) {
3321 this->reportUniqueWarning(
3322 "unable to read the content of the .reginfo section (" +
3323 describe(*RegInfoSec
) + "): " + toString(ContentsOrErr
.takeError()));
3327 if (ContentsOrErr
->size() < sizeof(Elf_Mips_RegInfo
<ELFT
>)) {
3328 this->reportUniqueWarning("the .reginfo section has an invalid size (0x" +
3329 Twine::utohexstr(ContentsOrErr
->size()) + ")");
3333 DictScope
GS(W
, "MIPS RegInfo");
3334 printMipsReginfoData(W
, *reinterpret_cast<const Elf_Mips_RegInfo
<ELFT
> *>(
3335 ContentsOrErr
->data()));
3338 template <class ELFT
>
3339 static Expected
<const Elf_Mips_Options
<ELFT
> *>
3340 readMipsOptions(const uint8_t *SecBegin
, ArrayRef
<uint8_t> &SecData
,
3341 bool &IsSupported
) {
3342 if (SecData
.size() < sizeof(Elf_Mips_Options
<ELFT
>))
3343 return createError("the .MIPS.options section has an invalid size (0x" +
3344 Twine::utohexstr(SecData
.size()) + ")");
3346 const Elf_Mips_Options
<ELFT
> *O
=
3347 reinterpret_cast<const Elf_Mips_Options
<ELFT
> *>(SecData
.data());
3348 const uint8_t Size
= O
->size
;
3349 if (Size
> SecData
.size()) {
3350 const uint64_t Offset
= SecData
.data() - SecBegin
;
3351 const uint64_t SecSize
= Offset
+ SecData
.size();
3352 return createError("a descriptor of size 0x" + Twine::utohexstr(Size
) +
3353 " at offset 0x" + Twine::utohexstr(Offset
) +
3354 " goes past the end of the .MIPS.options "
3355 "section of size 0x" +
3356 Twine::utohexstr(SecSize
));
3359 IsSupported
= O
->kind
== ODK_REGINFO
;
3360 const size_t ExpectedSize
=
3361 sizeof(Elf_Mips_Options
<ELFT
>) + sizeof(Elf_Mips_RegInfo
<ELFT
>);
3364 if (Size
< ExpectedSize
)
3366 "a .MIPS.options entry of kind " +
3367 Twine(getElfMipsOptionsOdkType(O
->kind
)) +
3368 " has an invalid size (0x" + Twine::utohexstr(Size
) +
3369 "), the expected size is 0x" + Twine::utohexstr(ExpectedSize
));
3371 SecData
= SecData
.drop_front(Size
);
3375 template <class ELFT
> void ELFDumper
<ELFT
>::printMipsOptions() {
3376 const Elf_Shdr
*MipsOpts
= findSectionByName(".MIPS.options");
3378 W
.startLine() << "There is no .MIPS.options section in the file.\n";
3382 DictScope
GS(W
, "MIPS Options");
3384 ArrayRef
<uint8_t> Data
=
3385 unwrapOrError(ObjF
.getFileName(), Obj
.getSectionContents(*MipsOpts
));
3386 const uint8_t *const SecBegin
= Data
.begin();
3387 while (!Data
.empty()) {
3389 Expected
<const Elf_Mips_Options
<ELFT
> *> OptsOrErr
=
3390 readMipsOptions
<ELFT
>(SecBegin
, Data
, IsSupported
);
3392 reportUniqueWarning(OptsOrErr
.takeError());
3396 unsigned Kind
= (*OptsOrErr
)->kind
;
3397 const char *Type
= getElfMipsOptionsOdkType(Kind
);
3399 W
.startLine() << "Unsupported MIPS options tag: " << Type
<< " (" << Kind
3404 DictScope
GS(W
, Type
);
3405 if (Kind
== ODK_REGINFO
)
3406 printMipsReginfoData(W
, (*OptsOrErr
)->getRegInfo());
3408 llvm_unreachable("unexpected .MIPS.options section descriptor kind");
3412 template <class ELFT
> void ELFDumper
<ELFT
>::printStackMap() const {
3413 const Elf_Shdr
*StackMapSection
= findSectionByName(".llvm_stackmaps");
3414 if (!StackMapSection
)
3417 auto Warn
= [&](Error
&&E
) {
3418 this->reportUniqueWarning("unable to read the stack map from " +
3419 describe(*StackMapSection
) + ": " +
3420 toString(std::move(E
)));
3423 Expected
<ArrayRef
<uint8_t>> ContentOrErr
=
3424 Obj
.getSectionContents(*StackMapSection
);
3425 if (!ContentOrErr
) {
3426 Warn(ContentOrErr
.takeError());
3430 if (Error E
= StackMapParser
<ELFT::TargetEndianness
>::validateHeader(
3436 prettyPrintStackMap(W
, StackMapParser
<ELFT::TargetEndianness
>(*ContentOrErr
));
3439 template <class ELFT
>
3440 void ELFDumper
<ELFT
>::printReloc(const Relocation
<ELFT
> &R
, unsigned RelIndex
,
3441 const Elf_Shdr
&Sec
, const Elf_Shdr
*SymTab
) {
3442 Expected
<RelSymbol
<ELFT
>> Target
= getRelocationTarget(R
, SymTab
);
3444 reportUniqueWarning("unable to print relocation " + Twine(RelIndex
) +
3445 " in " + describe(Sec
) + ": " +
3446 toString(Target
.takeError()));
3448 printRelRelaReloc(R
, *Target
);
3451 template <class ELFT
>
3452 std::vector
<EnumEntry
<unsigned>>
3453 ELFDumper
<ELFT
>::getOtherFlagsFromSymbol(const Elf_Ehdr
&Header
,
3454 const Elf_Sym
&Symbol
) const {
3455 std::vector
<EnumEntry
<unsigned>> SymOtherFlags(std::begin(ElfSymOtherFlags
),
3456 std::end(ElfSymOtherFlags
));
3457 if (Header
.e_machine
== EM_MIPS
) {
3458 // Someone in their infinite wisdom decided to make STO_MIPS_MIPS16
3459 // flag overlap with other ST_MIPS_xxx flags. So consider both
3460 // cases separately.
3461 if ((Symbol
.st_other
& STO_MIPS_MIPS16
) == STO_MIPS_MIPS16
)
3462 SymOtherFlags
.insert(SymOtherFlags
.end(),
3463 std::begin(ElfMips16SymOtherFlags
),
3464 std::end(ElfMips16SymOtherFlags
));
3466 SymOtherFlags
.insert(SymOtherFlags
.end(),
3467 std::begin(ElfMipsSymOtherFlags
),
3468 std::end(ElfMipsSymOtherFlags
));
3469 } else if (Header
.e_machine
== EM_AARCH64
) {
3470 SymOtherFlags
.insert(SymOtherFlags
.end(),
3471 std::begin(ElfAArch64SymOtherFlags
),
3472 std::end(ElfAArch64SymOtherFlags
));
3473 } else if (Header
.e_machine
== EM_RISCV
) {
3474 SymOtherFlags
.insert(SymOtherFlags
.end(), std::begin(ElfRISCVSymOtherFlags
),
3475 std::end(ElfRISCVSymOtherFlags
));
3477 return SymOtherFlags
;
3480 static inline void printFields(formatted_raw_ostream
&OS
, StringRef Str1
,
3484 OS
.PadToColumn(37u);
3489 template <class ELFT
>
3490 static std::string
getSectionHeadersNumString(const ELFFile
<ELFT
> &Obj
,
3491 StringRef FileName
) {
3492 const typename
ELFT::Ehdr
&ElfHeader
= Obj
.getHeader();
3493 if (ElfHeader
.e_shnum
!= 0)
3494 return to_string(ElfHeader
.e_shnum
);
3496 Expected
<ArrayRef
<typename
ELFT::Shdr
>> ArrOrErr
= Obj
.sections();
3498 // In this case we can ignore an error, because we have already reported a
3499 // warning about the broken section header table earlier.
3500 consumeError(ArrOrErr
.takeError());
3504 if (ArrOrErr
->empty())
3506 return "0 (" + to_string((*ArrOrErr
)[0].sh_size
) + ")";
3509 template <class ELFT
>
3510 static std::string
getSectionHeaderTableIndexString(const ELFFile
<ELFT
> &Obj
,
3511 StringRef FileName
) {
3512 const typename
ELFT::Ehdr
&ElfHeader
= Obj
.getHeader();
3513 if (ElfHeader
.e_shstrndx
!= SHN_XINDEX
)
3514 return to_string(ElfHeader
.e_shstrndx
);
3516 Expected
<ArrayRef
<typename
ELFT::Shdr
>> ArrOrErr
= Obj
.sections();
3518 // In this case we can ignore an error, because we have already reported a
3519 // warning about the broken section header table earlier.
3520 consumeError(ArrOrErr
.takeError());
3524 if (ArrOrErr
->empty())
3525 return "65535 (corrupt: out of range)";
3526 return to_string(ElfHeader
.e_shstrndx
) + " (" +
3527 to_string((*ArrOrErr
)[0].sh_link
) + ")";
3530 static const EnumEntry
<unsigned> *getObjectFileEnumEntry(unsigned Type
) {
3531 auto It
= llvm::find_if(ElfObjectFileType
, [&](const EnumEntry
<unsigned> &E
) {
3532 return E
.Value
== Type
;
3534 if (It
!= ArrayRef(ElfObjectFileType
).end())
3539 template <class ELFT
>
3540 void GNUELFDumper
<ELFT
>::printFileSummary(StringRef FileStr
, ObjectFile
&Obj
,
3541 ArrayRef
<std::string
> InputFilenames
,
3543 if (InputFilenames
.size() > 1 || A
) {
3544 this->W
.startLine() << "\n";
3545 this->W
.printString("File", FileStr
);
3549 template <class ELFT
> void GNUELFDumper
<ELFT
>::printFileHeaders() {
3550 const Elf_Ehdr
&e
= this->Obj
.getHeader();
3551 OS
<< "ELF Header:\n";
3554 for (int i
= 0; i
< ELF::EI_NIDENT
; i
++)
3555 OS
<< format(" %02x", static_cast<int>(e
.e_ident
[i
]));
3557 Str
= enumToString(e
.e_ident
[ELF::EI_CLASS
], ArrayRef(ElfClass
));
3558 printFields(OS
, "Class:", Str
);
3559 Str
= enumToString(e
.e_ident
[ELF::EI_DATA
], ArrayRef(ElfDataEncoding
));
3560 printFields(OS
, "Data:", Str
);
3563 OS
.PadToColumn(37u);
3564 OS
<< utohexstr(e
.e_ident
[ELF::EI_VERSION
]);
3565 if (e
.e_version
== ELF::EV_CURRENT
)
3568 Str
= enumToString(e
.e_ident
[ELF::EI_OSABI
], ArrayRef(ElfOSABI
));
3569 printFields(OS
, "OS/ABI:", Str
);
3571 "ABI Version:", std::to_string(e
.e_ident
[ELF::EI_ABIVERSION
]));
3573 if (const EnumEntry
<unsigned> *E
= getObjectFileEnumEntry(e
.e_type
)) {
3574 Str
= E
->AltName
.str();
3576 if (e
.e_type
>= ET_LOPROC
)
3577 Str
= "Processor Specific: (" + utohexstr(e
.e_type
, /*LowerCase=*/true) + ")";
3578 else if (e
.e_type
>= ET_LOOS
)
3579 Str
= "OS Specific: (" + utohexstr(e
.e_type
, /*LowerCase=*/true) + ")";
3581 Str
= "<unknown>: " + utohexstr(e
.e_type
, /*LowerCase=*/true);
3583 printFields(OS
, "Type:", Str
);
3585 Str
= enumToString(e
.e_machine
, ArrayRef(ElfMachineType
));
3586 printFields(OS
, "Machine:", Str
);
3587 Str
= "0x" + utohexstr(e
.e_version
);
3588 printFields(OS
, "Version:", Str
);
3589 Str
= "0x" + utohexstr(e
.e_entry
);
3590 printFields(OS
, "Entry point address:", Str
);
3591 Str
= to_string(e
.e_phoff
) + " (bytes into file)";
3592 printFields(OS
, "Start of program headers:", Str
);
3593 Str
= to_string(e
.e_shoff
) + " (bytes into file)";
3594 printFields(OS
, "Start of section headers:", Str
);
3595 std::string ElfFlags
;
3596 if (e
.e_machine
== EM_MIPS
)
3597 ElfFlags
= printFlags(
3598 e
.e_flags
, ArrayRef(ElfHeaderMipsFlags
), unsigned(ELF::EF_MIPS_ARCH
),
3599 unsigned(ELF::EF_MIPS_ABI
), unsigned(ELF::EF_MIPS_MACH
));
3600 else if (e
.e_machine
== EM_RISCV
)
3601 ElfFlags
= printFlags(e
.e_flags
, ArrayRef(ElfHeaderRISCVFlags
));
3602 else if (e
.e_machine
== EM_AVR
)
3603 ElfFlags
= printFlags(e
.e_flags
, ArrayRef(ElfHeaderAVRFlags
),
3604 unsigned(ELF::EF_AVR_ARCH_MASK
));
3605 else if (e
.e_machine
== EM_LOONGARCH
)
3606 ElfFlags
= printFlags(e
.e_flags
, ArrayRef(ElfHeaderLoongArchFlags
),
3607 unsigned(ELF::EF_LOONGARCH_ABI_MODIFIER_MASK
),
3608 unsigned(ELF::EF_LOONGARCH_OBJABI_MASK
));
3609 else if (e
.e_machine
== EM_XTENSA
)
3610 ElfFlags
= printFlags(e
.e_flags
, ArrayRef(ElfHeaderXtensaFlags
),
3611 unsigned(ELF::EF_XTENSA_MACH
));
3612 Str
= "0x" + utohexstr(e
.e_flags
);
3613 if (!ElfFlags
.empty())
3614 Str
= Str
+ ", " + ElfFlags
;
3615 printFields(OS
, "Flags:", Str
);
3616 Str
= to_string(e
.e_ehsize
) + " (bytes)";
3617 printFields(OS
, "Size of this header:", Str
);
3618 Str
= to_string(e
.e_phentsize
) + " (bytes)";
3619 printFields(OS
, "Size of program headers:", Str
);
3620 Str
= to_string(e
.e_phnum
);
3621 printFields(OS
, "Number of program headers:", Str
);
3622 Str
= to_string(e
.e_shentsize
) + " (bytes)";
3623 printFields(OS
, "Size of section headers:", Str
);
3624 Str
= getSectionHeadersNumString(this->Obj
, this->FileName
);
3625 printFields(OS
, "Number of section headers:", Str
);
3626 Str
= getSectionHeaderTableIndexString(this->Obj
, this->FileName
);
3627 printFields(OS
, "Section header string table index:", Str
);
3630 template <class ELFT
> std::vector
<GroupSection
> ELFDumper
<ELFT
>::getGroups() {
3631 auto GetSignature
= [&](const Elf_Sym
&Sym
, unsigned SymNdx
,
3632 const Elf_Shdr
&Symtab
) -> StringRef
{
3633 Expected
<StringRef
> StrTableOrErr
= Obj
.getStringTableForSymtab(Symtab
);
3634 if (!StrTableOrErr
) {
3635 reportUniqueWarning("unable to get the string table for " +
3636 describe(Symtab
) + ": " +
3637 toString(StrTableOrErr
.takeError()));
3641 StringRef Strings
= *StrTableOrErr
;
3642 if (Sym
.st_name
>= Strings
.size()) {
3643 reportUniqueWarning("unable to get the name of the symbol with index " +
3644 Twine(SymNdx
) + ": st_name (0x" +
3645 Twine::utohexstr(Sym
.st_name
) +
3646 ") is past the end of the string table of size 0x" +
3647 Twine::utohexstr(Strings
.size()));
3651 return StrTableOrErr
->data() + Sym
.st_name
;
3654 std::vector
<GroupSection
> Ret
;
3656 for (const Elf_Shdr
&Sec
: cantFail(Obj
.sections())) {
3658 if (Sec
.sh_type
!= ELF::SHT_GROUP
)
3661 StringRef Signature
= "<?>";
3662 if (Expected
<const Elf_Shdr
*> SymtabOrErr
= Obj
.getSection(Sec
.sh_link
)) {
3663 if (Expected
<const Elf_Sym
*> SymOrErr
=
3664 Obj
.template getEntry
<Elf_Sym
>(**SymtabOrErr
, Sec
.sh_info
))
3665 Signature
= GetSignature(**SymOrErr
, Sec
.sh_info
, **SymtabOrErr
);
3667 reportUniqueWarning("unable to get the signature symbol for " +
3668 describe(Sec
) + ": " +
3669 toString(SymOrErr
.takeError()));
3671 reportUniqueWarning("unable to get the symbol table for " +
3672 describe(Sec
) + ": " +
3673 toString(SymtabOrErr
.takeError()));
3676 ArrayRef
<Elf_Word
> Data
;
3677 if (Expected
<ArrayRef
<Elf_Word
>> ContentsOrErr
=
3678 Obj
.template getSectionContentsAsArray
<Elf_Word
>(Sec
)) {
3679 if (ContentsOrErr
->empty())
3680 reportUniqueWarning("unable to read the section group flag from the " +
3681 describe(Sec
) + ": the section is empty");
3683 Data
= *ContentsOrErr
;
3685 reportUniqueWarning("unable to get the content of the " + describe(Sec
) +
3686 ": " + toString(ContentsOrErr
.takeError()));
3689 Ret
.push_back({getPrintableSectionName(Sec
),
3690 maybeDemangle(Signature
),
3695 Data
.empty() ? Elf_Word(0) : Data
[0],
3701 std::vector
<GroupMember
> &GM
= Ret
.back().Members
;
3702 for (uint32_t Ndx
: Data
.slice(1)) {
3703 if (Expected
<const Elf_Shdr
*> SecOrErr
= Obj
.getSection(Ndx
)) {
3704 GM
.push_back({getPrintableSectionName(**SecOrErr
), Ndx
});
3706 reportUniqueWarning("unable to get the section with index " +
3707 Twine(Ndx
) + " when dumping the " + describe(Sec
) +
3708 ": " + toString(SecOrErr
.takeError()));
3709 GM
.push_back({"<?>", Ndx
});
3716 static DenseMap
<uint64_t, const GroupSection
*>
3717 mapSectionsToGroups(ArrayRef
<GroupSection
> Groups
) {
3718 DenseMap
<uint64_t, const GroupSection
*> Ret
;
3719 for (const GroupSection
&G
: Groups
)
3720 for (const GroupMember
&GM
: G
.Members
)
3721 Ret
.insert({GM
.Index
, &G
});
3725 template <class ELFT
> void GNUELFDumper
<ELFT
>::printGroupSections() {
3726 std::vector
<GroupSection
> V
= this->getGroups();
3727 DenseMap
<uint64_t, const GroupSection
*> Map
= mapSectionsToGroups(V
);
3728 for (const GroupSection
&G
: V
) {
3730 << getGroupType(G
.Type
) << " group section ["
3731 << format_decimal(G
.Index
, 5) << "] `" << G
.Name
<< "' [" << G
.Signature
3732 << "] contains " << G
.Members
.size() << " sections:\n"
3733 << " [Index] Name\n";
3734 for (const GroupMember
&GM
: G
.Members
) {
3735 const GroupSection
*MainGroup
= Map
[GM
.Index
];
3736 if (MainGroup
!= &G
)
3737 this->reportUniqueWarning(
3738 "section with index " + Twine(GM
.Index
) +
3739 ", included in the group section with index " +
3740 Twine(MainGroup
->Index
) +
3741 ", was also found in the group section with index " +
3743 OS
<< " [" << format_decimal(GM
.Index
, 5) << "] " << GM
.Name
<< "\n";
3748 OS
<< "There are no section groups in this file.\n";
3751 template <class ELFT
>
3752 void GNUELFDumper
<ELFT
>::printRelrReloc(const Elf_Relr
&R
) {
3753 OS
<< to_string(format_hex_no_prefix(R
, ELFT::Is64Bits
? 16 : 8)) << "\n";
3756 template <class ELFT
>
3757 void GNUELFDumper
<ELFT
>::printRelRelaReloc(const Relocation
<ELFT
> &R
,
3758 const RelSymbol
<ELFT
> &RelSym
) {
3759 // First two fields are bit width dependent. The rest of them are fixed width.
3760 unsigned Bias
= ELFT::Is64Bits
? 8 : 0;
3761 Field Fields
[5] = {0, 10 + Bias
, 19 + 2 * Bias
, 42 + 2 * Bias
, 53 + 2 * Bias
};
3762 unsigned Width
= ELFT::Is64Bits
? 16 : 8;
3764 Fields
[0].Str
= to_string(format_hex_no_prefix(R
.Offset
, Width
));
3765 Fields
[1].Str
= to_string(format_hex_no_prefix(R
.Info
, Width
));
3767 SmallString
<32> RelocName
;
3768 this->Obj
.getRelocationTypeName(R
.Type
, RelocName
);
3769 Fields
[2].Str
= RelocName
.c_str();
3773 to_string(format_hex_no_prefix(RelSym
.Sym
->getValue(), Width
));
3774 if (RelSym
.Sym
&& RelSym
.Name
.empty())
3775 Fields
[4].Str
= "<null>";
3777 Fields
[4].Str
= std::string(RelSym
.Name
);
3779 for (const Field
&F
: Fields
)
3783 if (std::optional
<int64_t> A
= R
.Addend
) {
3784 int64_t RelAddend
= *A
;
3785 if (!Fields
[4].Str
.empty()) {
3786 if (RelAddend
< 0) {
3788 RelAddend
= -static_cast<uint64_t>(RelAddend
);
3793 Addend
+= utohexstr(RelAddend
, /*LowerCase=*/true);
3795 OS
<< Addend
<< "\n";
3798 template <class ELFT
>
3799 static void printRelocHeaderFields(formatted_raw_ostream
&OS
, unsigned SType
) {
3800 bool IsRela
= SType
== ELF::SHT_RELA
|| SType
== ELF::SHT_ANDROID_RELA
;
3801 bool IsRelr
= SType
== ELF::SHT_RELR
|| SType
== ELF::SHT_ANDROID_RELR
;
3806 if (IsRelr
&& opts::RawRelr
)
3812 << " Symbol's Value Symbol's Name";
3814 OS
<< " Info Type Sym. Value Symbol's Name";
3820 template <class ELFT
>
3821 void GNUELFDumper
<ELFT
>::printDynamicRelocHeader(unsigned Type
, StringRef Name
,
3822 const DynRegionInfo
&Reg
) {
3823 uint64_t Offset
= Reg
.Addr
- this->Obj
.base();
3824 OS
<< "\n'" << Name
.str().c_str() << "' relocation section at offset 0x"
3825 << utohexstr(Offset
, /*LowerCase=*/true) << " contains " << Reg
.Size
<< " bytes:\n";
3826 printRelocHeaderFields
<ELFT
>(OS
, Type
);
3829 template <class ELFT
>
3830 static bool isRelocationSec(const typename
ELFT::Shdr
&Sec
) {
3831 return Sec
.sh_type
== ELF::SHT_REL
|| Sec
.sh_type
== ELF::SHT_RELA
||
3832 Sec
.sh_type
== ELF::SHT_RELR
|| Sec
.sh_type
== ELF::SHT_ANDROID_REL
||
3833 Sec
.sh_type
== ELF::SHT_ANDROID_RELA
||
3834 Sec
.sh_type
== ELF::SHT_ANDROID_RELR
;
3837 template <class ELFT
> void GNUELFDumper
<ELFT
>::printRelocations() {
3838 auto GetEntriesNum
= [&](const Elf_Shdr
&Sec
) -> Expected
<size_t> {
3839 // Android's packed relocation section needs to be unpacked first
3840 // to get the actual number of entries.
3841 if (Sec
.sh_type
== ELF::SHT_ANDROID_REL
||
3842 Sec
.sh_type
== ELF::SHT_ANDROID_RELA
) {
3843 Expected
<std::vector
<typename
ELFT::Rela
>> RelasOrErr
=
3844 this->Obj
.android_relas(Sec
);
3846 return RelasOrErr
.takeError();
3847 return RelasOrErr
->size();
3850 if (!opts::RawRelr
&& (Sec
.sh_type
== ELF::SHT_RELR
||
3851 Sec
.sh_type
== ELF::SHT_ANDROID_RELR
)) {
3852 Expected
<Elf_Relr_Range
> RelrsOrErr
= this->Obj
.relrs(Sec
);
3854 return RelrsOrErr
.takeError();
3855 return this->Obj
.decode_relrs(*RelrsOrErr
).size();
3858 return Sec
.getEntityCount();
3861 bool HasRelocSections
= false;
3862 for (const Elf_Shdr
&Sec
: cantFail(this->Obj
.sections())) {
3863 if (!isRelocationSec
<ELFT
>(Sec
))
3865 HasRelocSections
= true;
3867 std::string EntriesNum
= "<?>";
3868 if (Expected
<size_t> NumOrErr
= GetEntriesNum(Sec
))
3869 EntriesNum
= std::to_string(*NumOrErr
);
3871 this->reportUniqueWarning("unable to get the number of relocations in " +
3872 this->describe(Sec
) + ": " +
3873 toString(NumOrErr
.takeError()));
3875 uintX_t Offset
= Sec
.sh_offset
;
3876 StringRef Name
= this->getPrintableSectionName(Sec
);
3877 OS
<< "\nRelocation section '" << Name
<< "' at offset 0x"
3878 << utohexstr(Offset
, /*LowerCase=*/true) << " contains " << EntriesNum
3880 printRelocHeaderFields
<ELFT
>(OS
, Sec
.sh_type
);
3881 this->printRelocationsHelper(Sec
);
3883 if (!HasRelocSections
)
3884 OS
<< "\nThere are no relocations in this file.\n";
3887 // Print the offset of a particular section from anyone of the ranges:
3888 // [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER].
3889 // If 'Type' does not fall within any of those ranges, then a string is
3890 // returned as '<unknown>' followed by the type value.
3891 static std::string
getSectionTypeOffsetString(unsigned Type
) {
3892 if (Type
>= SHT_LOOS
&& Type
<= SHT_HIOS
)
3893 return "LOOS+0x" + utohexstr(Type
- SHT_LOOS
);
3894 else if (Type
>= SHT_LOPROC
&& Type
<= SHT_HIPROC
)
3895 return "LOPROC+0x" + utohexstr(Type
- SHT_LOPROC
);
3896 else if (Type
>= SHT_LOUSER
&& Type
<= SHT_HIUSER
)
3897 return "LOUSER+0x" + utohexstr(Type
- SHT_LOUSER
);
3898 return "0x" + utohexstr(Type
) + ": <unknown>";
3901 static std::string
getSectionTypeString(unsigned Machine
, unsigned Type
) {
3902 StringRef Name
= getELFSectionTypeName(Machine
, Type
);
3904 // Handle SHT_GNU_* type names.
3905 if (Name
.consume_front("SHT_GNU_")) {
3908 // E.g. SHT_GNU_verneed -> VERNEED.
3909 return Name
.upper();
3912 if (Name
== "SHT_SYMTAB_SHNDX")
3913 return "SYMTAB SECTION INDICES";
3915 if (Name
.consume_front("SHT_"))
3917 return getSectionTypeOffsetString(Type
);
3920 static void printSectionDescription(formatted_raw_ostream
&OS
,
3921 unsigned EMachine
) {
3922 OS
<< "Key to Flags:\n";
3923 OS
<< " W (write), A (alloc), X (execute), M (merge), S (strings), I "
3925 OS
<< " L (link order), O (extra OS processing required), G (group), T "
3927 OS
<< " C (compressed), x (unknown), o (OS specific), E (exclude),\n";
3928 OS
<< " R (retain)";
3930 if (EMachine
== EM_X86_64
)
3931 OS
<< ", l (large)";
3932 else if (EMachine
== EM_ARM
)
3933 OS
<< ", y (purecode)";
3935 OS
<< ", p (processor specific)\n";
3938 template <class ELFT
> void GNUELFDumper
<ELFT
>::printSectionHeaders() {
3939 ArrayRef
<Elf_Shdr
> Sections
= cantFail(this->Obj
.sections());
3940 if (Sections
.empty()) {
3941 OS
<< "\nThere are no sections in this file.\n";
3942 Expected
<StringRef
> SecStrTableOrErr
=
3943 this->Obj
.getSectionStringTable(Sections
, this->WarningHandler
);
3944 if (!SecStrTableOrErr
)
3945 this->reportUniqueWarning(SecStrTableOrErr
.takeError());
3948 unsigned Bias
= ELFT::Is64Bits
? 0 : 8;
3949 OS
<< "There are " << to_string(Sections
.size())
3950 << " section headers, starting at offset "
3951 << "0x" << utohexstr(this->Obj
.getHeader().e_shoff
, /*LowerCase=*/true) << ":\n\n";
3952 OS
<< "Section Headers:\n";
3953 Field Fields
[11] = {
3954 {"[Nr]", 2}, {"Name", 7}, {"Type", 25},
3955 {"Address", 41}, {"Off", 58 - Bias
}, {"Size", 65 - Bias
},
3956 {"ES", 72 - Bias
}, {"Flg", 75 - Bias
}, {"Lk", 79 - Bias
},
3957 {"Inf", 82 - Bias
}, {"Al", 86 - Bias
}};
3958 for (const Field
&F
: Fields
)
3962 StringRef SecStrTable
;
3963 if (Expected
<StringRef
> SecStrTableOrErr
=
3964 this->Obj
.getSectionStringTable(Sections
, this->WarningHandler
))
3965 SecStrTable
= *SecStrTableOrErr
;
3967 this->reportUniqueWarning(SecStrTableOrErr
.takeError());
3969 size_t SectionIndex
= 0;
3970 for (const Elf_Shdr
&Sec
: Sections
) {
3971 Fields
[0].Str
= to_string(SectionIndex
);
3972 if (SecStrTable
.empty())
3973 Fields
[1].Str
= "<no-strings>";
3975 Fields
[1].Str
= std::string(unwrapOrError
<StringRef
>(
3976 this->FileName
, this->Obj
.getSectionName(Sec
, SecStrTable
)));
3978 getSectionTypeString(this->Obj
.getHeader().e_machine
, Sec
.sh_type
);
3980 to_string(format_hex_no_prefix(Sec
.sh_addr
, ELFT::Is64Bits
? 16 : 8));
3981 Fields
[4].Str
= to_string(format_hex_no_prefix(Sec
.sh_offset
, 6));
3982 Fields
[5].Str
= to_string(format_hex_no_prefix(Sec
.sh_size
, 6));
3983 Fields
[6].Str
= to_string(format_hex_no_prefix(Sec
.sh_entsize
, 2));
3984 Fields
[7].Str
= getGNUFlags(this->Obj
.getHeader().e_ident
[ELF::EI_OSABI
],
3985 this->Obj
.getHeader().e_machine
, Sec
.sh_flags
);
3986 Fields
[8].Str
= to_string(Sec
.sh_link
);
3987 Fields
[9].Str
= to_string(Sec
.sh_info
);
3988 Fields
[10].Str
= to_string(Sec
.sh_addralign
);
3990 OS
.PadToColumn(Fields
[0].Column
);
3991 OS
<< "[" << right_justify(Fields
[0].Str
, 2) << "]";
3992 for (int i
= 1; i
< 7; i
++)
3993 printField(Fields
[i
]);
3994 OS
.PadToColumn(Fields
[7].Column
);
3995 OS
<< right_justify(Fields
[7].Str
, 3);
3996 OS
.PadToColumn(Fields
[8].Column
);
3997 OS
<< right_justify(Fields
[8].Str
, 2);
3998 OS
.PadToColumn(Fields
[9].Column
);
3999 OS
<< right_justify(Fields
[9].Str
, 3);
4000 OS
.PadToColumn(Fields
[10].Column
);
4001 OS
<< right_justify(Fields
[10].Str
, 2);
4005 printSectionDescription(OS
, this->Obj
.getHeader().e_machine
);
4008 template <class ELFT
>
4009 void GNUELFDumper
<ELFT
>::printSymtabMessage(const Elf_Shdr
*Symtab
,
4011 bool NonVisibilityBitsUsed
,
4012 bool ExtraSymInfo
) const {
4015 Name
= this->getPrintableSectionName(*Symtab
);
4017 OS
<< "\nSymbol table '" << Name
<< "'";
4019 OS
<< "\nSymbol table for image";
4020 OS
<< " contains " << Entries
<< " entries:\n";
4022 if (ELFT::Is64Bits
) {
4023 OS
<< " Num: Value Size Type Bind Vis";
4027 OS
<< " Num: Value Size Type Bind Vis";
4032 OS
.PadToColumn((ELFT::Is64Bits
? 56 : 48) + (NonVisibilityBitsUsed
? 13 : 0));
4034 OS
<< "Ndx(SecName) Name [+ Version Info]\n";
4039 template <class ELFT
>
4040 std::string GNUELFDumper
<ELFT
>::getSymbolSectionNdx(
4041 const Elf_Sym
&Symbol
, unsigned SymIndex
, DataRegion
<Elf_Word
> ShndxTable
,
4042 bool ExtraSymInfo
) const {
4043 unsigned SectionIndex
= Symbol
.st_shndx
;
4044 switch (SectionIndex
) {
4045 case ELF::SHN_UNDEF
:
4049 case ELF::SHN_COMMON
:
4051 case ELF::SHN_XINDEX
: {
4052 Expected
<uint32_t> IndexOrErr
=
4053 object::getExtendedSymbolTableIndex
<ELFT
>(Symbol
, SymIndex
, ShndxTable
);
4055 assert(Symbol
.st_shndx
== SHN_XINDEX
&&
4056 "getExtendedSymbolTableIndex should only fail due to an invalid "
4057 "SHT_SYMTAB_SHNDX table/reference");
4058 this->reportUniqueWarning(IndexOrErr
.takeError());
4059 return "RSV[0xffff]";
4061 SectionIndex
= *IndexOrErr
;
4066 // Processor specific
4067 if (SectionIndex
>= ELF::SHN_LOPROC
&& SectionIndex
<= ELF::SHN_HIPROC
)
4068 return std::string("PRC[0x") +
4069 to_string(format_hex_no_prefix(SectionIndex
, 4)) + "]";
4071 if (SectionIndex
>= ELF::SHN_LOOS
&& SectionIndex
<= ELF::SHN_HIOS
)
4072 return std::string("OS[0x") +
4073 to_string(format_hex_no_prefix(SectionIndex
, 4)) + "]";
4074 // Architecture reserved:
4075 if (SectionIndex
>= ELF::SHN_LORESERVE
&&
4076 SectionIndex
<= ELF::SHN_HIRESERVE
)
4077 return std::string("RSV[0x") +
4078 to_string(format_hex_no_prefix(SectionIndex
, 4)) + "]";
4084 auto Sec
= this->Obj
.getSection(SectionIndex
);
4086 this->reportUniqueWarning(Sec
.takeError());
4088 auto SecName
= this->Obj
.getSectionName(**Sec
);
4090 this->reportUniqueWarning(SecName
.takeError());
4092 Extra
= Twine(" (" + *SecName
+ ")").str();
4095 return to_string(format_decimal(SectionIndex
, 3)) + Extra
;
4098 template <class ELFT
>
4099 void GNUELFDumper
<ELFT
>::printSymbol(const Elf_Sym
&Symbol
, unsigned SymIndex
,
4100 DataRegion
<Elf_Word
> ShndxTable
,
4101 std::optional
<StringRef
> StrTable
,
4102 bool IsDynamic
, bool NonVisibilityBitsUsed
,
4103 bool ExtraSymInfo
) const {
4104 unsigned Bias
= ELFT::Is64Bits
? 8 : 0;
4105 Field Fields
[8] = {0, 8, 17 + Bias
, 23 + Bias
,
4106 31 + Bias
, 38 + Bias
, 48 + Bias
, 51 + Bias
};
4107 Fields
[0].Str
= to_string(format_decimal(SymIndex
, 6)) + ":";
4109 to_string(format_hex_no_prefix(Symbol
.st_value
, ELFT::Is64Bits
? 16 : 8));
4110 Fields
[2].Str
= to_string(format_decimal(Symbol
.st_size
, 5));
4112 unsigned char SymbolType
= Symbol
.getType();
4113 if (this->Obj
.getHeader().e_machine
== ELF::EM_AMDGPU
&&
4114 SymbolType
>= ELF::STT_LOOS
&& SymbolType
< ELF::STT_HIOS
)
4115 Fields
[3].Str
= enumToString(SymbolType
, ArrayRef(AMDGPUSymbolTypes
));
4117 Fields
[3].Str
= enumToString(SymbolType
, ArrayRef(ElfSymbolTypes
));
4120 enumToString(Symbol
.getBinding(), ArrayRef(ElfSymbolBindings
));
4122 enumToString(Symbol
.getVisibility(), ArrayRef(ElfSymbolVisibilities
));
4124 if (Symbol
.st_other
& ~0x3) {
4125 if (this->Obj
.getHeader().e_machine
== ELF::EM_AARCH64
) {
4126 uint8_t Other
= Symbol
.st_other
& ~0x3;
4127 if (Other
& STO_AARCH64_VARIANT_PCS
) {
4128 Other
&= ~STO_AARCH64_VARIANT_PCS
;
4129 Fields
[5].Str
+= " [VARIANT_PCS";
4131 Fields
[5].Str
.append(" | " + utohexstr(Other
, /*LowerCase=*/true));
4132 Fields
[5].Str
.append("]");
4134 } else if (this->Obj
.getHeader().e_machine
== ELF::EM_RISCV
) {
4135 uint8_t Other
= Symbol
.st_other
& ~0x3;
4136 if (Other
& STO_RISCV_VARIANT_CC
) {
4137 Other
&= ~STO_RISCV_VARIANT_CC
;
4138 Fields
[5].Str
+= " [VARIANT_CC";
4140 Fields
[5].Str
.append(" | " + utohexstr(Other
, /*LowerCase=*/true));
4141 Fields
[5].Str
.append("]");
4145 " [<other: " + to_string(format_hex(Symbol
.st_other
, 2)) + ">]";
4149 Fields
[6].Column
+= NonVisibilityBitsUsed
? 13 : 0;
4151 getSymbolSectionNdx(Symbol
, SymIndex
, ShndxTable
, ExtraSymInfo
);
4153 Fields
[7].Column
+= ExtraSymInfo
? 10 : 0;
4154 Fields
[7].Str
= this->getFullSymbolName(Symbol
, SymIndex
, ShndxTable
,
4155 StrTable
, IsDynamic
);
4156 for (const Field
&Entry
: Fields
)
4161 template <class ELFT
>
4162 void GNUELFDumper
<ELFT
>::printHashedSymbol(const Elf_Sym
*Symbol
,
4164 DataRegion
<Elf_Word
> ShndxTable
,
4167 unsigned Bias
= ELFT::Is64Bits
? 8 : 0;
4168 Field Fields
[9] = {0, 6, 11, 20 + Bias
, 25 + Bias
,
4169 34 + Bias
, 41 + Bias
, 49 + Bias
, 53 + Bias
};
4170 Fields
[0].Str
= to_string(format_decimal(SymIndex
, 5));
4171 Fields
[1].Str
= to_string(format_decimal(Bucket
, 3)) + ":";
4173 Fields
[2].Str
= to_string(
4174 format_hex_no_prefix(Symbol
->st_value
, ELFT::Is64Bits
? 16 : 8));
4175 Fields
[3].Str
= to_string(format_decimal(Symbol
->st_size
, 5));
4177 unsigned char SymbolType
= Symbol
->getType();
4178 if (this->Obj
.getHeader().e_machine
== ELF::EM_AMDGPU
&&
4179 SymbolType
>= ELF::STT_LOOS
&& SymbolType
< ELF::STT_HIOS
)
4180 Fields
[4].Str
= enumToString(SymbolType
, ArrayRef(AMDGPUSymbolTypes
));
4182 Fields
[4].Str
= enumToString(SymbolType
, ArrayRef(ElfSymbolTypes
));
4185 enumToString(Symbol
->getBinding(), ArrayRef(ElfSymbolBindings
));
4187 enumToString(Symbol
->getVisibility(), ArrayRef(ElfSymbolVisibilities
));
4188 Fields
[7].Str
= getSymbolSectionNdx(*Symbol
, SymIndex
, ShndxTable
);
4190 this->getFullSymbolName(*Symbol
, SymIndex
, ShndxTable
, StrTable
, true);
4192 for (const Field
&Entry
: Fields
)
4197 template <class ELFT
>
4198 void GNUELFDumper
<ELFT
>::printSymbols(bool PrintSymbols
,
4199 bool PrintDynamicSymbols
,
4200 bool ExtraSymInfo
) {
4201 if (!PrintSymbols
&& !PrintDynamicSymbols
)
4203 // GNU readelf prints both the .dynsym and .symtab with --symbols.
4204 this->printSymbolsHelper(true, ExtraSymInfo
);
4206 this->printSymbolsHelper(false, ExtraSymInfo
);
4209 template <class ELFT
>
4210 void GNUELFDumper
<ELFT
>::printHashTableSymbols(const Elf_Hash
&SysVHash
) {
4211 if (this->DynamicStringTable
.empty())
4215 OS
<< " Num Buc: Value Size Type Bind Vis Ndx Name";
4217 OS
<< " Num Buc: Value Size Type Bind Vis Ndx Name";
4220 Elf_Sym_Range DynSyms
= this->dynamic_symbols();
4221 const Elf_Sym
*FirstSym
= DynSyms
.empty() ? nullptr : &DynSyms
[0];
4223 this->reportUniqueWarning(
4224 Twine("unable to print symbols for the .hash table: the "
4225 "dynamic symbol table ") +
4226 (this->DynSymRegion
? "is empty" : "was not found"));
4230 DataRegion
<Elf_Word
> ShndxTable(
4231 (const Elf_Word
*)this->DynSymTabShndxRegion
.Addr
, this->Obj
.end());
4232 auto Buckets
= SysVHash
.buckets();
4233 auto Chains
= SysVHash
.chains();
4234 for (uint32_t Buc
= 0; Buc
< SysVHash
.nbucket
; Buc
++) {
4235 if (Buckets
[Buc
] == ELF::STN_UNDEF
)
4237 BitVector
Visited(SysVHash
.nchain
);
4238 for (uint32_t Ch
= Buckets
[Buc
]; Ch
< SysVHash
.nchain
; Ch
= Chains
[Ch
]) {
4239 if (Ch
== ELF::STN_UNDEF
)
4243 this->reportUniqueWarning(".hash section is invalid: bucket " +
4245 ": a cycle was detected in the linked chain");
4249 printHashedSymbol(FirstSym
+ Ch
, Ch
, ShndxTable
, this->DynamicStringTable
,
4256 template <class ELFT
>
4257 void GNUELFDumper
<ELFT
>::printGnuHashTableSymbols(const Elf_GnuHash
&GnuHash
) {
4258 if (this->DynamicStringTable
.empty())
4261 Elf_Sym_Range DynSyms
= this->dynamic_symbols();
4262 const Elf_Sym
*FirstSym
= DynSyms
.empty() ? nullptr : &DynSyms
[0];
4264 this->reportUniqueWarning(
4265 Twine("unable to print symbols for the .gnu.hash table: the "
4266 "dynamic symbol table ") +
4267 (this->DynSymRegion
? "is empty" : "was not found"));
4271 auto GetSymbol
= [&](uint64_t SymIndex
,
4272 uint64_t SymsTotal
) -> const Elf_Sym
* {
4273 if (SymIndex
>= SymsTotal
) {
4274 this->reportUniqueWarning(
4275 "unable to print hashed symbol with index " + Twine(SymIndex
) +
4276 ", which is greater than or equal to the number of dynamic symbols "
4278 Twine::utohexstr(SymsTotal
) + ")");
4281 return FirstSym
+ SymIndex
;
4284 Expected
<ArrayRef
<Elf_Word
>> ValuesOrErr
=
4285 getGnuHashTableChains
<ELFT
>(this->DynSymRegion
, &GnuHash
);
4286 ArrayRef
<Elf_Word
> Values
;
4288 this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH "
4290 toString(ValuesOrErr
.takeError()));
4292 Values
= *ValuesOrErr
;
4294 DataRegion
<Elf_Word
> ShndxTable(
4295 (const Elf_Word
*)this->DynSymTabShndxRegion
.Addr
, this->Obj
.end());
4296 ArrayRef
<Elf_Word
> Buckets
= GnuHash
.buckets();
4297 for (uint32_t Buc
= 0; Buc
< GnuHash
.nbuckets
; Buc
++) {
4298 if (Buckets
[Buc
] == ELF::STN_UNDEF
)
4300 uint32_t Index
= Buckets
[Buc
];
4301 // Print whole chain.
4303 uint32_t SymIndex
= Index
++;
4304 if (const Elf_Sym
*Sym
= GetSymbol(SymIndex
, DynSyms
.size()))
4305 printHashedSymbol(Sym
, SymIndex
, ShndxTable
, this->DynamicStringTable
,
4310 if (SymIndex
< GnuHash
.symndx
) {
4311 this->reportUniqueWarning(
4312 "unable to read the hash value for symbol with index " +
4314 ", which is less than the index of the first hashed symbol (" +
4315 Twine(GnuHash
.symndx
) + ")");
4319 // Chain ends at symbol with stopper bit.
4320 if ((Values
[SymIndex
- GnuHash
.symndx
] & 1) == 1)
4326 template <class ELFT
> void GNUELFDumper
<ELFT
>::printHashSymbols() {
4327 if (this->HashTable
) {
4328 OS
<< "\n Symbol table of .hash for image:\n";
4329 if (Error E
= checkHashTable
<ELFT
>(*this, this->HashTable
))
4330 this->reportUniqueWarning(std::move(E
));
4332 printHashTableSymbols(*this->HashTable
);
4335 // Try printing the .gnu.hash table.
4336 if (this->GnuHashTable
) {
4337 OS
<< "\n Symbol table of .gnu.hash for image:\n";
4339 OS
<< " Num Buc: Value Size Type Bind Vis Ndx Name";
4341 OS
<< " Num Buc: Value Size Type Bind Vis Ndx Name";
4344 if (Error E
= checkGNUHashTable
<ELFT
>(this->Obj
, this->GnuHashTable
))
4345 this->reportUniqueWarning(std::move(E
));
4347 printGnuHashTableSymbols(*this->GnuHashTable
);
4351 template <class ELFT
> void GNUELFDumper
<ELFT
>::printSectionDetails() {
4352 ArrayRef
<Elf_Shdr
> Sections
= cantFail(this->Obj
.sections());
4353 if (Sections
.empty()) {
4354 OS
<< "\nThere are no sections in this file.\n";
4355 Expected
<StringRef
> SecStrTableOrErr
=
4356 this->Obj
.getSectionStringTable(Sections
, this->WarningHandler
);
4357 if (!SecStrTableOrErr
)
4358 this->reportUniqueWarning(SecStrTableOrErr
.takeError());
4361 OS
<< "There are " << to_string(Sections
.size())
4362 << " section headers, starting at offset "
4363 << "0x" << utohexstr(this->Obj
.getHeader().e_shoff
, /*LowerCase=*/true) << ":\n\n";
4365 OS
<< "Section Headers:\n";
4367 auto PrintFields
= [&](ArrayRef
<Field
> V
) {
4368 for (const Field
&F
: V
)
4373 PrintFields({{"[Nr]", 2}, {"Name", 7}});
4375 constexpr bool Is64
= ELFT::Is64Bits
;
4376 PrintFields({{"Type", 7},
4377 {Is64
? "Address" : "Addr", 23},
4378 {"Off", Is64
? 40 : 32},
4379 {"Size", Is64
? 47 : 39},
4380 {"ES", Is64
? 54 : 46},
4381 {"Lk", Is64
? 59 : 51},
4382 {"Inf", Is64
? 62 : 54},
4383 {"Al", Is64
? 66 : 57}});
4384 PrintFields({{"Flags", 7}});
4386 StringRef SecStrTable
;
4387 if (Expected
<StringRef
> SecStrTableOrErr
=
4388 this->Obj
.getSectionStringTable(Sections
, this->WarningHandler
))
4389 SecStrTable
= *SecStrTableOrErr
;
4391 this->reportUniqueWarning(SecStrTableOrErr
.takeError());
4393 size_t SectionIndex
= 0;
4394 const unsigned AddrSize
= Is64
? 16 : 8;
4395 for (const Elf_Shdr
&S
: Sections
) {
4396 StringRef Name
= "<?>";
4397 if (Expected
<StringRef
> NameOrErr
=
4398 this->Obj
.getSectionName(S
, SecStrTable
))
4401 this->reportUniqueWarning(NameOrErr
.takeError());
4404 OS
<< "[" << right_justify(to_string(SectionIndex
), 2) << "]";
4405 PrintFields({{Name
, 7}});
4407 {{getSectionTypeString(this->Obj
.getHeader().e_machine
, S
.sh_type
), 7},
4408 {to_string(format_hex_no_prefix(S
.sh_addr
, AddrSize
)), 23},
4409 {to_string(format_hex_no_prefix(S
.sh_offset
, 6)), Is64
? 39 : 32},
4410 {to_string(format_hex_no_prefix(S
.sh_size
, 6)), Is64
? 47 : 39},
4411 {to_string(format_hex_no_prefix(S
.sh_entsize
, 2)), Is64
? 54 : 46},
4412 {to_string(S
.sh_link
), Is64
? 59 : 51},
4413 {to_string(S
.sh_info
), Is64
? 63 : 55},
4414 {to_string(S
.sh_addralign
), Is64
? 66 : 58}});
4417 OS
<< "[" << to_string(format_hex_no_prefix(S
.sh_flags
, AddrSize
)) << "]: ";
4419 DenseMap
<unsigned, StringRef
> FlagToName
= {
4420 {SHF_WRITE
, "WRITE"}, {SHF_ALLOC
, "ALLOC"},
4421 {SHF_EXECINSTR
, "EXEC"}, {SHF_MERGE
, "MERGE"},
4422 {SHF_STRINGS
, "STRINGS"}, {SHF_INFO_LINK
, "INFO LINK"},
4423 {SHF_LINK_ORDER
, "LINK ORDER"}, {SHF_OS_NONCONFORMING
, "OS NONCONF"},
4424 {SHF_GROUP
, "GROUP"}, {SHF_TLS
, "TLS"},
4425 {SHF_COMPRESSED
, "COMPRESSED"}, {SHF_EXCLUDE
, "EXCLUDE"}};
4427 uint64_t Flags
= S
.sh_flags
;
4428 uint64_t UnknownFlags
= 0;
4431 // Take the least significant bit as a flag.
4432 uint64_t Flag
= Flags
& -Flags
;
4435 auto It
= FlagToName
.find(Flag
);
4436 if (It
!= FlagToName
.end())
4437 OS
<< LS
<< It
->second
;
4439 UnknownFlags
|= Flag
;
4442 auto PrintUnknownFlags
= [&](uint64_t Mask
, StringRef Name
) {
4443 uint64_t FlagsToPrint
= UnknownFlags
& Mask
;
4447 OS
<< LS
<< Name
<< " ("
4448 << to_string(format_hex_no_prefix(FlagsToPrint
, AddrSize
)) << ")";
4449 UnknownFlags
&= ~Mask
;
4452 PrintUnknownFlags(SHF_MASKOS
, "OS");
4453 PrintUnknownFlags(SHF_MASKPROC
, "PROC");
4454 PrintUnknownFlags(uint64_t(-1), "UNKNOWN");
4459 if (!(S
.sh_flags
& SHF_COMPRESSED
))
4461 Expected
<ArrayRef
<uint8_t>> Data
= this->Obj
.getSectionContents(S
);
4462 if (!Data
|| Data
->size() < sizeof(Elf_Chdr
)) {
4463 consumeError(Data
.takeError());
4464 reportWarning(createError("SHF_COMPRESSED section '" + Name
+
4465 "' does not have an Elf_Chdr header"),
4468 OS
<< "[<corrupt>]";
4471 auto *Chdr
= reinterpret_cast<const Elf_Chdr
*>(Data
->data());
4472 if (Chdr
->ch_type
== ELFCOMPRESS_ZLIB
)
4474 else if (Chdr
->ch_type
== ELFCOMPRESS_ZSTD
)
4477 OS
<< format("[<unknown>: 0x%x]", unsigned(Chdr
->ch_type
));
4478 OS
<< ", " << format_hex_no_prefix(Chdr
->ch_size
, ELFT::Is64Bits
? 16 : 8)
4479 << ", " << Chdr
->ch_addralign
;
4485 static inline std::string
printPhdrFlags(unsigned Flag
) {
4487 Str
= (Flag
& PF_R
) ? "R" : " ";
4488 Str
+= (Flag
& PF_W
) ? "W" : " ";
4489 Str
+= (Flag
& PF_X
) ? "E" : " ";
4493 template <class ELFT
>
4494 static bool checkTLSSections(const typename
ELFT::Phdr
&Phdr
,
4495 const typename
ELFT::Shdr
&Sec
) {
4496 if (Sec
.sh_flags
& ELF::SHF_TLS
) {
4497 // .tbss must only be shown in the PT_TLS segment.
4498 if (Sec
.sh_type
== ELF::SHT_NOBITS
)
4499 return Phdr
.p_type
== ELF::PT_TLS
;
4501 // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO
4503 return (Phdr
.p_type
== ELF::PT_TLS
) || (Phdr
.p_type
== ELF::PT_LOAD
) ||
4504 (Phdr
.p_type
== ELF::PT_GNU_RELRO
);
4507 // PT_TLS must only have SHF_TLS sections.
4508 return Phdr
.p_type
!= ELF::PT_TLS
;
4511 template <class ELFT
>
4512 static bool checkOffsets(const typename
ELFT::Phdr
&Phdr
,
4513 const typename
ELFT::Shdr
&Sec
) {
4514 // SHT_NOBITS sections don't need to have an offset inside the segment.
4515 if (Sec
.sh_type
== ELF::SHT_NOBITS
)
4518 if (Sec
.sh_offset
< Phdr
.p_offset
)
4521 // Only non-empty sections can be at the end of a segment.
4522 if (Sec
.sh_size
== 0)
4523 return (Sec
.sh_offset
+ 1 <= Phdr
.p_offset
+ Phdr
.p_filesz
);
4524 return Sec
.sh_offset
+ Sec
.sh_size
<= Phdr
.p_offset
+ Phdr
.p_filesz
;
4527 // Check that an allocatable section belongs to a virtual address
4528 // space of a segment.
4529 template <class ELFT
>
4530 static bool checkVMA(const typename
ELFT::Phdr
&Phdr
,
4531 const typename
ELFT::Shdr
&Sec
) {
4532 if (!(Sec
.sh_flags
& ELF::SHF_ALLOC
))
4535 if (Sec
.sh_addr
< Phdr
.p_vaddr
)
4539 (Sec
.sh_type
== ELF::SHT_NOBITS
) && ((Sec
.sh_flags
& ELF::SHF_TLS
) != 0);
4540 // .tbss is special, it only has memory in PT_TLS and has NOBITS properties.
4541 bool IsTbssInNonTLS
= IsTbss
&& Phdr
.p_type
!= ELF::PT_TLS
;
4542 // Only non-empty sections can be at the end of a segment.
4543 if (Sec
.sh_size
== 0 || IsTbssInNonTLS
)
4544 return Sec
.sh_addr
+ 1 <= Phdr
.p_vaddr
+ Phdr
.p_memsz
;
4545 return Sec
.sh_addr
+ Sec
.sh_size
<= Phdr
.p_vaddr
+ Phdr
.p_memsz
;
4548 template <class ELFT
>
4549 static bool checkPTDynamic(const typename
ELFT::Phdr
&Phdr
,
4550 const typename
ELFT::Shdr
&Sec
) {
4551 if (Phdr
.p_type
!= ELF::PT_DYNAMIC
|| Phdr
.p_memsz
== 0 || Sec
.sh_size
!= 0)
4554 // We get here when we have an empty section. Only non-empty sections can be
4555 // at the start or at the end of PT_DYNAMIC.
4556 // Is section within the phdr both based on offset and VMA?
4557 bool CheckOffset
= (Sec
.sh_type
== ELF::SHT_NOBITS
) ||
4558 (Sec
.sh_offset
> Phdr
.p_offset
&&
4559 Sec
.sh_offset
< Phdr
.p_offset
+ Phdr
.p_filesz
);
4560 bool CheckVA
= !(Sec
.sh_flags
& ELF::SHF_ALLOC
) ||
4561 (Sec
.sh_addr
> Phdr
.p_vaddr
&& Sec
.sh_addr
< Phdr
.p_memsz
);
4562 return CheckOffset
&& CheckVA
;
4565 template <class ELFT
>
4566 void GNUELFDumper
<ELFT
>::printProgramHeaders(
4567 bool PrintProgramHeaders
, cl::boolOrDefault PrintSectionMapping
) {
4568 const bool ShouldPrintSectionMapping
= (PrintSectionMapping
!= cl::BOU_FALSE
);
4569 // Exit early if no program header or section mapping details were requested.
4570 if (!PrintProgramHeaders
&& !ShouldPrintSectionMapping
)
4573 if (PrintProgramHeaders
) {
4574 const Elf_Ehdr
&Header
= this->Obj
.getHeader();
4575 if (Header
.e_phnum
== 0) {
4576 OS
<< "\nThere are no program headers in this file.\n";
4578 printProgramHeaders();
4582 if (ShouldPrintSectionMapping
)
4583 printSectionMapping();
4586 template <class ELFT
> void GNUELFDumper
<ELFT
>::printProgramHeaders() {
4587 unsigned Bias
= ELFT::Is64Bits
? 8 : 0;
4588 const Elf_Ehdr
&Header
= this->Obj
.getHeader();
4589 Field Fields
[8] = {2, 17, 26, 37 + Bias
,
4590 48 + Bias
, 56 + Bias
, 64 + Bias
, 68 + Bias
};
4591 OS
<< "\nElf file type is "
4592 << enumToString(Header
.e_type
, ArrayRef(ElfObjectFileType
)) << "\n"
4593 << "Entry point " << format_hex(Header
.e_entry
, 3) << "\n"
4594 << "There are " << Header
.e_phnum
<< " program headers,"
4595 << " starting at offset " << Header
.e_phoff
<< "\n\n"
4596 << "Program Headers:\n";
4598 OS
<< " Type Offset VirtAddr PhysAddr "
4599 << " FileSiz MemSiz Flg Align\n";
4601 OS
<< " Type Offset VirtAddr PhysAddr FileSiz "
4602 << "MemSiz Flg Align\n";
4604 unsigned Width
= ELFT::Is64Bits
? 18 : 10;
4605 unsigned SizeWidth
= ELFT::Is64Bits
? 8 : 7;
4607 Expected
<ArrayRef
<Elf_Phdr
>> PhdrsOrErr
= this->Obj
.program_headers();
4609 this->reportUniqueWarning("unable to dump program headers: " +
4610 toString(PhdrsOrErr
.takeError()));
4614 for (const Elf_Phdr
&Phdr
: *PhdrsOrErr
) {
4615 Fields
[0].Str
= getGNUPtType(Header
.e_machine
, Phdr
.p_type
);
4616 Fields
[1].Str
= to_string(format_hex(Phdr
.p_offset
, 8));
4617 Fields
[2].Str
= to_string(format_hex(Phdr
.p_vaddr
, Width
));
4618 Fields
[3].Str
= to_string(format_hex(Phdr
.p_paddr
, Width
));
4619 Fields
[4].Str
= to_string(format_hex(Phdr
.p_filesz
, SizeWidth
));
4620 Fields
[5].Str
= to_string(format_hex(Phdr
.p_memsz
, SizeWidth
));
4621 Fields
[6].Str
= printPhdrFlags(Phdr
.p_flags
);
4622 Fields
[7].Str
= to_string(format_hex(Phdr
.p_align
, 1));
4623 for (const Field
&F
: Fields
)
4625 if (Phdr
.p_type
== ELF::PT_INTERP
) {
4627 auto ReportBadInterp
= [&](const Twine
&Msg
) {
4628 this->reportUniqueWarning(
4629 "unable to read program interpreter name at offset 0x" +
4630 Twine::utohexstr(Phdr
.p_offset
) + ": " + Msg
);
4633 if (Phdr
.p_offset
>= this->Obj
.getBufSize()) {
4634 ReportBadInterp("it goes past the end of the file (0x" +
4635 Twine::utohexstr(this->Obj
.getBufSize()) + ")");
4640 reinterpret_cast<const char *>(this->Obj
.base()) + Phdr
.p_offset
;
4641 size_t MaxSize
= this->Obj
.getBufSize() - Phdr
.p_offset
;
4642 size_t Len
= strnlen(Data
, MaxSize
);
4643 if (Len
== MaxSize
) {
4644 ReportBadInterp("it is not null-terminated");
4648 OS
<< " [Requesting program interpreter: ";
4649 OS
<< StringRef(Data
, Len
) << "]";
4655 template <class ELFT
> void GNUELFDumper
<ELFT
>::printSectionMapping() {
4656 OS
<< "\n Section to Segment mapping:\n Segment Sections...\n";
4657 DenseSet
<const Elf_Shdr
*> BelongsToSegment
;
4660 Expected
<ArrayRef
<Elf_Phdr
>> PhdrsOrErr
= this->Obj
.program_headers();
4662 this->reportUniqueWarning(
4663 "can't read program headers to build section to segment mapping: " +
4664 toString(PhdrsOrErr
.takeError()));
4668 for (const Elf_Phdr
&Phdr
: *PhdrsOrErr
) {
4669 std::string Sections
;
4670 OS
<< format(" %2.2d ", Phnum
++);
4671 // Check if each section is in a segment and then print mapping.
4672 for (const Elf_Shdr
&Sec
: cantFail(this->Obj
.sections())) {
4673 if (Sec
.sh_type
== ELF::SHT_NULL
)
4676 // readelf additionally makes sure it does not print zero sized sections
4677 // at end of segments and for PT_DYNAMIC both start and end of section
4678 // .tbss must only be shown in PT_TLS section.
4679 if (checkTLSSections
<ELFT
>(Phdr
, Sec
) && checkOffsets
<ELFT
>(Phdr
, Sec
) &&
4680 checkVMA
<ELFT
>(Phdr
, Sec
) && checkPTDynamic
<ELFT
>(Phdr
, Sec
)) {
4682 unwrapOrError(this->FileName
, this->Obj
.getSectionName(Sec
)).str() +
4684 BelongsToSegment
.insert(&Sec
);
4687 OS
<< Sections
<< "\n";
4691 // Display sections that do not belong to a segment.
4692 std::string Sections
;
4693 for (const Elf_Shdr
&Sec
: cantFail(this->Obj
.sections())) {
4694 if (BelongsToSegment
.find(&Sec
) == BelongsToSegment
.end())
4696 unwrapOrError(this->FileName
, this->Obj
.getSectionName(Sec
)).str() +
4699 if (!Sections
.empty()) {
4700 OS
<< " None " << Sections
<< '\n';
4707 template <class ELFT
>
4708 RelSymbol
<ELFT
> getSymbolForReloc(const ELFDumper
<ELFT
> &Dumper
,
4709 const Relocation
<ELFT
> &Reloc
) {
4710 using Elf_Sym
= typename
ELFT::Sym
;
4711 auto WarnAndReturn
= [&](const Elf_Sym
*Sym
,
4712 const Twine
&Reason
) -> RelSymbol
<ELFT
> {
4713 Dumper
.reportUniqueWarning(
4714 "unable to get name of the dynamic symbol with index " +
4715 Twine(Reloc
.Symbol
) + ": " + Reason
);
4716 return {Sym
, "<corrupt>"};
4719 ArrayRef
<Elf_Sym
> Symbols
= Dumper
.dynamic_symbols();
4720 const Elf_Sym
*FirstSym
= Symbols
.begin();
4722 return WarnAndReturn(nullptr, "no dynamic symbol table found");
4724 // We might have an object without a section header. In this case the size of
4725 // Symbols is zero, because there is no way to know the size of the dynamic
4726 // table. We should allow this case and not print a warning.
4727 if (!Symbols
.empty() && Reloc
.Symbol
>= Symbols
.size())
4728 return WarnAndReturn(
4730 "index is greater than or equal to the number of dynamic symbols (" +
4731 Twine(Symbols
.size()) + ")");
4733 const ELFFile
<ELFT
> &Obj
= Dumper
.getElfObject().getELFFile();
4734 const uint64_t FileSize
= Obj
.getBufSize();
4735 const uint64_t SymOffset
= ((const uint8_t *)FirstSym
- Obj
.base()) +
4736 (uint64_t)Reloc
.Symbol
* sizeof(Elf_Sym
);
4737 if (SymOffset
+ sizeof(Elf_Sym
) > FileSize
)
4738 return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(SymOffset
) +
4739 " goes past the end of the file (0x" +
4740 Twine::utohexstr(FileSize
) + ")");
4742 const Elf_Sym
*Sym
= FirstSym
+ Reloc
.Symbol
;
4743 Expected
<StringRef
> ErrOrName
= Sym
->getName(Dumper
.getDynamicStringTable());
4745 return WarnAndReturn(Sym
, toString(ErrOrName
.takeError()));
4747 return {Sym
== FirstSym
? nullptr : Sym
, maybeDemangle(*ErrOrName
)};
4751 template <class ELFT
>
4752 static size_t getMaxDynamicTagSize(const ELFFile
<ELFT
> &Obj
,
4753 typename
ELFT::DynRange Tags
) {
4755 for (const typename
ELFT::Dyn
&Dyn
: Tags
)
4756 Max
= std::max(Max
, Obj
.getDynamicTagAsString(Dyn
.d_tag
).size());
4760 template <class ELFT
> void GNUELFDumper
<ELFT
>::printDynamicTable() {
4761 Elf_Dyn_Range Table
= this->dynamic_table();
4765 OS
<< "Dynamic section at offset "
4766 << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable
.Addr
) -
4769 << " contains " << Table
.size() << " entries:\n";
4771 // The type name is surrounded with round brackets, hence add 2.
4772 size_t MaxTagSize
= getMaxDynamicTagSize(this->Obj
, Table
) + 2;
4773 // The "Name/Value" column should be indented from the "Type" column by N
4774 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
4776 OS
<< " Tag" + std::string(ELFT::Is64Bits
? 16 : 8, ' ') + "Type"
4777 << std::string(MaxTagSize
- 3, ' ') << "Name/Value\n";
4779 std::string ValueFmt
= " %-" + std::to_string(MaxTagSize
) + "s ";
4780 for (auto Entry
: Table
) {
4781 uintX_t Tag
= Entry
.getTag();
4783 std::string("(") + this->Obj
.getDynamicTagAsString(Tag
) + ")";
4784 std::string Value
= this->getDynamicEntry(Tag
, Entry
.getVal());
4785 OS
<< " " << format_hex(Tag
, ELFT::Is64Bits
? 18 : 10)
4786 << format(ValueFmt
.c_str(), Type
.c_str()) << Value
<< "\n";
4790 template <class ELFT
> void GNUELFDumper
<ELFT
>::printDynamicRelocations() {
4791 this->printDynamicRelocationsHelper();
4794 template <class ELFT
>
4795 void ELFDumper
<ELFT
>::printDynamicReloc(const Relocation
<ELFT
> &R
) {
4796 printRelRelaReloc(R
, getSymbolForReloc(*this, R
));
4799 template <class ELFT
>
4800 void ELFDumper
<ELFT
>::printRelocationsHelper(const Elf_Shdr
&Sec
) {
4801 this->forEachRelocationDo(
4803 [&](const Relocation
<ELFT
> &R
, unsigned Ndx
, const Elf_Shdr
&Sec
,
4804 const Elf_Shdr
*SymTab
) { printReloc(R
, Ndx
, Sec
, SymTab
); },
4805 [&](const Elf_Relr
&R
) { printRelrReloc(R
); });
4808 template <class ELFT
> void ELFDumper
<ELFT
>::printDynamicRelocationsHelper() {
4809 const bool IsMips64EL
= this->Obj
.isMips64EL();
4810 if (this->DynRelaRegion
.Size
> 0) {
4811 printDynamicRelocHeader(ELF::SHT_RELA
, "RELA", this->DynRelaRegion
);
4812 for (const Elf_Rela
&Rela
:
4813 this->DynRelaRegion
.template getAsArrayRef
<Elf_Rela
>())
4814 printDynamicReloc(Relocation
<ELFT
>(Rela
, IsMips64EL
));
4817 if (this->DynRelRegion
.Size
> 0) {
4818 printDynamicRelocHeader(ELF::SHT_REL
, "REL", this->DynRelRegion
);
4819 for (const Elf_Rel
&Rel
:
4820 this->DynRelRegion
.template getAsArrayRef
<Elf_Rel
>())
4821 printDynamicReloc(Relocation
<ELFT
>(Rel
, IsMips64EL
));
4824 if (this->DynRelrRegion
.Size
> 0) {
4825 printDynamicRelocHeader(ELF::SHT_REL
, "RELR", this->DynRelrRegion
);
4826 Elf_Relr_Range Relrs
=
4827 this->DynRelrRegion
.template getAsArrayRef
<Elf_Relr
>();
4828 for (const Elf_Rel
&Rel
: Obj
.decode_relrs(Relrs
))
4829 printDynamicReloc(Relocation
<ELFT
>(Rel
, IsMips64EL
));
4832 if (this->DynPLTRelRegion
.Size
) {
4833 if (this->DynPLTRelRegion
.EntSize
== sizeof(Elf_Rela
)) {
4834 printDynamicRelocHeader(ELF::SHT_RELA
, "PLT", this->DynPLTRelRegion
);
4835 for (const Elf_Rela
&Rela
:
4836 this->DynPLTRelRegion
.template getAsArrayRef
<Elf_Rela
>())
4837 printDynamicReloc(Relocation
<ELFT
>(Rela
, IsMips64EL
));
4839 printDynamicRelocHeader(ELF::SHT_REL
, "PLT", this->DynPLTRelRegion
);
4840 for (const Elf_Rel
&Rel
:
4841 this->DynPLTRelRegion
.template getAsArrayRef
<Elf_Rel
>())
4842 printDynamicReloc(Relocation
<ELFT
>(Rel
, IsMips64EL
));
4847 template <class ELFT
>
4848 void GNUELFDumper
<ELFT
>::printGNUVersionSectionProlog(
4849 const typename
ELFT::Shdr
&Sec
, const Twine
&Label
, unsigned EntriesNum
) {
4850 // Don't inline the SecName, because it might report a warning to stderr and
4851 // corrupt the output.
4852 StringRef SecName
= this->getPrintableSectionName(Sec
);
4853 OS
<< Label
<< " section '" << SecName
<< "' "
4854 << "contains " << EntriesNum
<< " entries:\n";
4856 StringRef LinkedSecName
= "<corrupt>";
4857 if (Expected
<const typename
ELFT::Shdr
*> LinkedSecOrErr
=
4858 this->Obj
.getSection(Sec
.sh_link
))
4859 LinkedSecName
= this->getPrintableSectionName(**LinkedSecOrErr
);
4861 this->reportUniqueWarning("invalid section linked to " +
4862 this->describe(Sec
) + ": " +
4863 toString(LinkedSecOrErr
.takeError()));
4865 OS
<< " Addr: " << format_hex_no_prefix(Sec
.sh_addr
, 16)
4866 << " Offset: " << format_hex(Sec
.sh_offset
, 8)
4867 << " Link: " << Sec
.sh_link
<< " (" << LinkedSecName
<< ")\n";
4870 template <class ELFT
>
4871 void GNUELFDumper
<ELFT
>::printVersionSymbolSection(const Elf_Shdr
*Sec
) {
4875 printGNUVersionSectionProlog(*Sec
, "Version symbols",
4876 Sec
->sh_size
/ sizeof(Elf_Versym
));
4877 Expected
<ArrayRef
<Elf_Versym
>> VerTableOrErr
=
4878 this->getVersionTable(*Sec
, /*SymTab=*/nullptr,
4879 /*StrTab=*/nullptr, /*SymTabSec=*/nullptr);
4880 if (!VerTableOrErr
) {
4881 this->reportUniqueWarning(VerTableOrErr
.takeError());
4885 SmallVector
<std::optional
<VersionEntry
>, 0> *VersionMap
= nullptr;
4886 if (Expected
<SmallVector
<std::optional
<VersionEntry
>, 0> *> MapOrErr
=
4887 this->getVersionMap())
4888 VersionMap
= *MapOrErr
;
4890 this->reportUniqueWarning(MapOrErr
.takeError());
4892 ArrayRef
<Elf_Versym
> VerTable
= *VerTableOrErr
;
4893 std::vector
<StringRef
> Versions
;
4894 for (size_t I
= 0, E
= VerTable
.size(); I
< E
; ++I
) {
4895 unsigned Ndx
= VerTable
[I
].vs_index
;
4896 if (Ndx
== VER_NDX_LOCAL
|| Ndx
== VER_NDX_GLOBAL
) {
4897 Versions
.emplace_back(Ndx
== VER_NDX_LOCAL
? "*local*" : "*global*");
4902 Versions
.emplace_back("<corrupt>");
4907 Expected
<StringRef
> NameOrErr
= this->Obj
.getSymbolVersionByIndex(
4908 Ndx
, IsDefault
, *VersionMap
, /*IsSymHidden=*/std::nullopt
);
4910 this->reportUniqueWarning("unable to get a version for entry " +
4911 Twine(I
) + " of " + this->describe(*Sec
) +
4912 ": " + toString(NameOrErr
.takeError()));
4913 Versions
.emplace_back("<corrupt>");
4916 Versions
.emplace_back(*NameOrErr
);
4919 // readelf prints 4 entries per line.
4920 uint64_t Entries
= VerTable
.size();
4921 for (uint64_t VersymRow
= 0; VersymRow
< Entries
; VersymRow
+= 4) {
4922 OS
<< " " << format_hex_no_prefix(VersymRow
, 3) << ":";
4923 for (uint64_t I
= 0; (I
< 4) && (I
+ VersymRow
) < Entries
; ++I
) {
4924 unsigned Ndx
= VerTable
[VersymRow
+ I
].vs_index
;
4925 OS
<< format("%4x%c", Ndx
& VERSYM_VERSION
,
4926 Ndx
& VERSYM_HIDDEN
? 'h' : ' ');
4927 OS
<< left_justify("(" + std::string(Versions
[VersymRow
+ I
]) + ")", 13);
4934 static std::string
versionFlagToString(unsigned Flags
) {
4939 auto AddFlag
= [&Ret
, &Flags
](unsigned Flag
, StringRef Name
) {
4940 if (!(Flags
& Flag
))
4948 AddFlag(VER_FLG_BASE
, "BASE");
4949 AddFlag(VER_FLG_WEAK
, "WEAK");
4950 AddFlag(VER_FLG_INFO
, "INFO");
4951 AddFlag(~0, "<unknown>");
4955 template <class ELFT
>
4956 void GNUELFDumper
<ELFT
>::printVersionDefinitionSection(const Elf_Shdr
*Sec
) {
4960 printGNUVersionSectionProlog(*Sec
, "Version definition", Sec
->sh_info
);
4962 Expected
<std::vector
<VerDef
>> V
= this->Obj
.getVersionDefinitions(*Sec
);
4964 this->reportUniqueWarning(V
.takeError());
4968 for (const VerDef
&Def
: *V
) {
4969 OS
<< format(" 0x%04x: Rev: %u Flags: %s Index: %u Cnt: %u Name: %s\n",
4970 Def
.Offset
, Def
.Version
,
4971 versionFlagToString(Def
.Flags
).c_str(), Def
.Ndx
, Def
.Cnt
,
4974 for (const VerdAux
&Aux
: Def
.AuxV
)
4975 OS
<< format(" 0x%04x: Parent %u: %s\n", Aux
.Offset
, ++I
,
4982 template <class ELFT
>
4983 void GNUELFDumper
<ELFT
>::printVersionDependencySection(const Elf_Shdr
*Sec
) {
4987 unsigned VerneedNum
= Sec
->sh_info
;
4988 printGNUVersionSectionProlog(*Sec
, "Version needs", VerneedNum
);
4990 Expected
<std::vector
<VerNeed
>> V
=
4991 this->Obj
.getVersionDependencies(*Sec
, this->WarningHandler
);
4993 this->reportUniqueWarning(V
.takeError());
4997 for (const VerNeed
&VN
: *V
) {
4998 OS
<< format(" 0x%04x: Version: %u File: %s Cnt: %u\n", VN
.Offset
,
4999 VN
.Version
, VN
.File
.data(), VN
.Cnt
);
5000 for (const VernAux
&Aux
: VN
.AuxV
)
5001 OS
<< format(" 0x%04x: Name: %s Flags: %s Version: %u\n", Aux
.Offset
,
5002 Aux
.Name
.data(), versionFlagToString(Aux
.Flags
).c_str(),
5008 template <class ELFT
>
5009 void GNUELFDumper
<ELFT
>::printHashHistogramStats(size_t NBucket
,
5012 ArrayRef
<size_t> Count
,
5014 size_t CumulativeNonZero
= 0;
5015 OS
<< "Histogram for" << (IsGnu
? " `.gnu.hash'" : "")
5016 << " bucket list length (total of " << NBucket
<< " buckets)\n"
5017 << " Length Number % of total Coverage\n";
5018 for (size_t I
= 0; I
< MaxChain
; ++I
) {
5019 CumulativeNonZero
+= Count
[I
] * I
;
5020 OS
<< format("%7lu %-10lu (%5.1f%%) %5.1f%%\n", I
, Count
[I
],
5021 (Count
[I
] * 100.0) / NBucket
,
5022 (CumulativeNonZero
* 100.0) / TotalSyms
);
5026 template <class ELFT
> void GNUELFDumper
<ELFT
>::printCGProfile() {
5027 OS
<< "GNUStyle::printCGProfile not implemented\n";
5030 template <class ELFT
> void GNUELFDumper
<ELFT
>::printBBAddrMaps() {
5031 OS
<< "GNUStyle::printBBAddrMaps not implemented\n";
5034 static Expected
<std::vector
<uint64_t>> toULEB128Array(ArrayRef
<uint8_t> Data
) {
5035 std::vector
<uint64_t> Ret
;
5036 const uint8_t *Cur
= Data
.begin();
5037 const uint8_t *End
= Data
.end();
5038 while (Cur
!= End
) {
5041 Ret
.push_back(decodeULEB128(Cur
, &Size
, End
, &Err
));
5043 return createError(Err
);
5049 template <class ELFT
>
5050 static Expected
<std::vector
<uint64_t>>
5051 decodeAddrsigSection(const ELFFile
<ELFT
> &Obj
, const typename
ELFT::Shdr
&Sec
) {
5052 Expected
<ArrayRef
<uint8_t>> ContentsOrErr
= Obj
.getSectionContents(Sec
);
5054 return ContentsOrErr
.takeError();
5056 if (Expected
<std::vector
<uint64_t>> SymsOrErr
=
5057 toULEB128Array(*ContentsOrErr
))
5060 return createError("unable to decode " + describe(Obj
, Sec
) + ": " +
5061 toString(SymsOrErr
.takeError()));
5064 template <class ELFT
> void GNUELFDumper
<ELFT
>::printAddrsig() {
5065 if (!this->DotAddrsigSec
)
5068 Expected
<std::vector
<uint64_t>> SymsOrErr
=
5069 decodeAddrsigSection(this->Obj
, *this->DotAddrsigSec
);
5071 this->reportUniqueWarning(SymsOrErr
.takeError());
5075 StringRef Name
= this->getPrintableSectionName(*this->DotAddrsigSec
);
5076 OS
<< "\nAddress-significant symbols section '" << Name
<< "'"
5077 << " contains " << SymsOrErr
->size() << " entries:\n";
5078 OS
<< " Num: Name\n";
5080 Field Fields
[2] = {0, 8};
5081 size_t SymIndex
= 0;
5082 for (uint64_t Sym
: *SymsOrErr
) {
5083 Fields
[0].Str
= to_string(format_decimal(++SymIndex
, 6)) + ":";
5084 Fields
[1].Str
= this->getStaticSymbolName(Sym
);
5085 for (const Field
&Entry
: Fields
)
5091 template <typename ELFT
>
5092 static std::string
getGNUProperty(uint32_t Type
, uint32_t DataSize
,
5093 ArrayRef
<uint8_t> Data
) {
5095 raw_string_ostream
OS(str
);
5097 auto DumpBit
= [&](uint32_t Flag
, StringRef Name
) {
5098 if (PrData
& Flag
) {
5108 OS
<< format("<application-specific type 0x%x>", Type
);
5110 case GNU_PROPERTY_STACK_SIZE
: {
5111 OS
<< "stack size: ";
5112 if (DataSize
== sizeof(typename
ELFT::uint
))
5113 OS
<< formatv("{0:x}",
5114 (uint64_t)(*(const typename
ELFT::Addr
*)Data
.data()));
5116 OS
<< format("<corrupt length: 0x%x>", DataSize
);
5119 case GNU_PROPERTY_NO_COPY_ON_PROTECTED
:
5120 OS
<< "no copy on protected";
5122 OS
<< format(" <corrupt length: 0x%x>", DataSize
);
5124 case GNU_PROPERTY_AARCH64_FEATURE_1_AND
:
5125 case GNU_PROPERTY_X86_FEATURE_1_AND
:
5126 OS
<< ((Type
== GNU_PROPERTY_AARCH64_FEATURE_1_AND
) ? "aarch64 feature: "
5128 if (DataSize
!= 4) {
5129 OS
<< format("<corrupt length: 0x%x>", DataSize
);
5132 PrData
= support::endian::read32
<ELFT::TargetEndianness
>(Data
.data());
5137 if (Type
== GNU_PROPERTY_AARCH64_FEATURE_1_AND
) {
5138 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI
, "BTI");
5139 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC
, "PAC");
5141 DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT
, "IBT");
5142 DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK
, "SHSTK");
5145 OS
<< format("<unknown flags: 0x%x>", PrData
);
5147 case GNU_PROPERTY_X86_FEATURE_2_NEEDED
:
5148 case GNU_PROPERTY_X86_FEATURE_2_USED
:
5149 OS
<< "x86 feature "
5150 << (Type
== GNU_PROPERTY_X86_FEATURE_2_NEEDED
? "needed: " : "used: ");
5151 if (DataSize
!= 4) {
5152 OS
<< format("<corrupt length: 0x%x>", DataSize
);
5155 PrData
= support::endian::read32
<ELFT::TargetEndianness
>(Data
.data());
5160 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86
, "x86");
5161 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87
, "x87");
5162 DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX
, "MMX");
5163 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM
, "XMM");
5164 DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM
, "YMM");
5165 DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM
, "ZMM");
5166 DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR
, "FXSR");
5167 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE
, "XSAVE");
5168 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT
, "XSAVEOPT");
5169 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC
, "XSAVEC");
5171 OS
<< format("<unknown flags: 0x%x>", PrData
);
5173 case GNU_PROPERTY_X86_ISA_1_NEEDED
:
5174 case GNU_PROPERTY_X86_ISA_1_USED
:
5176 << (Type
== GNU_PROPERTY_X86_ISA_1_NEEDED
? "needed: " : "used: ");
5177 if (DataSize
!= 4) {
5178 OS
<< format("<corrupt length: 0x%x>", DataSize
);
5181 PrData
= support::endian::read32
<ELFT::TargetEndianness
>(Data
.data());
5186 DumpBit(GNU_PROPERTY_X86_ISA_1_BASELINE
, "x86-64-baseline");
5187 DumpBit(GNU_PROPERTY_X86_ISA_1_V2
, "x86-64-v2");
5188 DumpBit(GNU_PROPERTY_X86_ISA_1_V3
, "x86-64-v3");
5189 DumpBit(GNU_PROPERTY_X86_ISA_1_V4
, "x86-64-v4");
5191 OS
<< format("<unknown flags: 0x%x>", PrData
);
5196 template <typename ELFT
>
5197 static SmallVector
<std::string
, 4> getGNUPropertyList(ArrayRef
<uint8_t> Arr
) {
5198 using Elf_Word
= typename
ELFT::Word
;
5200 SmallVector
<std::string
, 4> Properties
;
5201 while (Arr
.size() >= 8) {
5202 uint32_t Type
= *reinterpret_cast<const Elf_Word
*>(Arr
.data());
5203 uint32_t DataSize
= *reinterpret_cast<const Elf_Word
*>(Arr
.data() + 4);
5204 Arr
= Arr
.drop_front(8);
5206 // Take padding size into account if present.
5207 uint64_t PaddedSize
= alignTo(DataSize
, sizeof(typename
ELFT::uint
));
5209 raw_string_ostream
OS(str
);
5210 if (Arr
.size() < PaddedSize
) {
5211 OS
<< format("<corrupt type (0x%x) datasz: 0x%x>", Type
, DataSize
);
5212 Properties
.push_back(OS
.str());
5215 Properties
.push_back(
5216 getGNUProperty
<ELFT
>(Type
, DataSize
, Arr
.take_front(PaddedSize
)));
5217 Arr
= Arr
.drop_front(PaddedSize
);
5221 Properties
.push_back("<corrupted GNU_PROPERTY_TYPE_0>");
5232 template <typename ELFT
> static GNUAbiTag
getGNUAbiTag(ArrayRef
<uint8_t> Desc
) {
5233 typedef typename
ELFT::Word Elf_Word
;
5235 ArrayRef
<Elf_Word
> Words(reinterpret_cast<const Elf_Word
*>(Desc
.begin()),
5236 reinterpret_cast<const Elf_Word
*>(Desc
.end()));
5238 if (Words
.size() < 4)
5239 return {"", "", /*IsValid=*/false};
5241 static const char *OSNames
[] = {
5242 "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable", "NaCl",
5244 StringRef OSName
= "Unknown";
5245 if (Words
[0] < std::size(OSNames
))
5246 OSName
= OSNames
[Words
[0]];
5247 uint32_t Major
= Words
[1], Minor
= Words
[2], Patch
= Words
[3];
5249 raw_string_ostream
ABI(str
);
5250 ABI
<< Major
<< "." << Minor
<< "." << Patch
;
5251 return {std::string(OSName
), ABI
.str(), /*IsValid=*/true};
5254 static std::string
getGNUBuildId(ArrayRef
<uint8_t> Desc
) {
5256 raw_string_ostream
OS(str
);
5257 for (uint8_t B
: Desc
)
5258 OS
<< format_hex_no_prefix(B
, 2);
5262 static StringRef
getDescAsStringRef(ArrayRef
<uint8_t> Desc
) {
5263 return StringRef(reinterpret_cast<const char *>(Desc
.data()), Desc
.size());
5266 template <typename ELFT
>
5267 static bool printGNUNote(raw_ostream
&OS
, uint32_t NoteType
,
5268 ArrayRef
<uint8_t> Desc
) {
5269 // Return true if we were able to pretty-print the note, false otherwise.
5273 case ELF::NT_GNU_ABI_TAG
: {
5274 const GNUAbiTag
&AbiTag
= getGNUAbiTag
<ELFT
>(Desc
);
5275 if (!AbiTag
.IsValid
)
5276 OS
<< " <corrupt GNU_ABI_TAG>";
5278 OS
<< " OS: " << AbiTag
.OSName
<< ", ABI: " << AbiTag
.ABI
;
5281 case ELF::NT_GNU_BUILD_ID
: {
5282 OS
<< " Build ID: " << getGNUBuildId(Desc
);
5285 case ELF::NT_GNU_GOLD_VERSION
:
5286 OS
<< " Version: " << getDescAsStringRef(Desc
);
5288 case ELF::NT_GNU_PROPERTY_TYPE_0
:
5289 OS
<< " Properties:";
5290 for (const std::string
&Property
: getGNUPropertyList
<ELFT
>(Desc
))
5291 OS
<< " " << Property
<< "\n";
5298 using AndroidNoteProperties
= std::vector
<std::pair
<StringRef
, std::string
>>;
5299 static AndroidNoteProperties
getAndroidNoteProperties(uint32_t NoteType
,
5300 ArrayRef
<uint8_t> Desc
) {
5301 AndroidNoteProperties Props
;
5303 case ELF::NT_ANDROID_TYPE_MEMTAG
:
5305 Props
.emplace_back("Invalid .note.android.memtag", "");
5309 switch (Desc
[0] & NT_MEMTAG_LEVEL_MASK
) {
5310 case NT_MEMTAG_LEVEL_NONE
:
5311 Props
.emplace_back("Tagging Mode", "NONE");
5313 case NT_MEMTAG_LEVEL_ASYNC
:
5314 Props
.emplace_back("Tagging Mode", "ASYNC");
5316 case NT_MEMTAG_LEVEL_SYNC
:
5317 Props
.emplace_back("Tagging Mode", "SYNC");
5322 ("Unknown (" + Twine::utohexstr(Desc
[0] & NT_MEMTAG_LEVEL_MASK
) + ")")
5326 Props
.emplace_back("Heap",
5327 (Desc
[0] & NT_MEMTAG_HEAP
) ? "Enabled" : "Disabled");
5328 Props
.emplace_back("Stack",
5329 (Desc
[0] & NT_MEMTAG_STACK
) ? "Enabled" : "Disabled");
5337 static bool printAndroidNote(raw_ostream
&OS
, uint32_t NoteType
,
5338 ArrayRef
<uint8_t> Desc
) {
5339 // Return true if we were able to pretty-print the note, false otherwise.
5340 AndroidNoteProperties Props
= getAndroidNoteProperties(NoteType
, Desc
);
5343 for (const auto &KV
: Props
)
5344 OS
<< " " << KV
.first
<< ": " << KV
.second
<< '\n';
5348 template <class ELFT
>
5349 void GNUELFDumper
<ELFT
>::printMemtag(
5350 const ArrayRef
<std::pair
<std::string
, std::string
>> DynamicEntries
,
5351 const ArrayRef
<uint8_t> AndroidNoteDesc
,
5352 const ArrayRef
<std::pair
<uint64_t, uint64_t>> Descriptors
) {
5353 OS
<< "Memtag Dynamic Entries:\n";
5354 if (DynamicEntries
.empty())
5355 OS
<< " < none found >\n";
5356 for (const auto &DynamicEntryKV
: DynamicEntries
)
5357 OS
<< " " << DynamicEntryKV
.first
<< ": " << DynamicEntryKV
.second
5360 if (!AndroidNoteDesc
.empty()) {
5361 OS
<< "Memtag Android Note:\n";
5362 printAndroidNote(OS
, ELF::NT_ANDROID_TYPE_MEMTAG
, AndroidNoteDesc
);
5365 if (Descriptors
.empty())
5368 OS
<< "Memtag Global Descriptors:\n";
5369 for (const auto &[Addr
, BytesToTag
] : Descriptors
) {
5370 OS
<< " 0x" << utohexstr(Addr
, /*LowerCase=*/true) << ": 0x"
5371 << utohexstr(BytesToTag
, /*LowerCase=*/true) << "\n";
5375 template <typename ELFT
>
5376 static bool printLLVMOMPOFFLOADNote(raw_ostream
&OS
, uint32_t NoteType
,
5377 ArrayRef
<uint8_t> Desc
) {
5381 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION
:
5382 OS
<< " Version: " << getDescAsStringRef(Desc
);
5384 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER
:
5385 OS
<< " Producer: " << getDescAsStringRef(Desc
);
5387 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION
:
5388 OS
<< " Producer version: " << getDescAsStringRef(Desc
);
5395 const EnumEntry
<unsigned> FreeBSDFeatureCtlFlags
[] = {
5396 {"ASLR_DISABLE", NT_FREEBSD_FCTL_ASLR_DISABLE
},
5397 {"PROTMAX_DISABLE", NT_FREEBSD_FCTL_PROTMAX_DISABLE
},
5398 {"STKGAP_DISABLE", NT_FREEBSD_FCTL_STKGAP_DISABLE
},
5399 {"WXNEEDED", NT_FREEBSD_FCTL_WXNEEDED
},
5400 {"LA48", NT_FREEBSD_FCTL_LA48
},
5401 {"ASG_DISABLE", NT_FREEBSD_FCTL_ASG_DISABLE
},
5404 struct FreeBSDNote
{
5409 template <typename ELFT
>
5410 static std::optional
<FreeBSDNote
>
5411 getFreeBSDNote(uint32_t NoteType
, ArrayRef
<uint8_t> Desc
, bool IsCore
) {
5413 return std::nullopt
; // No pretty-printing yet.
5415 case ELF::NT_FREEBSD_ABI_TAG
:
5416 if (Desc
.size() != 4)
5417 return std::nullopt
;
5420 utostr(support::endian::read32
<ELFT::TargetEndianness
>(Desc
.data()))};
5421 case ELF::NT_FREEBSD_ARCH_TAG
:
5422 return FreeBSDNote
{"Arch tag", toStringRef(Desc
).str()};
5423 case ELF::NT_FREEBSD_FEATURE_CTL
: {
5424 if (Desc
.size() != 4)
5425 return std::nullopt
;
5427 support::endian::read32
<ELFT::TargetEndianness
>(Desc
.data());
5428 std::string FlagsStr
;
5429 raw_string_ostream
OS(FlagsStr
);
5430 printFlags(Value
, ArrayRef(FreeBSDFeatureCtlFlags
), OS
);
5431 if (OS
.str().empty())
5432 OS
<< "0x" << utohexstr(Value
);
5434 OS
<< "(0x" << utohexstr(Value
) << ")";
5435 return FreeBSDNote
{"Feature flags", OS
.str()};
5438 return std::nullopt
;
5447 template <typename ELFT
>
5448 static AMDNote
getAMDNote(uint32_t NoteType
, ArrayRef
<uint8_t> Desc
) {
5452 case ELF::NT_AMD_HSA_CODE_OBJECT_VERSION
: {
5453 struct CodeObjectVersion
{
5454 uint32_t MajorVersion
;
5455 uint32_t MinorVersion
;
5457 if (Desc
.size() != sizeof(CodeObjectVersion
))
5458 return {"AMD HSA Code Object Version",
5459 "Invalid AMD HSA Code Object Version"};
5460 std::string VersionString
;
5461 raw_string_ostream
StrOS(VersionString
);
5462 auto Version
= reinterpret_cast<const CodeObjectVersion
*>(Desc
.data());
5463 StrOS
<< "[Major: " << Version
->MajorVersion
5464 << ", Minor: " << Version
->MinorVersion
<< "]";
5465 return {"AMD HSA Code Object Version", VersionString
};
5467 case ELF::NT_AMD_HSA_HSAIL
: {
5468 struct HSAILProperties
{
5469 uint32_t HSAILMajorVersion
;
5470 uint32_t HSAILMinorVersion
;
5472 uint8_t MachineModel
;
5473 uint8_t DefaultFloatRound
;
5475 if (Desc
.size() != sizeof(HSAILProperties
))
5476 return {"AMD HSA HSAIL Properties", "Invalid AMD HSA HSAIL Properties"};
5477 auto Properties
= reinterpret_cast<const HSAILProperties
*>(Desc
.data());
5478 std::string HSAILPropetiesString
;
5479 raw_string_ostream
StrOS(HSAILPropetiesString
);
5480 StrOS
<< "[HSAIL Major: " << Properties
->HSAILMajorVersion
5481 << ", HSAIL Minor: " << Properties
->HSAILMinorVersion
5482 << ", Profile: " << uint32_t(Properties
->Profile
)
5483 << ", Machine Model: " << uint32_t(Properties
->MachineModel
)
5484 << ", Default Float Round: "
5485 << uint32_t(Properties
->DefaultFloatRound
) << "]";
5486 return {"AMD HSA HSAIL Properties", HSAILPropetiesString
};
5488 case ELF::NT_AMD_HSA_ISA_VERSION
: {
5490 uint16_t VendorNameSize
;
5491 uint16_t ArchitectureNameSize
;
5496 if (Desc
.size() < sizeof(IsaVersion
))
5497 return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"};
5498 auto Isa
= reinterpret_cast<const IsaVersion
*>(Desc
.data());
5499 if (Desc
.size() < sizeof(IsaVersion
) +
5500 Isa
->VendorNameSize
+ Isa
->ArchitectureNameSize
||
5501 Isa
->VendorNameSize
== 0 || Isa
->ArchitectureNameSize
== 0)
5502 return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"};
5503 std::string IsaString
;
5504 raw_string_ostream
StrOS(IsaString
);
5505 StrOS
<< "[Vendor: "
5506 << StringRef((const char*)Desc
.data() + sizeof(IsaVersion
), Isa
->VendorNameSize
- 1)
5507 << ", Architecture: "
5508 << StringRef((const char*)Desc
.data() + sizeof(IsaVersion
) + Isa
->VendorNameSize
,
5509 Isa
->ArchitectureNameSize
- 1)
5510 << ", Major: " << Isa
->Major
<< ", Minor: " << Isa
->Minor
5511 << ", Stepping: " << Isa
->Stepping
<< "]";
5512 return {"AMD HSA ISA Version", IsaString
};
5514 case ELF::NT_AMD_HSA_METADATA
: {
5515 if (Desc
.size() == 0)
5516 return {"AMD HSA Metadata", ""};
5519 std::string(reinterpret_cast<const char *>(Desc
.data()), Desc
.size() - 1)};
5521 case ELF::NT_AMD_HSA_ISA_NAME
: {
5522 if (Desc
.size() == 0)
5523 return {"AMD HSA ISA Name", ""};
5526 std::string(reinterpret_cast<const char *>(Desc
.data()), Desc
.size())};
5528 case ELF::NT_AMD_PAL_METADATA
: {
5529 struct PALMetadata
{
5533 if (Desc
.size() % sizeof(PALMetadata
) != 0)
5534 return {"AMD PAL Metadata", "Invalid AMD PAL Metadata"};
5535 auto Isa
= reinterpret_cast<const PALMetadata
*>(Desc
.data());
5536 std::string MetadataString
;
5537 raw_string_ostream
StrOS(MetadataString
);
5538 for (size_t I
= 0, E
= Desc
.size() / sizeof(PALMetadata
); I
< E
; ++I
) {
5539 StrOS
<< "[" << Isa
[I
].Key
<< ": " << Isa
[I
].Value
<< "]";
5541 return {"AMD PAL Metadata", MetadataString
};
5551 template <typename ELFT
>
5552 static AMDGPUNote
getAMDGPUNote(uint32_t NoteType
, ArrayRef
<uint8_t> Desc
) {
5556 case ELF::NT_AMDGPU_METADATA
: {
5557 StringRef MsgPackString
=
5558 StringRef(reinterpret_cast<const char *>(Desc
.data()), Desc
.size());
5559 msgpack::Document MsgPackDoc
;
5560 if (!MsgPackDoc
.readFromBlob(MsgPackString
, /*Multi=*/false))
5563 std::string MetadataString
;
5565 // FIXME: Metadata Verifier only works with AMDHSA.
5566 // This is an ugly workaround to avoid the verifier for other MD
5567 // formats (e.g. amdpal)
5568 if (MsgPackString
.contains("amdhsa.")) {
5569 AMDGPU::HSAMD::V3::MetadataVerifier
Verifier(true);
5570 if (!Verifier
.verify(MsgPackDoc
.getRoot()))
5571 MetadataString
= "Invalid AMDGPU Metadata\n";
5574 raw_string_ostream
StrOS(MetadataString
);
5575 if (MsgPackDoc
.getRoot().isScalar()) {
5576 // TODO: passing a scalar root to toYAML() asserts:
5577 // (PolymorphicTraits<T>::getKind(Val) != NodeKind::Scalar &&
5578 // "plain scalar documents are not supported")
5579 // To avoid this crash we print the raw data instead.
5582 MsgPackDoc
.toYAML(StrOS
);
5583 return {"AMDGPU Metadata", StrOS
.str()};
5588 struct CoreFileMapping
{
5589 uint64_t Start
, End
, Offset
;
5595 std::vector
<CoreFileMapping
> Mappings
;
5598 static Expected
<CoreNote
> readCoreNote(DataExtractor Desc
) {
5599 // Expected format of the NT_FILE note description:
5600 // 1. # of file mappings (call it N)
5602 // 3. N (start, end, offset) triples
5603 // 4. N packed filenames (null delimited)
5604 // Each field is an Elf_Addr, except for filenames which are char* strings.
5607 const int Bytes
= Desc
.getAddressSize();
5609 if (!Desc
.isValidOffsetForAddress(2))
5610 return createError("the note of size 0x" + Twine::utohexstr(Desc
.size()) +
5611 " is too short, expected at least 0x" +
5612 Twine::utohexstr(Bytes
* 2));
5613 if (Desc
.getData().back() != 0)
5614 return createError("the note is not NUL terminated");
5616 uint64_t DescOffset
= 0;
5617 uint64_t FileCount
= Desc
.getAddress(&DescOffset
);
5618 Ret
.PageSize
= Desc
.getAddress(&DescOffset
);
5620 if (!Desc
.isValidOffsetForAddress(3 * FileCount
* Bytes
))
5621 return createError("unable to read file mappings (found " +
5622 Twine(FileCount
) + "): the note of size 0x" +
5623 Twine::utohexstr(Desc
.size()) + " is too short");
5625 uint64_t FilenamesOffset
= 0;
5626 DataExtractor
Filenames(
5627 Desc
.getData().drop_front(DescOffset
+ 3 * FileCount
* Bytes
),
5628 Desc
.isLittleEndian(), Desc
.getAddressSize());
5630 Ret
.Mappings
.resize(FileCount
);
5632 for (CoreFileMapping
&Mapping
: Ret
.Mappings
) {
5634 if (!Filenames
.isValidOffsetForDataOfSize(FilenamesOffset
, 1))
5636 "unable to read the file name for the mapping with index " +
5637 Twine(I
) + ": the note of size 0x" + Twine::utohexstr(Desc
.size()) +
5639 Mapping
.Start
= Desc
.getAddress(&DescOffset
);
5640 Mapping
.End
= Desc
.getAddress(&DescOffset
);
5641 Mapping
.Offset
= Desc
.getAddress(&DescOffset
);
5642 Mapping
.Filename
= Filenames
.getCStrRef(&FilenamesOffset
);
5648 template <typename ELFT
>
5649 static void printCoreNote(raw_ostream
&OS
, const CoreNote
&Note
) {
5650 // Length of "0x<address>" string.
5651 const int FieldWidth
= ELFT::Is64Bits
? 18 : 10;
5653 OS
<< " Page size: " << format_decimal(Note
.PageSize
, 0) << '\n';
5654 OS
<< " " << right_justify("Start", FieldWidth
) << " "
5655 << right_justify("End", FieldWidth
) << " "
5656 << right_justify("Page Offset", FieldWidth
) << '\n';
5657 for (const CoreFileMapping
&Mapping
: Note
.Mappings
) {
5658 OS
<< " " << format_hex(Mapping
.Start
, FieldWidth
) << " "
5659 << format_hex(Mapping
.End
, FieldWidth
) << " "
5660 << format_hex(Mapping
.Offset
, FieldWidth
) << "\n "
5661 << Mapping
.Filename
<< '\n';
5665 const NoteType GenericNoteTypes
[] = {
5666 {ELF::NT_VERSION
, "NT_VERSION (version)"},
5667 {ELF::NT_ARCH
, "NT_ARCH (architecture)"},
5668 {ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN
, "OPEN"},
5669 {ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC
, "func"},
5672 const NoteType GNUNoteTypes
[] = {
5673 {ELF::NT_GNU_ABI_TAG
, "NT_GNU_ABI_TAG (ABI version tag)"},
5674 {ELF::NT_GNU_HWCAP
, "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"},
5675 {ELF::NT_GNU_BUILD_ID
, "NT_GNU_BUILD_ID (unique build ID bitstring)"},
5676 {ELF::NT_GNU_GOLD_VERSION
, "NT_GNU_GOLD_VERSION (gold version)"},
5677 {ELF::NT_GNU_PROPERTY_TYPE_0
, "NT_GNU_PROPERTY_TYPE_0 (property note)"},
5680 const NoteType FreeBSDCoreNoteTypes
[] = {
5681 {ELF::NT_FREEBSD_THRMISC
, "NT_THRMISC (thrmisc structure)"},
5682 {ELF::NT_FREEBSD_PROCSTAT_PROC
, "NT_PROCSTAT_PROC (proc data)"},
5683 {ELF::NT_FREEBSD_PROCSTAT_FILES
, "NT_PROCSTAT_FILES (files data)"},
5684 {ELF::NT_FREEBSD_PROCSTAT_VMMAP
, "NT_PROCSTAT_VMMAP (vmmap data)"},
5685 {ELF::NT_FREEBSD_PROCSTAT_GROUPS
, "NT_PROCSTAT_GROUPS (groups data)"},
5686 {ELF::NT_FREEBSD_PROCSTAT_UMASK
, "NT_PROCSTAT_UMASK (umask data)"},
5687 {ELF::NT_FREEBSD_PROCSTAT_RLIMIT
, "NT_PROCSTAT_RLIMIT (rlimit data)"},
5688 {ELF::NT_FREEBSD_PROCSTAT_OSREL
, "NT_PROCSTAT_OSREL (osreldate data)"},
5689 {ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS
,
5690 "NT_PROCSTAT_PSSTRINGS (ps_strings data)"},
5691 {ELF::NT_FREEBSD_PROCSTAT_AUXV
, "NT_PROCSTAT_AUXV (auxv data)"},
5694 const NoteType FreeBSDNoteTypes
[] = {
5695 {ELF::NT_FREEBSD_ABI_TAG
, "NT_FREEBSD_ABI_TAG (ABI version tag)"},
5696 {ELF::NT_FREEBSD_NOINIT_TAG
, "NT_FREEBSD_NOINIT_TAG (no .init tag)"},
5697 {ELF::NT_FREEBSD_ARCH_TAG
, "NT_FREEBSD_ARCH_TAG (architecture tag)"},
5698 {ELF::NT_FREEBSD_FEATURE_CTL
,
5699 "NT_FREEBSD_FEATURE_CTL (FreeBSD feature control)"},
5702 const NoteType NetBSDCoreNoteTypes
[] = {
5703 {ELF::NT_NETBSDCORE_PROCINFO
,
5704 "NT_NETBSDCORE_PROCINFO (procinfo structure)"},
5705 {ELF::NT_NETBSDCORE_AUXV
, "NT_NETBSDCORE_AUXV (ELF auxiliary vector data)"},
5706 {ELF::NT_NETBSDCORE_LWPSTATUS
, "PT_LWPSTATUS (ptrace_lwpstatus structure)"},
5709 const NoteType OpenBSDCoreNoteTypes
[] = {
5710 {ELF::NT_OPENBSD_PROCINFO
, "NT_OPENBSD_PROCINFO (procinfo structure)"},
5711 {ELF::NT_OPENBSD_AUXV
, "NT_OPENBSD_AUXV (ELF auxiliary vector data)"},
5712 {ELF::NT_OPENBSD_REGS
, "NT_OPENBSD_REGS (regular registers)"},
5713 {ELF::NT_OPENBSD_FPREGS
, "NT_OPENBSD_FPREGS (floating point registers)"},
5714 {ELF::NT_OPENBSD_WCOOKIE
, "NT_OPENBSD_WCOOKIE (window cookie)"},
5717 const NoteType AMDNoteTypes
[] = {
5718 {ELF::NT_AMD_HSA_CODE_OBJECT_VERSION
,
5719 "NT_AMD_HSA_CODE_OBJECT_VERSION (AMD HSA Code Object Version)"},
5720 {ELF::NT_AMD_HSA_HSAIL
, "NT_AMD_HSA_HSAIL (AMD HSA HSAIL Properties)"},
5721 {ELF::NT_AMD_HSA_ISA_VERSION
, "NT_AMD_HSA_ISA_VERSION (AMD HSA ISA Version)"},
5722 {ELF::NT_AMD_HSA_METADATA
, "NT_AMD_HSA_METADATA (AMD HSA Metadata)"},
5723 {ELF::NT_AMD_HSA_ISA_NAME
, "NT_AMD_HSA_ISA_NAME (AMD HSA ISA Name)"},
5724 {ELF::NT_AMD_PAL_METADATA
, "NT_AMD_PAL_METADATA (AMD PAL Metadata)"},
5727 const NoteType AMDGPUNoteTypes
[] = {
5728 {ELF::NT_AMDGPU_METADATA
, "NT_AMDGPU_METADATA (AMDGPU Metadata)"},
5731 const NoteType LLVMOMPOFFLOADNoteTypes
[] = {
5732 {ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION
,
5733 "NT_LLVM_OPENMP_OFFLOAD_VERSION (image format version)"},
5734 {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER
,
5735 "NT_LLVM_OPENMP_OFFLOAD_PRODUCER (producing toolchain)"},
5736 {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION
,
5737 "NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION (producing toolchain version)"},
5740 const NoteType AndroidNoteTypes
[] = {
5741 {ELF::NT_ANDROID_TYPE_IDENT
, "NT_ANDROID_TYPE_IDENT"},
5742 {ELF::NT_ANDROID_TYPE_KUSER
, "NT_ANDROID_TYPE_KUSER"},
5743 {ELF::NT_ANDROID_TYPE_MEMTAG
,
5744 "NT_ANDROID_TYPE_MEMTAG (Android memory tagging information)"},
5747 const NoteType CoreNoteTypes
[] = {
5748 {ELF::NT_PRSTATUS
, "NT_PRSTATUS (prstatus structure)"},
5749 {ELF::NT_FPREGSET
, "NT_FPREGSET (floating point registers)"},
5750 {ELF::NT_PRPSINFO
, "NT_PRPSINFO (prpsinfo structure)"},
5751 {ELF::NT_TASKSTRUCT
, "NT_TASKSTRUCT (task structure)"},
5752 {ELF::NT_AUXV
, "NT_AUXV (auxiliary vector)"},
5753 {ELF::NT_PSTATUS
, "NT_PSTATUS (pstatus structure)"},
5754 {ELF::NT_FPREGS
, "NT_FPREGS (floating point registers)"},
5755 {ELF::NT_PSINFO
, "NT_PSINFO (psinfo structure)"},
5756 {ELF::NT_LWPSTATUS
, "NT_LWPSTATUS (lwpstatus_t structure)"},
5757 {ELF::NT_LWPSINFO
, "NT_LWPSINFO (lwpsinfo_t structure)"},
5758 {ELF::NT_WIN32PSTATUS
, "NT_WIN32PSTATUS (win32_pstatus structure)"},
5760 {ELF::NT_PPC_VMX
, "NT_PPC_VMX (ppc Altivec registers)"},
5761 {ELF::NT_PPC_VSX
, "NT_PPC_VSX (ppc VSX registers)"},
5762 {ELF::NT_PPC_TAR
, "NT_PPC_TAR (ppc TAR register)"},
5763 {ELF::NT_PPC_PPR
, "NT_PPC_PPR (ppc PPR register)"},
5764 {ELF::NT_PPC_DSCR
, "NT_PPC_DSCR (ppc DSCR register)"},
5765 {ELF::NT_PPC_EBB
, "NT_PPC_EBB (ppc EBB registers)"},
5766 {ELF::NT_PPC_PMU
, "NT_PPC_PMU (ppc PMU registers)"},
5767 {ELF::NT_PPC_TM_CGPR
, "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"},
5768 {ELF::NT_PPC_TM_CFPR
,
5769 "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"},
5770 {ELF::NT_PPC_TM_CVMX
,
5771 "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"},
5772 {ELF::NT_PPC_TM_CVSX
, "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"},
5773 {ELF::NT_PPC_TM_SPR
, "NT_PPC_TM_SPR (ppc TM special purpose registers)"},
5774 {ELF::NT_PPC_TM_CTAR
, "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"},
5775 {ELF::NT_PPC_TM_CPPR
, "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"},
5776 {ELF::NT_PPC_TM_CDSCR
, "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"},
5778 {ELF::NT_386_TLS
, "NT_386_TLS (x86 TLS information)"},
5779 {ELF::NT_386_IOPERM
, "NT_386_IOPERM (x86 I/O permissions)"},
5780 {ELF::NT_X86_XSTATE
, "NT_X86_XSTATE (x86 XSAVE extended state)"},
5782 {ELF::NT_S390_HIGH_GPRS
, "NT_S390_HIGH_GPRS (s390 upper register halves)"},
5783 {ELF::NT_S390_TIMER
, "NT_S390_TIMER (s390 timer register)"},
5784 {ELF::NT_S390_TODCMP
, "NT_S390_TODCMP (s390 TOD comparator register)"},
5785 {ELF::NT_S390_TODPREG
, "NT_S390_TODPREG (s390 TOD programmable register)"},
5786 {ELF::NT_S390_CTRS
, "NT_S390_CTRS (s390 control registers)"},
5787 {ELF::NT_S390_PREFIX
, "NT_S390_PREFIX (s390 prefix register)"},
5788 {ELF::NT_S390_LAST_BREAK
,
5789 "NT_S390_LAST_BREAK (s390 last breaking event address)"},
5790 {ELF::NT_S390_SYSTEM_CALL
,
5791 "NT_S390_SYSTEM_CALL (s390 system call restart data)"},
5792 {ELF::NT_S390_TDB
, "NT_S390_TDB (s390 transaction diagnostic block)"},
5793 {ELF::NT_S390_VXRS_LOW
,
5794 "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"},
5795 {ELF::NT_S390_VXRS_HIGH
, "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"},
5796 {ELF::NT_S390_GS_CB
, "NT_S390_GS_CB (s390 guarded-storage registers)"},
5797 {ELF::NT_S390_GS_BC
,
5798 "NT_S390_GS_BC (s390 guarded-storage broadcast control)"},
5800 {ELF::NT_ARM_VFP
, "NT_ARM_VFP (arm VFP registers)"},
5801 {ELF::NT_ARM_TLS
, "NT_ARM_TLS (AArch TLS registers)"},
5802 {ELF::NT_ARM_HW_BREAK
,
5803 "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"},
5804 {ELF::NT_ARM_HW_WATCH
,
5805 "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"},
5806 {ELF::NT_ARM_SVE
, "NT_ARM_SVE (AArch64 SVE registers)"},
5807 {ELF::NT_ARM_PAC_MASK
,
5808 "NT_ARM_PAC_MASK (AArch64 Pointer Authentication code masks)"},
5809 {ELF::NT_ARM_TAGGED_ADDR_CTRL
,
5810 "NT_ARM_TAGGED_ADDR_CTRL (AArch64 Tagged Address Control)"},
5811 {ELF::NT_ARM_SSVE
, "NT_ARM_SSVE (AArch64 Streaming SVE registers)"},
5812 {ELF::NT_ARM_ZA
, "NT_ARM_ZA (AArch64 SME ZA registers)"},
5813 {ELF::NT_ARM_ZT
, "NT_ARM_ZT (AArch64 SME ZT registers)"},
5815 {ELF::NT_FILE
, "NT_FILE (mapped files)"},
5816 {ELF::NT_PRXFPREG
, "NT_PRXFPREG (user_xfpregs structure)"},
5817 {ELF::NT_SIGINFO
, "NT_SIGINFO (siginfo_t data)"},
5820 template <class ELFT
>
5821 StringRef
getNoteTypeName(const typename
ELFT::Note
&Note
, unsigned ELFType
) {
5822 uint32_t Type
= Note
.getType();
5823 auto FindNote
= [&](ArrayRef
<NoteType
> V
) -> StringRef
{
5824 for (const NoteType
&N
: V
)
5830 StringRef Name
= Note
.getName();
5832 return FindNote(GNUNoteTypes
);
5833 if (Name
== "FreeBSD") {
5834 if (ELFType
== ELF::ET_CORE
) {
5835 // FreeBSD also places the generic core notes in the FreeBSD namespace.
5836 StringRef Result
= FindNote(FreeBSDCoreNoteTypes
);
5837 if (!Result
.empty())
5839 return FindNote(CoreNoteTypes
);
5841 return FindNote(FreeBSDNoteTypes
);
5844 if (ELFType
== ELF::ET_CORE
&& Name
.startswith("NetBSD-CORE")) {
5845 StringRef Result
= FindNote(NetBSDCoreNoteTypes
);
5846 if (!Result
.empty())
5848 return FindNote(CoreNoteTypes
);
5850 if (ELFType
== ELF::ET_CORE
&& Name
.startswith("OpenBSD")) {
5851 // OpenBSD also places the generic core notes in the OpenBSD namespace.
5852 StringRef Result
= FindNote(OpenBSDCoreNoteTypes
);
5853 if (!Result
.empty())
5855 return FindNote(CoreNoteTypes
);
5858 return FindNote(AMDNoteTypes
);
5859 if (Name
== "AMDGPU")
5860 return FindNote(AMDGPUNoteTypes
);
5861 if (Name
== "LLVMOMPOFFLOAD")
5862 return FindNote(LLVMOMPOFFLOADNoteTypes
);
5863 if (Name
== "Android")
5864 return FindNote(AndroidNoteTypes
);
5866 if (ELFType
== ELF::ET_CORE
)
5867 return FindNote(CoreNoteTypes
);
5868 return FindNote(GenericNoteTypes
);
5871 template <class ELFT
>
5872 static void processNotesHelper(
5873 const ELFDumper
<ELFT
> &Dumper
,
5874 llvm::function_ref
<void(std::optional
<StringRef
>, typename
ELFT::Off
,
5875 typename
ELFT::Addr
, size_t)>
5877 llvm::function_ref
<Error(const typename
ELFT::Note
&, bool)> ProcessNoteFn
,
5878 llvm::function_ref
<void()> FinishNotesFn
) {
5879 const ELFFile
<ELFT
> &Obj
= Dumper
.getElfObject().getELFFile();
5880 bool IsCoreFile
= Obj
.getHeader().e_type
== ELF::ET_CORE
;
5882 ArrayRef
<typename
ELFT::Shdr
> Sections
= cantFail(Obj
.sections());
5883 if (!IsCoreFile
&& !Sections
.empty()) {
5884 for (const typename
ELFT::Shdr
&S
: Sections
) {
5885 if (S
.sh_type
!= SHT_NOTE
)
5887 StartNotesFn(expectedToStdOptional(Obj
.getSectionName(S
)), S
.sh_offset
,
5888 S
.sh_size
, S
.sh_addralign
);
5889 Error Err
= Error::success();
5891 for (const typename
ELFT::Note Note
: Obj
.notes(S
, Err
)) {
5892 if (Error E
= ProcessNoteFn(Note
, IsCoreFile
))
5893 Dumper
.reportUniqueWarning(
5894 "unable to read note with index " + Twine(I
) + " from the " +
5895 describe(Obj
, S
) + ": " + toString(std::move(E
)));
5899 Dumper
.reportUniqueWarning("unable to read notes from the " +
5900 describe(Obj
, S
) + ": " +
5901 toString(std::move(Err
)));
5907 Expected
<ArrayRef
<typename
ELFT::Phdr
>> PhdrsOrErr
= Obj
.program_headers();
5909 Dumper
.reportUniqueWarning(
5910 "unable to read program headers to locate the PT_NOTE segment: " +
5911 toString(PhdrsOrErr
.takeError()));
5915 for (size_t I
= 0, E
= (*PhdrsOrErr
).size(); I
!= E
; ++I
) {
5916 const typename
ELFT::Phdr
&P
= (*PhdrsOrErr
)[I
];
5917 if (P
.p_type
!= PT_NOTE
)
5919 StartNotesFn(/*SecName=*/std::nullopt
, P
.p_offset
, P
.p_filesz
, P
.p_align
);
5920 Error Err
= Error::success();
5922 for (const typename
ELFT::Note Note
: Obj
.notes(P
, Err
)) {
5923 if (Error E
= ProcessNoteFn(Note
, IsCoreFile
))
5924 Dumper
.reportUniqueWarning("unable to read note with index " +
5926 " from the PT_NOTE segment with index " +
5927 Twine(I
) + ": " + toString(std::move(E
)));
5931 Dumper
.reportUniqueWarning(
5932 "unable to read notes from the PT_NOTE segment with index " +
5933 Twine(I
) + ": " + toString(std::move(Err
)));
5938 template <class ELFT
> void GNUELFDumper
<ELFT
>::printNotes() {
5940 bool IsFirstHeader
= true;
5941 auto PrintHeader
= [&](std::optional
<StringRef
> SecName
,
5942 const typename
ELFT::Off Offset
,
5943 const typename
ELFT::Addr Size
, size_t Al
) {
5944 Align
= std::max
<size_t>(Al
, 4);
5945 // Print a newline between notes sections to match GNU readelf.
5946 if (!IsFirstHeader
) {
5949 IsFirstHeader
= false;
5952 OS
<< "Displaying notes found ";
5955 OS
<< "in: " << *SecName
<< "\n";
5957 OS
<< "at file offset " << format_hex(Offset
, 10) << " with length "
5958 << format_hex(Size
, 10) << ":\n";
5960 OS
<< " Owner Data size \tDescription\n";
5963 auto ProcessNote
= [&](const Elf_Note
&Note
, bool IsCore
) -> Error
{
5964 StringRef Name
= Note
.getName();
5965 ArrayRef
<uint8_t> Descriptor
= Note
.getDesc(Align
);
5966 Elf_Word Type
= Note
.getType();
5968 // Print the note owner/type.
5969 OS
<< " " << left_justify(Name
, 20) << ' '
5970 << format_hex(Descriptor
.size(), 10) << '\t';
5972 StringRef NoteType
=
5973 getNoteTypeName
<ELFT
>(Note
, this->Obj
.getHeader().e_type
);
5974 if (!NoteType
.empty())
5975 OS
<< NoteType
<< '\n';
5977 OS
<< "Unknown note type: (" << format_hex(Type
, 10) << ")\n";
5979 // Print the description, or fallback to printing raw bytes for unknown
5980 // owners/if we fail to pretty-print the contents.
5981 if (Name
== "GNU") {
5982 if (printGNUNote
<ELFT
>(OS
, Type
, Descriptor
))
5983 return Error::success();
5984 } else if (Name
== "FreeBSD") {
5985 if (std::optional
<FreeBSDNote
> N
=
5986 getFreeBSDNote
<ELFT
>(Type
, Descriptor
, IsCore
)) {
5987 OS
<< " " << N
->Type
<< ": " << N
->Value
<< '\n';
5988 return Error::success();
5990 } else if (Name
== "AMD") {
5991 const AMDNote N
= getAMDNote
<ELFT
>(Type
, Descriptor
);
5992 if (!N
.Type
.empty()) {
5993 OS
<< " " << N
.Type
<< ":\n " << N
.Value
<< '\n';
5994 return Error::success();
5996 } else if (Name
== "AMDGPU") {
5997 const AMDGPUNote N
= getAMDGPUNote
<ELFT
>(Type
, Descriptor
);
5998 if (!N
.Type
.empty()) {
5999 OS
<< " " << N
.Type
<< ":\n " << N
.Value
<< '\n';
6000 return Error::success();
6002 } else if (Name
== "LLVMOMPOFFLOAD") {
6003 if (printLLVMOMPOFFLOADNote
<ELFT
>(OS
, Type
, Descriptor
))
6004 return Error::success();
6005 } else if (Name
== "CORE") {
6006 if (Type
== ELF::NT_FILE
) {
6007 DataExtractor
DescExtractor(
6008 Descriptor
, ELFT::TargetEndianness
== llvm::endianness::little
,
6010 if (Expected
<CoreNote
> NoteOrErr
= readCoreNote(DescExtractor
)) {
6011 printCoreNote
<ELFT
>(OS
, *NoteOrErr
);
6012 return Error::success();
6014 return NoteOrErr
.takeError();
6017 } else if (Name
== "Android") {
6018 if (printAndroidNote(OS
, Type
, Descriptor
))
6019 return Error::success();
6021 if (!Descriptor
.empty()) {
6022 OS
<< " description data:";
6023 for (uint8_t B
: Descriptor
)
6024 OS
<< " " << format("%02x", B
);
6027 return Error::success();
6030 processNotesHelper(*this, /*StartNotesFn=*/PrintHeader
,
6031 /*ProcessNoteFn=*/ProcessNote
, /*FinishNotesFn=*/[]() {});
6034 template <class ELFT
>
6036 ELFDumper
<ELFT
>::getMemtagGlobalsSectionContents(uint64_t ExpectedAddr
) {
6037 for (const typename
ELFT::Shdr
&Sec
: cantFail(Obj
.sections())) {
6038 if (Sec
.sh_type
!= SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC
)
6040 if (Sec
.sh_addr
!= ExpectedAddr
) {
6041 reportUniqueWarning(
6042 "SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section was unexpectedly at 0x" +
6043 Twine::utohexstr(Sec
.sh_addr
) +
6044 ", when DT_AARCH64_MEMTAG_GLOBALS says it should be at 0x" +
6045 Twine::utohexstr(ExpectedAddr
));
6046 return ArrayRef
<uint8_t>();
6048 Expected
<ArrayRef
<uint8_t>> Contents
= Obj
.getSectionContents(Sec
);
6049 if (auto E
= Contents
.takeError()) {
6050 reportUniqueWarning(
6051 "couldn't get SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section contents: " +
6052 toString(std::move(E
)));
6053 return ArrayRef
<uint8_t>();
6055 return Contents
.get();
6057 return ArrayRef
<uint8_t>();
6060 // Reserve the lower three bits of the first byte of the step distance when
6061 // encoding the memtag descriptors. Found to be the best overall size tradeoff
6062 // when compiling Android T with full MTE globals enabled.
6063 constexpr uint64_t MemtagStepVarintReservedBits
= 3;
6064 constexpr uint64_t MemtagGranuleSize
= 16;
6066 template <typename ELFT
> void ELFDumper
<ELFT
>::printMemtag() {
6067 if (Obj
.getHeader().e_machine
!= EM_AARCH64
) return;
6068 std::vector
<std::pair
<std::string
, std::string
>> DynamicEntries
;
6069 uint64_t MemtagGlobalsSz
= 0;
6070 uint64_t MemtagGlobals
= 0;
6071 for (const typename
ELFT::Dyn
&Entry
: dynamic_table()) {
6072 uintX_t Tag
= Entry
.getTag();
6074 case DT_AARCH64_MEMTAG_GLOBALSSZ
:
6075 MemtagGlobalsSz
= Entry
.getVal();
6076 DynamicEntries
.emplace_back(Obj
.getDynamicTagAsString(Tag
),
6077 getDynamicEntry(Tag
, Entry
.getVal()));
6079 case DT_AARCH64_MEMTAG_GLOBALS
:
6080 MemtagGlobals
= Entry
.getVal();
6081 DynamicEntries
.emplace_back(Obj
.getDynamicTagAsString(Tag
),
6082 getDynamicEntry(Tag
, Entry
.getVal()));
6084 case DT_AARCH64_MEMTAG_MODE
:
6085 case DT_AARCH64_MEMTAG_HEAP
:
6086 case DT_AARCH64_MEMTAG_STACK
:
6087 DynamicEntries
.emplace_back(Obj
.getDynamicTagAsString(Tag
),
6088 getDynamicEntry(Tag
, Entry
.getVal()));
6093 ArrayRef
<uint8_t> AndroidNoteDesc
;
6094 auto FindAndroidNote
= [&](const Elf_Note
&Note
, bool IsCore
) -> Error
{
6095 if (Note
.getName() == "Android" &&
6096 Note
.getType() == ELF::NT_ANDROID_TYPE_MEMTAG
)
6097 AndroidNoteDesc
= Note
.getDesc(4);
6098 return Error::success();
6104 [](std::optional
<StringRef
>, const typename
ELFT::Off
,
6105 const typename
ELFT::Addr
, size_t) {},
6106 /*ProcessNoteFn=*/FindAndroidNote
, /*FinishNotesFn=*/[]() {});
6108 ArrayRef
<uint8_t> Contents
= getMemtagGlobalsSectionContents(MemtagGlobals
);
6109 if (Contents
.size() != MemtagGlobalsSz
) {
6110 reportUniqueWarning(
6111 "mismatch between DT_AARCH64_MEMTAG_GLOBALSSZ (0x" +
6112 Twine::utohexstr(MemtagGlobalsSz
) +
6113 ") and SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section size (0x" +
6114 Twine::utohexstr(Contents
.size()) + ")");
6115 Contents
= ArrayRef
<uint8_t>();
6118 std::vector
<std::pair
<uint64_t, uint64_t>> GlobalDescriptors
;
6119 uint64_t Address
= 0;
6120 // See the AArch64 MemtagABI document for a description of encoding scheme:
6121 // https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#83encoding-of-sht_aarch64_memtag_globals_dynamic
6122 for (size_t I
= 0; I
< Contents
.size();) {
6123 const char *Error
= nullptr;
6124 unsigned DecodedBytes
= 0;
6125 uint64_t Value
= decodeULEB128(Contents
.data() + I
, &DecodedBytes
,
6126 Contents
.end(), &Error
);
6129 reportUniqueWarning(
6130 "error decoding distance uleb, " + Twine(DecodedBytes
) +
6131 " byte(s) into SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC: " + Twine(Error
));
6132 GlobalDescriptors
.clear();
6135 uint64_t Distance
= Value
>> MemtagStepVarintReservedBits
;
6136 uint64_t GranulesToTag
= Value
& ((1 << MemtagStepVarintReservedBits
) - 1);
6137 if (GranulesToTag
== 0) {
6138 GranulesToTag
= decodeULEB128(Contents
.data() + I
, &DecodedBytes
,
6139 Contents
.end(), &Error
) +
6143 reportUniqueWarning(
6144 "error decoding size-only uleb, " + Twine(DecodedBytes
) +
6145 " byte(s) into SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC: " + Twine(Error
));
6146 GlobalDescriptors
.clear();
6150 Address
+= Distance
* MemtagGranuleSize
;
6151 GlobalDescriptors
.emplace_back(Address
, GranulesToTag
* MemtagGranuleSize
);
6152 Address
+= GranulesToTag
* MemtagGranuleSize
;
6155 printMemtag(DynamicEntries
, AndroidNoteDesc
, GlobalDescriptors
);
6158 template <class ELFT
> void GNUELFDumper
<ELFT
>::printELFLinkerOptions() {
6159 OS
<< "printELFLinkerOptions not implemented!\n";
6162 template <class ELFT
>
6163 void ELFDumper
<ELFT
>::printDependentLibsHelper(
6164 function_ref
<void(const Elf_Shdr
&)> OnSectionStart
,
6165 function_ref
<void(StringRef
, uint64_t)> OnLibEntry
) {
6166 auto Warn
= [this](unsigned SecNdx
, StringRef Msg
) {
6167 this->reportUniqueWarning("SHT_LLVM_DEPENDENT_LIBRARIES section at index " +
6168 Twine(SecNdx
) + " is broken: " + Msg
);
6172 for (const Elf_Shdr
&Shdr
: cantFail(Obj
.sections())) {
6174 if (Shdr
.sh_type
!= ELF::SHT_LLVM_DEPENDENT_LIBRARIES
)
6177 OnSectionStart(Shdr
);
6179 Expected
<ArrayRef
<uint8_t>> ContentsOrErr
= Obj
.getSectionContents(Shdr
);
6180 if (!ContentsOrErr
) {
6181 Warn(I
, toString(ContentsOrErr
.takeError()));
6185 ArrayRef
<uint8_t> Contents
= *ContentsOrErr
;
6186 if (!Contents
.empty() && Contents
.back() != 0) {
6187 Warn(I
, "the content is not null-terminated");
6191 for (const uint8_t *I
= Contents
.begin(), *E
= Contents
.end(); I
< E
;) {
6192 StringRef
Lib((const char *)I
);
6193 OnLibEntry(Lib
, I
- Contents
.begin());
6194 I
+= Lib
.size() + 1;
6199 template <class ELFT
>
6200 void ELFDumper
<ELFT
>::forEachRelocationDo(
6201 const Elf_Shdr
&Sec
, bool RawRelr
,
6202 llvm::function_ref
<void(const Relocation
<ELFT
> &, unsigned,
6203 const Elf_Shdr
&, const Elf_Shdr
*)>
6205 llvm::function_ref
<void(const Elf_Relr
&)> RelrFn
) {
6206 auto Warn
= [&](Error
&&E
,
6207 const Twine
&Prefix
= "unable to read relocations from") {
6208 this->reportUniqueWarning(Prefix
+ " " + describe(Sec
) + ": " +
6209 toString(std::move(E
)));
6212 // SHT_RELR/SHT_ANDROID_RELR sections do not have an associated symbol table.
6213 // For them we should not treat the value of the sh_link field as an index of
6215 const Elf_Shdr
*SymTab
;
6216 if (Sec
.sh_type
!= ELF::SHT_RELR
&& Sec
.sh_type
!= ELF::SHT_ANDROID_RELR
) {
6217 Expected
<const Elf_Shdr
*> SymTabOrErr
= Obj
.getSection(Sec
.sh_link
);
6219 Warn(SymTabOrErr
.takeError(), "unable to locate a symbol table for");
6222 SymTab
= *SymTabOrErr
;
6225 unsigned RelNdx
= 0;
6226 const bool IsMips64EL
= this->Obj
.isMips64EL();
6227 switch (Sec
.sh_type
) {
6229 if (Expected
<Elf_Rel_Range
> RangeOrErr
= Obj
.rels(Sec
)) {
6230 for (const Elf_Rel
&R
: *RangeOrErr
)
6231 RelRelaFn(Relocation
<ELFT
>(R
, IsMips64EL
), RelNdx
++, Sec
, SymTab
);
6233 Warn(RangeOrErr
.takeError());
6237 if (Expected
<Elf_Rela_Range
> RangeOrErr
= Obj
.relas(Sec
)) {
6238 for (const Elf_Rela
&R
: *RangeOrErr
)
6239 RelRelaFn(Relocation
<ELFT
>(R
, IsMips64EL
), RelNdx
++, Sec
, SymTab
);
6241 Warn(RangeOrErr
.takeError());
6245 case ELF::SHT_ANDROID_RELR
: {
6246 Expected
<Elf_Relr_Range
> RangeOrErr
= Obj
.relrs(Sec
);
6248 Warn(RangeOrErr
.takeError());
6252 for (const Elf_Relr
&R
: *RangeOrErr
)
6257 for (const Elf_Rel
&R
: Obj
.decode_relrs(*RangeOrErr
))
6258 RelRelaFn(Relocation
<ELFT
>(R
, IsMips64EL
), RelNdx
++, Sec
,
6259 /*SymTab=*/nullptr);
6262 case ELF::SHT_ANDROID_REL
:
6263 case ELF::SHT_ANDROID_RELA
:
6264 if (Expected
<std::vector
<Elf_Rela
>> RelasOrErr
= Obj
.android_relas(Sec
)) {
6265 for (const Elf_Rela
&R
: *RelasOrErr
)
6266 RelRelaFn(Relocation
<ELFT
>(R
, IsMips64EL
), RelNdx
++, Sec
, SymTab
);
6268 Warn(RelasOrErr
.takeError());
6274 template <class ELFT
>
6275 StringRef ELFDumper
<ELFT
>::getPrintableSectionName(const Elf_Shdr
&Sec
) const {
6276 StringRef Name
= "<?>";
6277 if (Expected
<StringRef
> SecNameOrErr
=
6278 Obj
.getSectionName(Sec
, this->WarningHandler
))
6279 Name
= *SecNameOrErr
;
6281 this->reportUniqueWarning("unable to get the name of " + describe(Sec
) +
6282 ": " + toString(SecNameOrErr
.takeError()));
6286 template <class ELFT
> void GNUELFDumper
<ELFT
>::printDependentLibs() {
6287 bool SectionStarted
= false;
6292 std::vector
<NameOffset
> SecEntries
;
6294 auto PrintSection
= [&]() {
6295 OS
<< "Dependent libraries section " << Current
.Name
<< " at offset "
6296 << format_hex(Current
.Offset
, 1) << " contains " << SecEntries
.size()
6298 for (NameOffset Entry
: SecEntries
)
6299 OS
<< " [" << format("%6" PRIx64
, Entry
.Offset
) << "] " << Entry
.Name
6305 auto OnSectionStart
= [&](const Elf_Shdr
&Shdr
) {
6308 SectionStarted
= true;
6309 Current
.Offset
= Shdr
.sh_offset
;
6310 Current
.Name
= this->getPrintableSectionName(Shdr
);
6312 auto OnLibEntry
= [&](StringRef Lib
, uint64_t Offset
) {
6313 SecEntries
.push_back(NameOffset
{Lib
, Offset
});
6316 this->printDependentLibsHelper(OnSectionStart
, OnLibEntry
);
6321 template <class ELFT
>
6322 SmallVector
<uint32_t> ELFDumper
<ELFT
>::getSymbolIndexesForFunctionAddress(
6323 uint64_t SymValue
, std::optional
<const Elf_Shdr
*> FunctionSec
) {
6324 SmallVector
<uint32_t> SymbolIndexes
;
6325 if (!this->AddressToIndexMap
) {
6326 // Populate the address to index map upon the first invocation of this
6328 this->AddressToIndexMap
.emplace();
6329 if (this->DotSymtabSec
) {
6330 if (Expected
<Elf_Sym_Range
> SymsOrError
=
6331 Obj
.symbols(this->DotSymtabSec
)) {
6332 uint32_t Index
= (uint32_t)-1;
6333 for (const Elf_Sym
&Sym
: *SymsOrError
) {
6336 if (Sym
.st_shndx
== ELF::SHN_UNDEF
|| Sym
.getType() != ELF::STT_FUNC
)
6339 Expected
<uint64_t> SymAddrOrErr
=
6340 ObjF
.toSymbolRef(this->DotSymtabSec
, Index
).getAddress();
6341 if (!SymAddrOrErr
) {
6342 std::string Name
= this->getStaticSymbolName(Index
);
6343 reportUniqueWarning("unable to get address of symbol '" + Name
+
6344 "': " + toString(SymAddrOrErr
.takeError()));
6345 return SymbolIndexes
;
6348 (*this->AddressToIndexMap
)[*SymAddrOrErr
].push_back(Index
);
6351 reportUniqueWarning("unable to read the symbol table: " +
6352 toString(SymsOrError
.takeError()));
6357 auto Symbols
= this->AddressToIndexMap
->find(SymValue
);
6358 if (Symbols
== this->AddressToIndexMap
->end())
6359 return SymbolIndexes
;
6361 for (uint32_t Index
: Symbols
->second
) {
6362 // Check if the symbol is in the right section. FunctionSec == None
6363 // means "any section".
6365 const Elf_Sym
&Sym
= *cantFail(Obj
.getSymbol(this->DotSymtabSec
, Index
));
6366 if (Expected
<const Elf_Shdr
*> SecOrErr
=
6367 Obj
.getSection(Sym
, this->DotSymtabSec
,
6368 this->getShndxTable(this->DotSymtabSec
))) {
6369 if (*FunctionSec
!= *SecOrErr
)
6372 std::string Name
= this->getStaticSymbolName(Index
);
6373 // Note: it is impossible to trigger this error currently, it is
6375 reportUniqueWarning("unable to get section of symbol '" + Name
+
6376 "': " + toString(SecOrErr
.takeError()));
6377 return SymbolIndexes
;
6381 SymbolIndexes
.push_back(Index
);
6384 return SymbolIndexes
;
6387 template <class ELFT
>
6388 bool ELFDumper
<ELFT
>::printFunctionStackSize(
6389 uint64_t SymValue
, std::optional
<const Elf_Shdr
*> FunctionSec
,
6390 const Elf_Shdr
&StackSizeSec
, DataExtractor Data
, uint64_t *Offset
) {
6391 SmallVector
<uint32_t> FuncSymIndexes
=
6392 this->getSymbolIndexesForFunctionAddress(SymValue
, FunctionSec
);
6393 if (FuncSymIndexes
.empty())
6394 reportUniqueWarning(
6395 "could not identify function symbol for stack size entry in " +
6396 describe(StackSizeSec
));
6398 // Extract the size. The expectation is that Offset is pointing to the right
6399 // place, i.e. past the function address.
6400 Error Err
= Error::success();
6401 uint64_t StackSize
= Data
.getULEB128(Offset
, &Err
);
6403 reportUniqueWarning("could not extract a valid stack size from " +
6404 describe(StackSizeSec
) + ": " +
6405 toString(std::move(Err
)));
6409 if (FuncSymIndexes
.empty()) {
6410 printStackSizeEntry(StackSize
, {"?"});
6412 SmallVector
<std::string
> FuncSymNames
;
6413 for (uint32_t Index
: FuncSymIndexes
)
6414 FuncSymNames
.push_back(this->getStaticSymbolName(Index
));
6415 printStackSizeEntry(StackSize
, FuncSymNames
);
6421 template <class ELFT
>
6422 void GNUELFDumper
<ELFT
>::printStackSizeEntry(uint64_t Size
,
6423 ArrayRef
<std::string
> FuncNames
) {
6425 OS
<< format_decimal(Size
, 11);
6428 OS
<< join(FuncNames
.begin(), FuncNames
.end(), ", ") << "\n";
6431 template <class ELFT
>
6432 void ELFDumper
<ELFT
>::printStackSize(const Relocation
<ELFT
> &R
,
6433 const Elf_Shdr
&RelocSec
, unsigned Ndx
,
6434 const Elf_Shdr
*SymTab
,
6435 const Elf_Shdr
*FunctionSec
,
6436 const Elf_Shdr
&StackSizeSec
,
6437 const RelocationResolver
&Resolver
,
6438 DataExtractor Data
) {
6439 // This function ignores potentially erroneous input, unless it is directly
6440 // related to stack size reporting.
6441 const Elf_Sym
*Sym
= nullptr;
6442 Expected
<RelSymbol
<ELFT
>> TargetOrErr
= this->getRelocationTarget(R
, SymTab
);
6444 reportUniqueWarning("unable to get the target of relocation with index " +
6445 Twine(Ndx
) + " in " + describe(RelocSec
) + ": " +
6446 toString(TargetOrErr
.takeError()));
6448 Sym
= TargetOrErr
->Sym
;
6450 uint64_t RelocSymValue
= 0;
6452 Expected
<const Elf_Shdr
*> SectionOrErr
=
6453 this->Obj
.getSection(*Sym
, SymTab
, this->getShndxTable(SymTab
));
6454 if (!SectionOrErr
) {
6455 reportUniqueWarning(
6456 "cannot identify the section for relocation symbol '" +
6457 (*TargetOrErr
).Name
+ "': " + toString(SectionOrErr
.takeError()));
6458 } else if (*SectionOrErr
!= FunctionSec
) {
6459 reportUniqueWarning("relocation symbol '" + (*TargetOrErr
).Name
+
6460 "' is not in the expected section");
6461 // Pretend that the symbol is in the correct section and report its
6462 // stack size anyway.
6463 FunctionSec
= *SectionOrErr
;
6466 RelocSymValue
= Sym
->st_value
;
6469 uint64_t Offset
= R
.Offset
;
6470 if (!Data
.isValidOffsetForDataOfSize(Offset
, sizeof(Elf_Addr
) + 1)) {
6471 reportUniqueWarning("found invalid relocation offset (0x" +
6472 Twine::utohexstr(Offset
) + ") into " +
6473 describe(StackSizeSec
) +
6474 " while trying to extract a stack size entry");
6478 uint64_t SymValue
= Resolver(R
.Type
, Offset
, RelocSymValue
,
6479 Data
.getAddress(&Offset
), R
.Addend
.value_or(0));
6480 this->printFunctionStackSize(SymValue
, FunctionSec
, StackSizeSec
, Data
,
6484 template <class ELFT
>
6485 void ELFDumper
<ELFT
>::printNonRelocatableStackSizes(
6486 std::function
<void()> PrintHeader
) {
6487 // This function ignores potentially erroneous input, unless it is directly
6488 // related to stack size reporting.
6489 for (const Elf_Shdr
&Sec
: cantFail(Obj
.sections())) {
6490 if (this->getPrintableSectionName(Sec
) != ".stack_sizes")
6493 ArrayRef
<uint8_t> Contents
=
6494 unwrapOrError(this->FileName
, Obj
.getSectionContents(Sec
));
6495 DataExtractor
Data(Contents
, Obj
.isLE(), sizeof(Elf_Addr
));
6496 uint64_t Offset
= 0;
6497 while (Offset
< Contents
.size()) {
6498 // The function address is followed by a ULEB representing the stack
6499 // size. Check for an extra byte before we try to process the entry.
6500 if (!Data
.isValidOffsetForDataOfSize(Offset
, sizeof(Elf_Addr
) + 1)) {
6501 reportUniqueWarning(
6503 " ended while trying to extract a stack size entry");
6506 uint64_t SymValue
= Data
.getAddress(&Offset
);
6507 if (!printFunctionStackSize(SymValue
, /*FunctionSec=*/std::nullopt
, Sec
,
6514 template <class ELFT
>
6515 void ELFDumper
<ELFT
>::printRelocatableStackSizes(
6516 std::function
<void()> PrintHeader
) {
6517 // Build a map between stack size sections and their corresponding relocation
6519 auto IsMatch
= [&](const Elf_Shdr
&Sec
) -> bool {
6520 StringRef SectionName
;
6521 if (Expected
<StringRef
> NameOrErr
= Obj
.getSectionName(Sec
))
6522 SectionName
= *NameOrErr
;
6524 consumeError(NameOrErr
.takeError());
6526 return SectionName
== ".stack_sizes";
6529 Expected
<MapVector
<const Elf_Shdr
*, const Elf_Shdr
*>>
6530 StackSizeRelocMapOrErr
= Obj
.getSectionAndRelocations(IsMatch
);
6531 if (!StackSizeRelocMapOrErr
) {
6532 reportUniqueWarning("unable to get stack size map section(s): " +
6533 toString(StackSizeRelocMapOrErr
.takeError()));
6537 for (const auto &StackSizeMapEntry
: *StackSizeRelocMapOrErr
) {
6539 const Elf_Shdr
*StackSizesELFSec
= StackSizeMapEntry
.first
;
6540 const Elf_Shdr
*RelocSec
= StackSizeMapEntry
.second
;
6542 // Warn about stack size sections without a relocation section.
6544 reportWarning(createError(".stack_sizes (" + describe(*StackSizesELFSec
) +
6545 ") does not have a corresponding "
6546 "relocation section"),
6551 // A .stack_sizes section header's sh_link field is supposed to point
6552 // to the section that contains the functions whose stack sizes are
6554 const Elf_Shdr
*FunctionSec
= unwrapOrError(
6555 this->FileName
, Obj
.getSection(StackSizesELFSec
->sh_link
));
6557 SupportsRelocation IsSupportedFn
;
6558 RelocationResolver Resolver
;
6559 std::tie(IsSupportedFn
, Resolver
) = getRelocationResolver(this->ObjF
);
6560 ArrayRef
<uint8_t> Contents
=
6561 unwrapOrError(this->FileName
, Obj
.getSectionContents(*StackSizesELFSec
));
6562 DataExtractor
Data(Contents
, Obj
.isLE(), sizeof(Elf_Addr
));
6564 forEachRelocationDo(
6565 *RelocSec
, /*RawRelr=*/false,
6566 [&](const Relocation
<ELFT
> &R
, unsigned Ndx
, const Elf_Shdr
&Sec
,
6567 const Elf_Shdr
*SymTab
) {
6568 if (!IsSupportedFn
|| !IsSupportedFn(R
.Type
)) {
6569 reportUniqueWarning(
6570 describe(*RelocSec
) +
6571 " contains an unsupported relocation with index " + Twine(Ndx
) +
6572 ": " + Obj
.getRelocationTypeName(R
.Type
));
6576 this->printStackSize(R
, *RelocSec
, Ndx
, SymTab
, FunctionSec
,
6577 *StackSizesELFSec
, Resolver
, Data
);
6579 [](const Elf_Relr
&) {
6580 llvm_unreachable("can't get here, because we only support "
6581 "SHT_REL/SHT_RELA sections");
6586 template <class ELFT
>
6587 void GNUELFDumper
<ELFT
>::printStackSizes() {
6588 bool HeaderHasBeenPrinted
= false;
6589 auto PrintHeader
= [&]() {
6590 if (HeaderHasBeenPrinted
)
6592 OS
<< "\nStack Sizes:\n";
6596 OS
<< "Functions\n";
6597 HeaderHasBeenPrinted
= true;
6600 // For non-relocatable objects, look directly for sections whose name starts
6601 // with .stack_sizes and process the contents.
6602 if (this->Obj
.getHeader().e_type
== ELF::ET_REL
)
6603 this->printRelocatableStackSizes(PrintHeader
);
6605 this->printNonRelocatableStackSizes(PrintHeader
);
6608 template <class ELFT
>
6609 void GNUELFDumper
<ELFT
>::printMipsGOT(const MipsGOTParser
<ELFT
> &Parser
) {
6610 size_t Bias
= ELFT::Is64Bits
? 8 : 0;
6611 auto PrintEntry
= [&](const Elf_Addr
*E
, StringRef Purpose
) {
6613 OS
<< format_hex_no_prefix(Parser
.getGotAddress(E
), 8 + Bias
);
6614 OS
.PadToColumn(11 + Bias
);
6615 OS
<< format_decimal(Parser
.getGotOffset(E
), 6) << "(gp)";
6616 OS
.PadToColumn(22 + Bias
);
6617 OS
<< format_hex_no_prefix(*E
, 8 + Bias
);
6618 OS
.PadToColumn(31 + 2 * Bias
);
6619 OS
<< Purpose
<< "\n";
6622 OS
<< (Parser
.IsStatic
? "Static GOT:\n" : "Primary GOT:\n");
6623 OS
<< " Canonical gp value: "
6624 << format_hex_no_prefix(Parser
.getGp(), 8 + Bias
) << "\n\n";
6626 OS
<< " Reserved entries:\n";
6628 OS
<< " Address Access Initial Purpose\n";
6630 OS
<< " Address Access Initial Purpose\n";
6631 PrintEntry(Parser
.getGotLazyResolver(), "Lazy resolver");
6632 if (Parser
.getGotModulePointer())
6633 PrintEntry(Parser
.getGotModulePointer(), "Module pointer (GNU extension)");
6635 if (!Parser
.getLocalEntries().empty()) {
6637 OS
<< " Local entries:\n";
6639 OS
<< " Address Access Initial\n";
6641 OS
<< " Address Access Initial\n";
6642 for (auto &E
: Parser
.getLocalEntries())
6646 if (Parser
.IsStatic
)
6649 if (!Parser
.getGlobalEntries().empty()) {
6651 OS
<< " Global entries:\n";
6653 OS
<< " Address Access Initial Sym.Val."
6654 << " Type Ndx Name\n";
6656 OS
<< " Address Access Initial Sym.Val. Type Ndx Name\n";
6658 DataRegion
<Elf_Word
> ShndxTable(
6659 (const Elf_Word
*)this->DynSymTabShndxRegion
.Addr
, this->Obj
.end());
6660 for (auto &E
: Parser
.getGlobalEntries()) {
6661 const Elf_Sym
&Sym
= *Parser
.getGotSym(&E
);
6662 const Elf_Sym
&FirstSym
= this->dynamic_symbols()[0];
6663 std::string SymName
= this->getFullSymbolName(
6664 Sym
, &Sym
- &FirstSym
, ShndxTable
, this->DynamicStringTable
, false);
6667 OS
<< to_string(format_hex_no_prefix(Parser
.getGotAddress(&E
), 8 + Bias
));
6668 OS
.PadToColumn(11 + Bias
);
6669 OS
<< to_string(format_decimal(Parser
.getGotOffset(&E
), 6)) + "(gp)";
6670 OS
.PadToColumn(22 + Bias
);
6671 OS
<< to_string(format_hex_no_prefix(E
, 8 + Bias
));
6672 OS
.PadToColumn(31 + 2 * Bias
);
6673 OS
<< to_string(format_hex_no_prefix(Sym
.st_value
, 8 + Bias
));
6674 OS
.PadToColumn(40 + 3 * Bias
);
6675 OS
<< enumToString(Sym
.getType(), ArrayRef(ElfSymbolTypes
));
6676 OS
.PadToColumn(48 + 3 * Bias
);
6677 OS
<< getSymbolSectionNdx(Sym
, &Sym
- this->dynamic_symbols().begin(),
6679 OS
.PadToColumn(52 + 3 * Bias
);
6680 OS
<< SymName
<< "\n";
6684 if (!Parser
.getOtherEntries().empty())
6685 OS
<< "\n Number of TLS and multi-GOT entries "
6686 << Parser
.getOtherEntries().size() << "\n";
6689 template <class ELFT
>
6690 void GNUELFDumper
<ELFT
>::printMipsPLT(const MipsGOTParser
<ELFT
> &Parser
) {
6691 size_t Bias
= ELFT::Is64Bits
? 8 : 0;
6692 auto PrintEntry
= [&](const Elf_Addr
*E
, StringRef Purpose
) {
6694 OS
<< format_hex_no_prefix(Parser
.getPltAddress(E
), 8 + Bias
);
6695 OS
.PadToColumn(11 + Bias
);
6696 OS
<< format_hex_no_prefix(*E
, 8 + Bias
);
6697 OS
.PadToColumn(20 + 2 * Bias
);
6698 OS
<< Purpose
<< "\n";
6701 OS
<< "PLT GOT:\n\n";
6703 OS
<< " Reserved entries:\n";
6704 OS
<< " Address Initial Purpose\n";
6705 PrintEntry(Parser
.getPltLazyResolver(), "PLT lazy resolver");
6706 if (Parser
.getPltModulePointer())
6707 PrintEntry(Parser
.getPltModulePointer(), "Module pointer");
6709 if (!Parser
.getPltEntries().empty()) {
6711 OS
<< " Entries:\n";
6712 OS
<< " Address Initial Sym.Val. Type Ndx Name\n";
6713 DataRegion
<Elf_Word
> ShndxTable(
6714 (const Elf_Word
*)this->DynSymTabShndxRegion
.Addr
, this->Obj
.end());
6715 for (auto &E
: Parser
.getPltEntries()) {
6716 const Elf_Sym
&Sym
= *Parser
.getPltSym(&E
);
6717 const Elf_Sym
&FirstSym
= *cantFail(
6718 this->Obj
.template getEntry
<Elf_Sym
>(*Parser
.getPltSymTable(), 0));
6719 std::string SymName
= this->getFullSymbolName(
6720 Sym
, &Sym
- &FirstSym
, ShndxTable
, this->DynamicStringTable
, false);
6723 OS
<< to_string(format_hex_no_prefix(Parser
.getPltAddress(&E
), 8 + Bias
));
6724 OS
.PadToColumn(11 + Bias
);
6725 OS
<< to_string(format_hex_no_prefix(E
, 8 + Bias
));
6726 OS
.PadToColumn(20 + 2 * Bias
);
6727 OS
<< to_string(format_hex_no_prefix(Sym
.st_value
, 8 + Bias
));
6728 OS
.PadToColumn(29 + 3 * Bias
);
6729 OS
<< enumToString(Sym
.getType(), ArrayRef(ElfSymbolTypes
));
6730 OS
.PadToColumn(37 + 3 * Bias
);
6731 OS
<< getSymbolSectionNdx(Sym
, &Sym
- this->dynamic_symbols().begin(),
6733 OS
.PadToColumn(41 + 3 * Bias
);
6734 OS
<< SymName
<< "\n";
6739 template <class ELFT
>
6740 Expected
<const Elf_Mips_ABIFlags
<ELFT
> *>
6741 getMipsAbiFlagsSection(const ELFDumper
<ELFT
> &Dumper
) {
6742 const typename
ELFT::Shdr
*Sec
= Dumper
.findSectionByName(".MIPS.abiflags");
6746 constexpr StringRef ErrPrefix
= "unable to read the .MIPS.abiflags section: ";
6747 Expected
<ArrayRef
<uint8_t>> DataOrErr
=
6748 Dumper
.getElfObject().getELFFile().getSectionContents(*Sec
);
6750 return createError(ErrPrefix
+ toString(DataOrErr
.takeError()));
6752 if (DataOrErr
->size() != sizeof(Elf_Mips_ABIFlags
<ELFT
>))
6753 return createError(ErrPrefix
+ "it has a wrong size (" +
6754 Twine(DataOrErr
->size()) + ")");
6755 return reinterpret_cast<const Elf_Mips_ABIFlags
<ELFT
> *>(DataOrErr
->data());
6758 template <class ELFT
> void GNUELFDumper
<ELFT
>::printMipsABIFlags() {
6759 const Elf_Mips_ABIFlags
<ELFT
> *Flags
= nullptr;
6760 if (Expected
<const Elf_Mips_ABIFlags
<ELFT
> *> SecOrErr
=
6761 getMipsAbiFlagsSection(*this))
6764 this->reportUniqueWarning(SecOrErr
.takeError());
6768 OS
<< "MIPS ABI Flags Version: " << Flags
->version
<< "\n\n";
6769 OS
<< "ISA: MIPS" << int(Flags
->isa_level
);
6770 if (Flags
->isa_rev
> 1)
6771 OS
<< "r" << int(Flags
->isa_rev
);
6773 OS
<< "GPR size: " << getMipsRegisterSize(Flags
->gpr_size
) << "\n";
6774 OS
<< "CPR1 size: " << getMipsRegisterSize(Flags
->cpr1_size
) << "\n";
6775 OS
<< "CPR2 size: " << getMipsRegisterSize(Flags
->cpr2_size
) << "\n";
6776 OS
<< "FP ABI: " << enumToString(Flags
->fp_abi
, ArrayRef(ElfMipsFpABIType
))
6778 OS
<< "ISA Extension: "
6779 << enumToString(Flags
->isa_ext
, ArrayRef(ElfMipsISAExtType
)) << "\n";
6780 if (Flags
->ases
== 0)
6781 OS
<< "ASEs: None\n";
6783 // FIXME: Print each flag on a separate line.
6784 OS
<< "ASEs: " << printFlags(Flags
->ases
, ArrayRef(ElfMipsASEFlags
))
6786 OS
<< "FLAGS 1: " << format_hex_no_prefix(Flags
->flags1
, 8, false) << "\n";
6787 OS
<< "FLAGS 2: " << format_hex_no_prefix(Flags
->flags2
, 8, false) << "\n";
6791 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printFileHeaders() {
6792 const Elf_Ehdr
&E
= this->Obj
.getHeader();
6794 DictScope
D(W
, "ElfHeader");
6796 DictScope
D(W
, "Ident");
6797 W
.printBinary("Magic",
6798 ArrayRef
<unsigned char>(E
.e_ident
).slice(ELF::EI_MAG0
, 4));
6799 W
.printEnum("Class", E
.e_ident
[ELF::EI_CLASS
], ArrayRef(ElfClass
));
6800 W
.printEnum("DataEncoding", E
.e_ident
[ELF::EI_DATA
],
6801 ArrayRef(ElfDataEncoding
));
6802 W
.printNumber("FileVersion", E
.e_ident
[ELF::EI_VERSION
]);
6804 auto OSABI
= ArrayRef(ElfOSABI
);
6805 if (E
.e_ident
[ELF::EI_OSABI
] >= ELF::ELFOSABI_FIRST_ARCH
&&
6806 E
.e_ident
[ELF::EI_OSABI
] <= ELF::ELFOSABI_LAST_ARCH
) {
6807 switch (E
.e_machine
) {
6808 case ELF::EM_AMDGPU
:
6809 OSABI
= ArrayRef(AMDGPUElfOSABI
);
6812 OSABI
= ArrayRef(ARMElfOSABI
);
6814 case ELF::EM_TI_C6000
:
6815 OSABI
= ArrayRef(C6000ElfOSABI
);
6819 W
.printEnum("OS/ABI", E
.e_ident
[ELF::EI_OSABI
], OSABI
);
6820 W
.printNumber("ABIVersion", E
.e_ident
[ELF::EI_ABIVERSION
]);
6821 W
.printBinary("Unused",
6822 ArrayRef
<unsigned char>(E
.e_ident
).slice(ELF::EI_PAD
));
6825 std::string TypeStr
;
6826 if (const EnumEntry
<unsigned> *Ent
= getObjectFileEnumEntry(E
.e_type
)) {
6827 TypeStr
= Ent
->Name
.str();
6829 if (E
.e_type
>= ET_LOPROC
)
6830 TypeStr
= "Processor Specific";
6831 else if (E
.e_type
>= ET_LOOS
)
6832 TypeStr
= "OS Specific";
6834 TypeStr
= "Unknown";
6836 W
.printString("Type", TypeStr
+ " (0x" + utohexstr(E
.e_type
) + ")");
6838 W
.printEnum("Machine", E
.e_machine
, ArrayRef(ElfMachineType
));
6839 W
.printNumber("Version", E
.e_version
);
6840 W
.printHex("Entry", E
.e_entry
);
6841 W
.printHex("ProgramHeaderOffset", E
.e_phoff
);
6842 W
.printHex("SectionHeaderOffset", E
.e_shoff
);
6843 if (E
.e_machine
== EM_MIPS
)
6844 W
.printFlags("Flags", E
.e_flags
, ArrayRef(ElfHeaderMipsFlags
),
6845 unsigned(ELF::EF_MIPS_ARCH
), unsigned(ELF::EF_MIPS_ABI
),
6846 unsigned(ELF::EF_MIPS_MACH
));
6847 else if (E
.e_machine
== EM_AMDGPU
) {
6848 switch (E
.e_ident
[ELF::EI_ABIVERSION
]) {
6850 W
.printHex("Flags", E
.e_flags
);
6853 // ELFOSABI_AMDGPU_PAL, ELFOSABI_AMDGPU_MESA3D support *_V3 flags.
6855 case ELF::ELFABIVERSION_AMDGPU_HSA_V3
:
6856 W
.printFlags("Flags", E
.e_flags
,
6857 ArrayRef(ElfHeaderAMDGPUFlagsABIVersion3
),
6858 unsigned(ELF::EF_AMDGPU_MACH
));
6860 case ELF::ELFABIVERSION_AMDGPU_HSA_V4
:
6861 case ELF::ELFABIVERSION_AMDGPU_HSA_V5
:
6862 W
.printFlags("Flags", E
.e_flags
,
6863 ArrayRef(ElfHeaderAMDGPUFlagsABIVersion4
),
6864 unsigned(ELF::EF_AMDGPU_MACH
),
6865 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4
),
6866 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4
));
6869 } else if (E
.e_machine
== EM_RISCV
)
6870 W
.printFlags("Flags", E
.e_flags
, ArrayRef(ElfHeaderRISCVFlags
));
6871 else if (E
.e_machine
== EM_AVR
)
6872 W
.printFlags("Flags", E
.e_flags
, ArrayRef(ElfHeaderAVRFlags
),
6873 unsigned(ELF::EF_AVR_ARCH_MASK
));
6874 else if (E
.e_machine
== EM_LOONGARCH
)
6875 W
.printFlags("Flags", E
.e_flags
, ArrayRef(ElfHeaderLoongArchFlags
),
6876 unsigned(ELF::EF_LOONGARCH_ABI_MODIFIER_MASK
),
6877 unsigned(ELF::EF_LOONGARCH_OBJABI_MASK
));
6878 else if (E
.e_machine
== EM_XTENSA
)
6879 W
.printFlags("Flags", E
.e_flags
, ArrayRef(ElfHeaderXtensaFlags
),
6880 unsigned(ELF::EF_XTENSA_MACH
));
6882 W
.printFlags("Flags", E
.e_flags
);
6883 W
.printNumber("HeaderSize", E
.e_ehsize
);
6884 W
.printNumber("ProgramHeaderEntrySize", E
.e_phentsize
);
6885 W
.printNumber("ProgramHeaderCount", E
.e_phnum
);
6886 W
.printNumber("SectionHeaderEntrySize", E
.e_shentsize
);
6887 W
.printString("SectionHeaderCount",
6888 getSectionHeadersNumString(this->Obj
, this->FileName
));
6889 W
.printString("StringTableSectionIndex",
6890 getSectionHeaderTableIndexString(this->Obj
, this->FileName
));
6894 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printGroupSections() {
6895 DictScope
Lists(W
, "Groups");
6896 std::vector
<GroupSection
> V
= this->getGroups();
6897 DenseMap
<uint64_t, const GroupSection
*> Map
= mapSectionsToGroups(V
);
6898 for (const GroupSection
&G
: V
) {
6899 DictScope
D(W
, "Group");
6900 W
.printNumber("Name", G
.Name
, G
.ShName
);
6901 W
.printNumber("Index", G
.Index
);
6902 W
.printNumber("Link", G
.Link
);
6903 W
.printNumber("Info", G
.Info
);
6904 W
.printHex("Type", getGroupType(G
.Type
), G
.Type
);
6905 W
.printString("Signature", G
.Signature
);
6907 ListScope
L(W
, getGroupSectionHeaderName());
6908 for (const GroupMember
&GM
: G
.Members
) {
6909 const GroupSection
*MainGroup
= Map
[GM
.Index
];
6910 if (MainGroup
!= &G
)
6911 this->reportUniqueWarning(
6912 "section with index " + Twine(GM
.Index
) +
6913 ", included in the group section with index " +
6914 Twine(MainGroup
->Index
) +
6915 ", was also found in the group section with index " +
6917 printSectionGroupMembers(GM
.Name
, GM
.Index
);
6922 printEmptyGroupMessage();
6925 template <class ELFT
>
6926 std::string LLVMELFDumper
<ELFT
>::getGroupSectionHeaderName() const {
6927 return "Section(s) in group";
6930 template <class ELFT
>
6931 void LLVMELFDumper
<ELFT
>::printSectionGroupMembers(StringRef Name
,
6932 uint64_t Idx
) const {
6933 W
.startLine() << Name
<< " (" << Idx
<< ")\n";
6936 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printRelocations() {
6937 ListScope
D(W
, "Relocations");
6939 for (const Elf_Shdr
&Sec
: cantFail(this->Obj
.sections())) {
6940 if (!isRelocationSec
<ELFT
>(Sec
))
6943 StringRef Name
= this->getPrintableSectionName(Sec
);
6944 unsigned SecNdx
= &Sec
- &cantFail(this->Obj
.sections()).front();
6945 printRelocationSectionInfo(Sec
, Name
, SecNdx
);
6949 template <class ELFT
>
6950 void LLVMELFDumper
<ELFT
>::printRelrReloc(const Elf_Relr
&R
) {
6951 W
.startLine() << W
.hex(R
) << "\n";
6954 template <class ELFT
>
6955 void LLVMELFDumper
<ELFT
>::printExpandedRelRelaReloc(const Relocation
<ELFT
> &R
,
6956 StringRef SymbolName
,
6957 StringRef RelocName
) {
6958 DictScope
Group(W
, "Relocation");
6959 W
.printHex("Offset", R
.Offset
);
6960 W
.printNumber("Type", RelocName
, R
.Type
);
6961 W
.printNumber("Symbol", !SymbolName
.empty() ? SymbolName
: "-", R
.Symbol
);
6963 W
.printHex("Addend", (uintX_t
)*R
.Addend
);
6966 template <class ELFT
>
6967 void LLVMELFDumper
<ELFT
>::printDefaultRelRelaReloc(const Relocation
<ELFT
> &R
,
6968 StringRef SymbolName
,
6969 StringRef RelocName
) {
6970 raw_ostream
&OS
= W
.startLine();
6971 OS
<< W
.hex(R
.Offset
) << " " << RelocName
<< " "
6972 << (!SymbolName
.empty() ? SymbolName
: "-");
6974 OS
<< " " << W
.hex((uintX_t
)*R
.Addend
);
6978 template <class ELFT
>
6979 void LLVMELFDumper
<ELFT
>::printRelocationSectionInfo(const Elf_Shdr
&Sec
,
6981 const unsigned SecNdx
) {
6982 DictScope
D(W
, (Twine("Section (") + Twine(SecNdx
) + ") " + Name
).str());
6983 this->printRelocationsHelper(Sec
);
6986 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printEmptyGroupMessage() const {
6987 W
.startLine() << "There are no group sections in the file.\n";
6990 template <class ELFT
>
6991 void LLVMELFDumper
<ELFT
>::printRelRelaReloc(const Relocation
<ELFT
> &R
,
6992 const RelSymbol
<ELFT
> &RelSym
) {
6993 StringRef SymbolName
= RelSym
.Name
;
6994 if (RelSym
.Sym
&& RelSym
.Name
.empty())
6995 SymbolName
= "<null>";
6996 SmallString
<32> RelocName
;
6997 this->Obj
.getRelocationTypeName(R
.Type
, RelocName
);
6999 if (opts::ExpandRelocs
) {
7000 printExpandedRelRelaReloc(R
, SymbolName
, RelocName
);
7002 printDefaultRelRelaReloc(R
, SymbolName
, RelocName
);
7006 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printSectionHeaders() {
7007 ListScope
SectionsD(W
, "Sections");
7009 int SectionIndex
= -1;
7010 std::vector
<EnumEntry
<unsigned>> FlagsList
=
7011 getSectionFlagsForTarget(this->Obj
.getHeader().e_ident
[ELF::EI_OSABI
],
7012 this->Obj
.getHeader().e_machine
);
7013 for (const Elf_Shdr
&Sec
: cantFail(this->Obj
.sections())) {
7014 DictScope
SectionD(W
, "Section");
7015 W
.printNumber("Index", ++SectionIndex
);
7016 W
.printNumber("Name", this->getPrintableSectionName(Sec
), Sec
.sh_name
);
7018 object::getELFSectionTypeName(this->Obj
.getHeader().e_machine
,
7021 W
.printFlags("Flags", Sec
.sh_flags
, ArrayRef(FlagsList
));
7022 W
.printHex("Address", Sec
.sh_addr
);
7023 W
.printHex("Offset", Sec
.sh_offset
);
7024 W
.printNumber("Size", Sec
.sh_size
);
7025 W
.printNumber("Link", Sec
.sh_link
);
7026 W
.printNumber("Info", Sec
.sh_info
);
7027 W
.printNumber("AddressAlignment", Sec
.sh_addralign
);
7028 W
.printNumber("EntrySize", Sec
.sh_entsize
);
7030 if (opts::SectionRelocations
) {
7031 ListScope
D(W
, "Relocations");
7032 this->printRelocationsHelper(Sec
);
7035 if (opts::SectionSymbols
) {
7036 ListScope
D(W
, "Symbols");
7037 if (this->DotSymtabSec
) {
7038 StringRef StrTable
= unwrapOrError(
7040 this->Obj
.getStringTableForSymtab(*this->DotSymtabSec
));
7041 ArrayRef
<Elf_Word
> ShndxTable
= this->getShndxTable(this->DotSymtabSec
);
7043 typename
ELFT::SymRange Symbols
= unwrapOrError(
7044 this->FileName
, this->Obj
.symbols(this->DotSymtabSec
));
7045 for (const Elf_Sym
&Sym
: Symbols
) {
7046 const Elf_Shdr
*SymSec
= unwrapOrError(
7048 this->Obj
.getSection(Sym
, this->DotSymtabSec
, ShndxTable
));
7050 printSymbol(Sym
, &Sym
- &Symbols
[0], ShndxTable
, StrTable
, false,
7051 /*NonVisibilityBitsUsed=*/false,
7052 /*ExtraSymInfo=*/false);
7057 if (opts::SectionData
&& Sec
.sh_type
!= ELF::SHT_NOBITS
) {
7058 ArrayRef
<uint8_t> Data
=
7059 unwrapOrError(this->FileName
, this->Obj
.getSectionContents(Sec
));
7062 StringRef(reinterpret_cast<const char *>(Data
.data()), Data
.size()));
7067 template <class ELFT
>
7068 void LLVMELFDumper
<ELFT
>::printSymbolSection(
7069 const Elf_Sym
&Symbol
, unsigned SymIndex
,
7070 DataRegion
<Elf_Word
> ShndxTable
) const {
7071 auto GetSectionSpecialType
= [&]() -> std::optional
<StringRef
> {
7072 if (Symbol
.isUndefined())
7073 return StringRef("Undefined");
7074 if (Symbol
.isProcessorSpecific())
7075 return StringRef("Processor Specific");
7076 if (Symbol
.isOSSpecific())
7077 return StringRef("Operating System Specific");
7078 if (Symbol
.isAbsolute())
7079 return StringRef("Absolute");
7080 if (Symbol
.isCommon())
7081 return StringRef("Common");
7082 if (Symbol
.isReserved() && Symbol
.st_shndx
!= SHN_XINDEX
)
7083 return StringRef("Reserved");
7084 return std::nullopt
;
7087 if (std::optional
<StringRef
> Type
= GetSectionSpecialType()) {
7088 W
.printHex("Section", *Type
, Symbol
.st_shndx
);
7092 Expected
<unsigned> SectionIndex
=
7093 this->getSymbolSectionIndex(Symbol
, SymIndex
, ShndxTable
);
7094 if (!SectionIndex
) {
7095 assert(Symbol
.st_shndx
== SHN_XINDEX
&&
7096 "getSymbolSectionIndex should only fail due to an invalid "
7097 "SHT_SYMTAB_SHNDX table/reference");
7098 this->reportUniqueWarning(SectionIndex
.takeError());
7099 W
.printHex("Section", "Reserved", SHN_XINDEX
);
7103 Expected
<StringRef
> SectionName
=
7104 this->getSymbolSectionName(Symbol
, *SectionIndex
);
7106 // Don't report an invalid section name if the section headers are missing.
7107 // In such situations, all sections will be "invalid".
7108 if (!this->ObjF
.sections().empty())
7109 this->reportUniqueWarning(SectionName
.takeError());
7111 consumeError(SectionName
.takeError());
7112 W
.printHex("Section", "<?>", *SectionIndex
);
7114 W
.printHex("Section", *SectionName
, *SectionIndex
);
7118 template <class ELFT
>
7119 void LLVMELFDumper
<ELFT
>::printSymbolOtherField(const Elf_Sym
&Symbol
) const {
7120 std::vector
<EnumEntry
<unsigned>> SymOtherFlags
=
7121 this->getOtherFlagsFromSymbol(this->Obj
.getHeader(), Symbol
);
7122 W
.printFlags("Other", Symbol
.st_other
, ArrayRef(SymOtherFlags
), 0x3u
);
7125 template <class ELFT
>
7126 void LLVMELFDumper
<ELFT
>::printZeroSymbolOtherField(
7127 const Elf_Sym
&Symbol
) const {
7128 assert(Symbol
.st_other
== 0 && "non-zero Other Field");
7129 // Usually st_other flag is zero. Do not pollute the output
7130 // by flags enumeration in that case.
7131 W
.printNumber("Other", 0);
7134 template <class ELFT
>
7135 void LLVMELFDumper
<ELFT
>::printSymbol(const Elf_Sym
&Symbol
, unsigned SymIndex
,
7136 DataRegion
<Elf_Word
> ShndxTable
,
7137 std::optional
<StringRef
> StrTable
,
7139 bool /*NonVisibilityBitsUsed*/,
7140 bool /*ExtraSymInfo*/) const {
7141 std::string FullSymbolName
= this->getFullSymbolName(
7142 Symbol
, SymIndex
, ShndxTable
, StrTable
, IsDynamic
);
7143 unsigned char SymbolType
= Symbol
.getType();
7145 DictScope
D(W
, "Symbol");
7146 W
.printNumber("Name", FullSymbolName
, Symbol
.st_name
);
7147 W
.printHex("Value", Symbol
.st_value
);
7148 W
.printNumber("Size", Symbol
.st_size
);
7149 W
.printEnum("Binding", Symbol
.getBinding(), ArrayRef(ElfSymbolBindings
));
7150 if (this->Obj
.getHeader().e_machine
== ELF::EM_AMDGPU
&&
7151 SymbolType
>= ELF::STT_LOOS
&& SymbolType
< ELF::STT_HIOS
)
7152 W
.printEnum("Type", SymbolType
, ArrayRef(AMDGPUSymbolTypes
));
7154 W
.printEnum("Type", SymbolType
, ArrayRef(ElfSymbolTypes
));
7155 if (Symbol
.st_other
== 0)
7156 printZeroSymbolOtherField(Symbol
);
7158 printSymbolOtherField(Symbol
);
7159 printSymbolSection(Symbol
, SymIndex
, ShndxTable
);
7162 template <class ELFT
>
7163 void LLVMELFDumper
<ELFT
>::printSymbols(bool PrintSymbols
,
7164 bool PrintDynamicSymbols
,
7165 bool ExtraSymInfo
) {
7167 ListScope
Group(W
, "Symbols");
7168 this->printSymbolsHelper(false, ExtraSymInfo
);
7170 if (PrintDynamicSymbols
) {
7171 ListScope
Group(W
, "DynamicSymbols");
7172 this->printSymbolsHelper(true, ExtraSymInfo
);
7176 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printDynamicTable() {
7177 Elf_Dyn_Range Table
= this->dynamic_table();
7181 W
.startLine() << "DynamicSection [ (" << Table
.size() << " entries)\n";
7183 size_t MaxTagSize
= getMaxDynamicTagSize(this->Obj
, Table
);
7184 // The "Name/Value" column should be indented from the "Type" column by N
7185 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
7187 W
.startLine() << " Tag" << std::string(ELFT::Is64Bits
? 16 : 8, ' ')
7188 << "Type" << std::string(MaxTagSize
- 3, ' ') << "Name/Value\n";
7190 std::string ValueFmt
= "%-" + std::to_string(MaxTagSize
) + "s ";
7191 for (auto Entry
: Table
) {
7192 uintX_t Tag
= Entry
.getTag();
7193 std::string Value
= this->getDynamicEntry(Tag
, Entry
.getVal());
7194 W
.startLine() << " " << format_hex(Tag
, ELFT::Is64Bits
? 18 : 10, true)
7196 << format(ValueFmt
.c_str(),
7197 this->Obj
.getDynamicTagAsString(Tag
).c_str())
7200 W
.startLine() << "]\n";
7203 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printDynamicRelocations() {
7204 W
.startLine() << "Dynamic Relocations {\n";
7206 this->printDynamicRelocationsHelper();
7208 W
.startLine() << "}\n";
7211 template <class ELFT
>
7212 void LLVMELFDumper
<ELFT
>::printProgramHeaders(
7213 bool PrintProgramHeaders
, cl::boolOrDefault PrintSectionMapping
) {
7214 if (PrintProgramHeaders
)
7215 printProgramHeaders();
7216 if (PrintSectionMapping
== cl::BOU_TRUE
)
7217 printSectionMapping();
7220 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printProgramHeaders() {
7221 ListScope
L(W
, "ProgramHeaders");
7223 Expected
<ArrayRef
<Elf_Phdr
>> PhdrsOrErr
= this->Obj
.program_headers();
7225 this->reportUniqueWarning("unable to dump program headers: " +
7226 toString(PhdrsOrErr
.takeError()));
7230 for (const Elf_Phdr
&Phdr
: *PhdrsOrErr
) {
7231 DictScope
P(W
, "ProgramHeader");
7233 segmentTypeToString(this->Obj
.getHeader().e_machine
, Phdr
.p_type
);
7235 W
.printHex("Type", Type
.empty() ? "Unknown" : Type
, Phdr
.p_type
);
7236 W
.printHex("Offset", Phdr
.p_offset
);
7237 W
.printHex("VirtualAddress", Phdr
.p_vaddr
);
7238 W
.printHex("PhysicalAddress", Phdr
.p_paddr
);
7239 W
.printNumber("FileSize", Phdr
.p_filesz
);
7240 W
.printNumber("MemSize", Phdr
.p_memsz
);
7241 W
.printFlags("Flags", Phdr
.p_flags
, ArrayRef(ElfSegmentFlags
));
7242 W
.printNumber("Alignment", Phdr
.p_align
);
7246 template <class ELFT
>
7247 void LLVMELFDumper
<ELFT
>::printVersionSymbolSection(const Elf_Shdr
*Sec
) {
7248 ListScope
SS(W
, "VersionSymbols");
7253 ArrayRef
<Elf_Sym
> Syms
;
7254 const Elf_Shdr
*SymTabSec
;
7255 Expected
<ArrayRef
<Elf_Versym
>> VerTableOrErr
=
7256 this->getVersionTable(*Sec
, &Syms
, &StrTable
, &SymTabSec
);
7257 if (!VerTableOrErr
) {
7258 this->reportUniqueWarning(VerTableOrErr
.takeError());
7262 if (StrTable
.empty() || Syms
.empty() || Syms
.size() != VerTableOrErr
->size())
7265 ArrayRef
<Elf_Word
> ShNdxTable
= this->getShndxTable(SymTabSec
);
7266 for (size_t I
= 0, E
= Syms
.size(); I
< E
; ++I
) {
7267 DictScope
S(W
, "Symbol");
7268 W
.printNumber("Version", (*VerTableOrErr
)[I
].vs_index
& VERSYM_VERSION
);
7269 W
.printString("Name",
7270 this->getFullSymbolName(Syms
[I
], I
, ShNdxTable
, StrTable
,
7271 /*IsDynamic=*/true));
7275 const EnumEntry
<unsigned> SymVersionFlags
[] = {
7276 {"Base", "BASE", VER_FLG_BASE
},
7277 {"Weak", "WEAK", VER_FLG_WEAK
},
7278 {"Info", "INFO", VER_FLG_INFO
}};
7280 template <class ELFT
>
7281 void LLVMELFDumper
<ELFT
>::printVersionDefinitionSection(const Elf_Shdr
*Sec
) {
7282 ListScope
SD(W
, "VersionDefinitions");
7286 Expected
<std::vector
<VerDef
>> V
= this->Obj
.getVersionDefinitions(*Sec
);
7288 this->reportUniqueWarning(V
.takeError());
7292 for (const VerDef
&D
: *V
) {
7293 DictScope
Def(W
, "Definition");
7294 W
.printNumber("Version", D
.Version
);
7295 W
.printFlags("Flags", D
.Flags
, ArrayRef(SymVersionFlags
));
7296 W
.printNumber("Index", D
.Ndx
);
7297 W
.printNumber("Hash", D
.Hash
);
7298 W
.printString("Name", D
.Name
.c_str());
7300 "Predecessors", D
.AuxV
,
7301 [](raw_ostream
&OS
, const VerdAux
&Aux
) { OS
<< Aux
.Name
.c_str(); });
7305 template <class ELFT
>
7306 void LLVMELFDumper
<ELFT
>::printVersionDependencySection(const Elf_Shdr
*Sec
) {
7307 ListScope
SD(W
, "VersionRequirements");
7311 Expected
<std::vector
<VerNeed
>> V
=
7312 this->Obj
.getVersionDependencies(*Sec
, this->WarningHandler
);
7314 this->reportUniqueWarning(V
.takeError());
7318 for (const VerNeed
&VN
: *V
) {
7319 DictScope
Entry(W
, "Dependency");
7320 W
.printNumber("Version", VN
.Version
);
7321 W
.printNumber("Count", VN
.Cnt
);
7322 W
.printString("FileName", VN
.File
.c_str());
7324 ListScope
L(W
, "Entries");
7325 for (const VernAux
&Aux
: VN
.AuxV
) {
7326 DictScope
Entry(W
, "Entry");
7327 W
.printNumber("Hash", Aux
.Hash
);
7328 W
.printFlags("Flags", Aux
.Flags
, ArrayRef(SymVersionFlags
));
7329 W
.printNumber("Index", Aux
.Other
);
7330 W
.printString("Name", Aux
.Name
.c_str());
7335 template <class ELFT
>
7336 void LLVMELFDumper
<ELFT
>::printHashHistogramStats(size_t NBucket
,
7339 ArrayRef
<size_t> Count
,
7341 StringRef HistName
= IsGnu
? "GnuHashHistogram" : "HashHistogram";
7342 StringRef BucketName
= IsGnu
? "Bucket" : "Chain";
7343 StringRef ListName
= IsGnu
? "Buckets" : "Chains";
7344 DictScope
Outer(W
, HistName
);
7345 W
.printNumber("TotalBuckets", NBucket
);
7346 ListScope
Buckets(W
, ListName
);
7347 size_t CumulativeNonZero
= 0;
7348 for (size_t I
= 0; I
< MaxChain
; ++I
) {
7349 CumulativeNonZero
+= Count
[I
] * I
;
7350 DictScope
Bucket(W
, BucketName
);
7351 W
.printNumber("Length", I
);
7352 W
.printNumber("Count", Count
[I
]);
7353 W
.printNumber("Percentage", (float)(Count
[I
] * 100.0) / NBucket
);
7354 W
.printNumber("Coverage", (float)(CumulativeNonZero
* 100.0) / TotalSyms
);
7358 // Returns true if rel/rela section exists, and populates SymbolIndices.
7359 // Otherwise returns false.
7360 template <class ELFT
>
7361 static bool getSymbolIndices(const typename
ELFT::Shdr
*CGRelSection
,
7362 const ELFFile
<ELFT
> &Obj
,
7363 const LLVMELFDumper
<ELFT
> *Dumper
,
7364 SmallVector
<uint32_t, 128> &SymbolIndices
) {
7365 if (!CGRelSection
) {
7366 Dumper
->reportUniqueWarning(
7367 "relocation section for a call graph section doesn't exist");
7371 if (CGRelSection
->sh_type
== SHT_REL
) {
7372 typename
ELFT::RelRange CGProfileRel
;
7373 Expected
<typename
ELFT::RelRange
> CGProfileRelOrError
=
7374 Obj
.rels(*CGRelSection
);
7375 if (!CGProfileRelOrError
) {
7376 Dumper
->reportUniqueWarning("unable to load relocations for "
7377 "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
7378 toString(CGProfileRelOrError
.takeError()));
7382 CGProfileRel
= *CGProfileRelOrError
;
7383 for (const typename
ELFT::Rel
&Rel
: CGProfileRel
)
7384 SymbolIndices
.push_back(Rel
.getSymbol(Obj
.isMips64EL()));
7386 // MC unconditionally produces SHT_REL, but GNU strip/objcopy may convert
7387 // the format to SHT_RELA
7388 // (https://sourceware.org/bugzilla/show_bug.cgi?id=28035)
7389 typename
ELFT::RelaRange CGProfileRela
;
7390 Expected
<typename
ELFT::RelaRange
> CGProfileRelaOrError
=
7391 Obj
.relas(*CGRelSection
);
7392 if (!CGProfileRelaOrError
) {
7393 Dumper
->reportUniqueWarning("unable to load relocations for "
7394 "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
7395 toString(CGProfileRelaOrError
.takeError()));
7399 CGProfileRela
= *CGProfileRelaOrError
;
7400 for (const typename
ELFT::Rela
&Rela
: CGProfileRela
)
7401 SymbolIndices
.push_back(Rela
.getSymbol(Obj
.isMips64EL()));
7407 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printCGProfile() {
7408 auto IsMatch
= [](const Elf_Shdr
&Sec
) -> bool {
7409 return Sec
.sh_type
== ELF::SHT_LLVM_CALL_GRAPH_PROFILE
;
7412 Expected
<MapVector
<const Elf_Shdr
*, const Elf_Shdr
*>> SecToRelocMapOrErr
=
7413 this->Obj
.getSectionAndRelocations(IsMatch
);
7414 if (!SecToRelocMapOrErr
) {
7415 this->reportUniqueWarning("unable to get CG Profile section(s): " +
7416 toString(SecToRelocMapOrErr
.takeError()));
7420 for (const auto &CGMapEntry
: *SecToRelocMapOrErr
) {
7421 const Elf_Shdr
*CGSection
= CGMapEntry
.first
;
7422 const Elf_Shdr
*CGRelSection
= CGMapEntry
.second
;
7424 Expected
<ArrayRef
<Elf_CGProfile
>> CGProfileOrErr
=
7425 this->Obj
.template getSectionContentsAsArray
<Elf_CGProfile
>(*CGSection
);
7426 if (!CGProfileOrErr
) {
7427 this->reportUniqueWarning(
7428 "unable to load the SHT_LLVM_CALL_GRAPH_PROFILE section: " +
7429 toString(CGProfileOrErr
.takeError()));
7433 SmallVector
<uint32_t, 128> SymbolIndices
;
7435 getSymbolIndices
<ELFT
>(CGRelSection
, this->Obj
, this, SymbolIndices
);
7436 if (UseReloc
&& SymbolIndices
.size() != CGProfileOrErr
->size() * 2) {
7437 this->reportUniqueWarning(
7438 "number of from/to pairs does not match number of frequencies");
7442 ListScope
L(W
, "CGProfile");
7443 for (uint32_t I
= 0, Size
= CGProfileOrErr
->size(); I
!= Size
; ++I
) {
7444 const Elf_CGProfile
&CGPE
= (*CGProfileOrErr
)[I
];
7445 DictScope
D(W
, "CGProfileEntry");
7447 uint32_t From
= SymbolIndices
[I
* 2];
7448 uint32_t To
= SymbolIndices
[I
* 2 + 1];
7449 W
.printNumber("From", this->getStaticSymbolName(From
), From
);
7450 W
.printNumber("To", this->getStaticSymbolName(To
), To
);
7452 W
.printNumber("Weight", CGPE
.cgp_weight
);
7457 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printBBAddrMaps() {
7458 bool IsRelocatable
= this->Obj
.getHeader().e_type
== ELF::ET_REL
;
7459 using Elf_Shdr
= typename
ELFT::Shdr
;
7460 auto IsMatch
= [](const Elf_Shdr
&Sec
) -> bool {
7461 return Sec
.sh_type
== ELF::SHT_LLVM_BB_ADDR_MAP
||
7462 Sec
.sh_type
== ELF::SHT_LLVM_BB_ADDR_MAP_V0
;
7464 Expected
<MapVector
<const Elf_Shdr
*, const Elf_Shdr
*>> SecRelocMapOrErr
=
7465 this->Obj
.getSectionAndRelocations(IsMatch
);
7466 if (!SecRelocMapOrErr
) {
7467 this->reportUniqueWarning(
7468 "failed to get SHT_LLVM_BB_ADDR_MAP section(s): " +
7469 toString(SecRelocMapOrErr
.takeError()));
7472 for (auto const &[Sec
, RelocSec
] : *SecRelocMapOrErr
) {
7473 std::optional
<const Elf_Shdr
*> FunctionSec
;
7476 unwrapOrError(this->FileName
, this->Obj
.getSection(Sec
->sh_link
));
7477 ListScope
L(W
, "BBAddrMap");
7478 if (IsRelocatable
&& !RelocSec
) {
7479 this->reportUniqueWarning("unable to get relocation section for " +
7480 this->describe(*Sec
));
7483 Expected
<std::vector
<BBAddrMap
>> BBAddrMapOrErr
=
7484 this->Obj
.decodeBBAddrMap(*Sec
, RelocSec
);
7485 if (!BBAddrMapOrErr
) {
7486 this->reportUniqueWarning("unable to dump " + this->describe(*Sec
) +
7487 ": " + toString(BBAddrMapOrErr
.takeError()));
7490 for (const BBAddrMap
&AM
: *BBAddrMapOrErr
) {
7491 DictScope
D(W
, "Function");
7492 W
.printHex("At", AM
.Addr
);
7493 SmallVector
<uint32_t> FuncSymIndex
=
7494 this->getSymbolIndexesForFunctionAddress(AM
.Addr
, FunctionSec
);
7495 std::string FuncName
= "<?>";
7496 if (FuncSymIndex
.empty())
7497 this->reportUniqueWarning(
7498 "could not identify function symbol for address (0x" +
7499 Twine::utohexstr(AM
.Addr
) + ") in " + this->describe(*Sec
));
7501 FuncName
= this->getStaticSymbolName(FuncSymIndex
.front());
7502 W
.printString("Name", FuncName
);
7504 ListScope
L(W
, "BB entries");
7505 for (const BBAddrMap::BBEntry
&BBE
: AM
.BBEntries
) {
7507 W
.printNumber("ID", BBE
.ID
);
7508 W
.printHex("Offset", BBE
.Offset
);
7509 W
.printHex("Size", BBE
.Size
);
7510 W
.printBoolean("HasReturn", BBE
.hasReturn());
7511 W
.printBoolean("HasTailCall", BBE
.hasTailCall());
7512 W
.printBoolean("IsEHPad", BBE
.isEHPad());
7513 W
.printBoolean("CanFallThrough", BBE
.canFallThrough());
7514 W
.printBoolean("HasIndirectBranch", BBE
.hasIndirectBranch());
7520 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printAddrsig() {
7521 ListScope
L(W
, "Addrsig");
7522 if (!this->DotAddrsigSec
)
7525 Expected
<std::vector
<uint64_t>> SymsOrErr
=
7526 decodeAddrsigSection(this->Obj
, *this->DotAddrsigSec
);
7528 this->reportUniqueWarning(SymsOrErr
.takeError());
7532 for (uint64_t Sym
: *SymsOrErr
)
7533 W
.printNumber("Sym", this->getStaticSymbolName(Sym
), Sym
);
7536 template <typename ELFT
>
7537 static bool printGNUNoteLLVMStyle(uint32_t NoteType
, ArrayRef
<uint8_t> Desc
,
7539 // Return true if we were able to pretty-print the note, false otherwise.
7543 case ELF::NT_GNU_ABI_TAG
: {
7544 const GNUAbiTag
&AbiTag
= getGNUAbiTag
<ELFT
>(Desc
);
7545 if (!AbiTag
.IsValid
) {
7546 W
.printString("ABI", "<corrupt GNU_ABI_TAG>");
7549 W
.printString("OS", AbiTag
.OSName
);
7550 W
.printString("ABI", AbiTag
.ABI
);
7554 case ELF::NT_GNU_BUILD_ID
: {
7555 W
.printString("Build ID", getGNUBuildId(Desc
));
7558 case ELF::NT_GNU_GOLD_VERSION
:
7559 W
.printString("Version", getDescAsStringRef(Desc
));
7561 case ELF::NT_GNU_PROPERTY_TYPE_0
:
7562 ListScope
D(W
, "Property");
7563 for (const std::string
&Property
: getGNUPropertyList
<ELFT
>(Desc
))
7564 W
.printString(Property
);
7570 static bool printAndroidNoteLLVMStyle(uint32_t NoteType
, ArrayRef
<uint8_t> Desc
,
7572 // Return true if we were able to pretty-print the note, false otherwise.
7573 AndroidNoteProperties Props
= getAndroidNoteProperties(NoteType
, Desc
);
7576 for (const auto &KV
: Props
)
7577 W
.printString(KV
.first
, KV
.second
);
7581 template <class ELFT
>
7582 void LLVMELFDumper
<ELFT
>::printMemtag(
7583 const ArrayRef
<std::pair
<std::string
, std::string
>> DynamicEntries
,
7584 const ArrayRef
<uint8_t> AndroidNoteDesc
,
7585 const ArrayRef
<std::pair
<uint64_t, uint64_t>> Descriptors
) {
7587 ListScope
L(W
, "Memtag Dynamic Entries:");
7588 if (DynamicEntries
.empty())
7589 W
.printString("< none found >");
7590 for (const auto &DynamicEntryKV
: DynamicEntries
)
7591 W
.printString(DynamicEntryKV
.first
, DynamicEntryKV
.second
);
7594 if (!AndroidNoteDesc
.empty()) {
7595 ListScope
L(W
, "Memtag Android Note:");
7596 printAndroidNoteLLVMStyle(ELF::NT_ANDROID_TYPE_MEMTAG
, AndroidNoteDesc
, W
);
7599 if (Descriptors
.empty())
7603 ListScope
L(W
, "Memtag Global Descriptors:");
7604 for (const auto &[Addr
, BytesToTag
] : Descriptors
) {
7605 W
.printHex("0x" + utohexstr(Addr
), BytesToTag
);
7610 template <typename ELFT
>
7611 static bool printLLVMOMPOFFLOADNoteLLVMStyle(uint32_t NoteType
,
7612 ArrayRef
<uint8_t> Desc
,
7617 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION
:
7618 W
.printString("Version", getDescAsStringRef(Desc
));
7620 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER
:
7621 W
.printString("Producer", getDescAsStringRef(Desc
));
7623 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION
:
7624 W
.printString("Producer version", getDescAsStringRef(Desc
));
7630 static void printCoreNoteLLVMStyle(const CoreNote
&Note
, ScopedPrinter
&W
) {
7631 W
.printNumber("Page Size", Note
.PageSize
);
7632 for (const CoreFileMapping
&Mapping
: Note
.Mappings
) {
7633 ListScope
D(W
, "Mapping");
7634 W
.printHex("Start", Mapping
.Start
);
7635 W
.printHex("End", Mapping
.End
);
7636 W
.printHex("Offset", Mapping
.Offset
);
7637 W
.printString("Filename", Mapping
.Filename
);
7641 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printNotes() {
7642 ListScope
L(W
, "Notes");
7644 std::unique_ptr
<DictScope
> NoteScope
;
7646 auto StartNotes
= [&](std::optional
<StringRef
> SecName
,
7647 const typename
ELFT::Off Offset
,
7648 const typename
ELFT::Addr Size
, size_t Al
) {
7649 Align
= std::max
<size_t>(Al
, 4);
7650 NoteScope
= std::make_unique
<DictScope
>(W
, "NoteSection");
7651 W
.printString("Name", SecName
? *SecName
: "<?>");
7652 W
.printHex("Offset", Offset
);
7653 W
.printHex("Size", Size
);
7656 auto EndNotes
= [&] { NoteScope
.reset(); };
7658 auto ProcessNote
= [&](const Elf_Note
&Note
, bool IsCore
) -> Error
{
7659 DictScope
D2(W
, "Note");
7660 StringRef Name
= Note
.getName();
7661 ArrayRef
<uint8_t> Descriptor
= Note
.getDesc(Align
);
7662 Elf_Word Type
= Note
.getType();
7664 // Print the note owner/type.
7665 W
.printString("Owner", Name
);
7666 W
.printHex("Data size", Descriptor
.size());
7668 StringRef NoteType
=
7669 getNoteTypeName
<ELFT
>(Note
, this->Obj
.getHeader().e_type
);
7670 if (!NoteType
.empty())
7671 W
.printString("Type", NoteType
);
7673 W
.printString("Type",
7674 "Unknown (" + to_string(format_hex(Type
, 10)) + ")");
7676 // Print the description, or fallback to printing raw bytes for unknown
7677 // owners/if we fail to pretty-print the contents.
7678 if (Name
== "GNU") {
7679 if (printGNUNoteLLVMStyle
<ELFT
>(Type
, Descriptor
, W
))
7680 return Error::success();
7681 } else if (Name
== "FreeBSD") {
7682 if (std::optional
<FreeBSDNote
> N
=
7683 getFreeBSDNote
<ELFT
>(Type
, Descriptor
, IsCore
)) {
7684 W
.printString(N
->Type
, N
->Value
);
7685 return Error::success();
7687 } else if (Name
== "AMD") {
7688 const AMDNote N
= getAMDNote
<ELFT
>(Type
, Descriptor
);
7689 if (!N
.Type
.empty()) {
7690 W
.printString(N
.Type
, N
.Value
);
7691 return Error::success();
7693 } else if (Name
== "AMDGPU") {
7694 const AMDGPUNote N
= getAMDGPUNote
<ELFT
>(Type
, Descriptor
);
7695 if (!N
.Type
.empty()) {
7696 W
.printString(N
.Type
, N
.Value
);
7697 return Error::success();
7699 } else if (Name
== "LLVMOMPOFFLOAD") {
7700 if (printLLVMOMPOFFLOADNoteLLVMStyle
<ELFT
>(Type
, Descriptor
, W
))
7701 return Error::success();
7702 } else if (Name
== "CORE") {
7703 if (Type
== ELF::NT_FILE
) {
7704 DataExtractor
DescExtractor(
7705 Descriptor
, ELFT::TargetEndianness
== llvm::endianness::little
,
7707 if (Expected
<CoreNote
> N
= readCoreNote(DescExtractor
)) {
7708 printCoreNoteLLVMStyle(*N
, W
);
7709 return Error::success();
7711 return N
.takeError();
7714 } else if (Name
== "Android") {
7715 if (printAndroidNoteLLVMStyle(Type
, Descriptor
, W
))
7716 return Error::success();
7718 if (!Descriptor
.empty()) {
7719 W
.printBinaryBlock("Description data", Descriptor
);
7721 return Error::success();
7724 processNotesHelper(*this, /*StartNotesFn=*/StartNotes
,
7725 /*ProcessNoteFn=*/ProcessNote
, /*FinishNotesFn=*/EndNotes
);
7728 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printELFLinkerOptions() {
7729 ListScope
L(W
, "LinkerOptions");
7732 for (const Elf_Shdr
&Shdr
: cantFail(this->Obj
.sections())) {
7734 if (Shdr
.sh_type
!= ELF::SHT_LLVM_LINKER_OPTIONS
)
7737 Expected
<ArrayRef
<uint8_t>> ContentsOrErr
=
7738 this->Obj
.getSectionContents(Shdr
);
7739 if (!ContentsOrErr
) {
7740 this->reportUniqueWarning("unable to read the content of the "
7741 "SHT_LLVM_LINKER_OPTIONS section: " +
7742 toString(ContentsOrErr
.takeError()));
7745 if (ContentsOrErr
->empty())
7748 if (ContentsOrErr
->back() != 0) {
7749 this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " +
7752 "content is not null-terminated");
7756 SmallVector
<StringRef
, 16> Strings
;
7757 toStringRef(ContentsOrErr
->drop_back()).split(Strings
, '\0');
7758 if (Strings
.size() % 2 != 0) {
7759 this->reportUniqueWarning(
7760 "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I
) +
7761 " is broken: an incomplete "
7762 "key-value pair was found. The last possible key was: \"" +
7763 Strings
.back() + "\"");
7767 for (size_t I
= 0; I
< Strings
.size(); I
+= 2)
7768 W
.printString(Strings
[I
], Strings
[I
+ 1]);
7772 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printDependentLibs() {
7773 ListScope
L(W
, "DependentLibs");
7774 this->printDependentLibsHelper(
7775 [](const Elf_Shdr
&) {},
7776 [this](StringRef Lib
, uint64_t) { W
.printString(Lib
); });
7779 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printStackSizes() {
7780 ListScope
L(W
, "StackSizes");
7781 if (this->Obj
.getHeader().e_type
== ELF::ET_REL
)
7782 this->printRelocatableStackSizes([]() {});
7784 this->printNonRelocatableStackSizes([]() {});
7787 template <class ELFT
>
7788 void LLVMELFDumper
<ELFT
>::printStackSizeEntry(uint64_t Size
,
7789 ArrayRef
<std::string
> FuncNames
) {
7790 DictScope
D(W
, "Entry");
7791 W
.printList("Functions", FuncNames
);
7792 W
.printHex("Size", Size
);
7795 template <class ELFT
>
7796 void LLVMELFDumper
<ELFT
>::printMipsGOT(const MipsGOTParser
<ELFT
> &Parser
) {
7797 auto PrintEntry
= [&](const Elf_Addr
*E
) {
7798 W
.printHex("Address", Parser
.getGotAddress(E
));
7799 W
.printNumber("Access", Parser
.getGotOffset(E
));
7800 W
.printHex("Initial", *E
);
7803 DictScope
GS(W
, Parser
.IsStatic
? "Static GOT" : "Primary GOT");
7805 W
.printHex("Canonical gp value", Parser
.getGp());
7807 ListScope
RS(W
, "Reserved entries");
7809 DictScope
D(W
, "Entry");
7810 PrintEntry(Parser
.getGotLazyResolver());
7811 W
.printString("Purpose", StringRef("Lazy resolver"));
7814 if (Parser
.getGotModulePointer()) {
7815 DictScope
D(W
, "Entry");
7816 PrintEntry(Parser
.getGotModulePointer());
7817 W
.printString("Purpose", StringRef("Module pointer (GNU extension)"));
7821 ListScope
LS(W
, "Local entries");
7822 for (auto &E
: Parser
.getLocalEntries()) {
7823 DictScope
D(W
, "Entry");
7828 if (Parser
.IsStatic
)
7832 ListScope
GS(W
, "Global entries");
7833 for (auto &E
: Parser
.getGlobalEntries()) {
7834 DictScope
D(W
, "Entry");
7838 const Elf_Sym
&Sym
= *Parser
.getGotSym(&E
);
7839 W
.printHex("Value", Sym
.st_value
);
7840 W
.printEnum("Type", Sym
.getType(), ArrayRef(ElfSymbolTypes
));
7842 const unsigned SymIndex
= &Sym
- this->dynamic_symbols().begin();
7843 DataRegion
<Elf_Word
> ShndxTable(
7844 (const Elf_Word
*)this->DynSymTabShndxRegion
.Addr
, this->Obj
.end());
7845 printSymbolSection(Sym
, SymIndex
, ShndxTable
);
7847 std::string SymName
= this->getFullSymbolName(
7848 Sym
, SymIndex
, ShndxTable
, this->DynamicStringTable
, true);
7849 W
.printNumber("Name", SymName
, Sym
.st_name
);
7853 W
.printNumber("Number of TLS and multi-GOT entries",
7854 uint64_t(Parser
.getOtherEntries().size()));
7857 template <class ELFT
>
7858 void LLVMELFDumper
<ELFT
>::printMipsPLT(const MipsGOTParser
<ELFT
> &Parser
) {
7859 auto PrintEntry
= [&](const Elf_Addr
*E
) {
7860 W
.printHex("Address", Parser
.getPltAddress(E
));
7861 W
.printHex("Initial", *E
);
7864 DictScope
GS(W
, "PLT GOT");
7867 ListScope
RS(W
, "Reserved entries");
7869 DictScope
D(W
, "Entry");
7870 PrintEntry(Parser
.getPltLazyResolver());
7871 W
.printString("Purpose", StringRef("PLT lazy resolver"));
7874 if (auto E
= Parser
.getPltModulePointer()) {
7875 DictScope
D(W
, "Entry");
7877 W
.printString("Purpose", StringRef("Module pointer"));
7881 ListScope
LS(W
, "Entries");
7882 DataRegion
<Elf_Word
> ShndxTable(
7883 (const Elf_Word
*)this->DynSymTabShndxRegion
.Addr
, this->Obj
.end());
7884 for (auto &E
: Parser
.getPltEntries()) {
7885 DictScope
D(W
, "Entry");
7888 const Elf_Sym
&Sym
= *Parser
.getPltSym(&E
);
7889 W
.printHex("Value", Sym
.st_value
);
7890 W
.printEnum("Type", Sym
.getType(), ArrayRef(ElfSymbolTypes
));
7891 printSymbolSection(Sym
, &Sym
- this->dynamic_symbols().begin(),
7894 const Elf_Sym
*FirstSym
= cantFail(
7895 this->Obj
.template getEntry
<Elf_Sym
>(*Parser
.getPltSymTable(), 0));
7896 std::string SymName
= this->getFullSymbolName(
7897 Sym
, &Sym
- FirstSym
, ShndxTable
, Parser
.getPltStrTable(), true);
7898 W
.printNumber("Name", SymName
, Sym
.st_name
);
7903 template <class ELFT
> void LLVMELFDumper
<ELFT
>::printMipsABIFlags() {
7904 const Elf_Mips_ABIFlags
<ELFT
> *Flags
;
7905 if (Expected
<const Elf_Mips_ABIFlags
<ELFT
> *> SecOrErr
=
7906 getMipsAbiFlagsSection(*this)) {
7909 W
.startLine() << "There is no .MIPS.abiflags section in the file.\n";
7913 this->reportUniqueWarning(SecOrErr
.takeError());
7917 raw_ostream
&OS
= W
.getOStream();
7918 DictScope
GS(W
, "MIPS ABI Flags");
7920 W
.printNumber("Version", Flags
->version
);
7921 W
.startLine() << "ISA: ";
7922 if (Flags
->isa_rev
<= 1)
7923 OS
<< format("MIPS%u", Flags
->isa_level
);
7925 OS
<< format("MIPS%ur%u", Flags
->isa_level
, Flags
->isa_rev
);
7927 W
.printEnum("ISA Extension", Flags
->isa_ext
, ArrayRef(ElfMipsISAExtType
));
7928 W
.printFlags("ASEs", Flags
->ases
, ArrayRef(ElfMipsASEFlags
));
7929 W
.printEnum("FP ABI", Flags
->fp_abi
, ArrayRef(ElfMipsFpABIType
));
7930 W
.printNumber("GPR size", getMipsRegisterSize(Flags
->gpr_size
));
7931 W
.printNumber("CPR1 size", getMipsRegisterSize(Flags
->cpr1_size
));
7932 W
.printNumber("CPR2 size", getMipsRegisterSize(Flags
->cpr2_size
));
7933 W
.printFlags("Flags 1", Flags
->flags1
, ArrayRef(ElfMipsFlags1
));
7934 W
.printHex("Flags 2", Flags
->flags2
);
7937 template <class ELFT
>
7938 void JSONELFDumper
<ELFT
>::printFileSummary(StringRef FileStr
, ObjectFile
&Obj
,
7939 ArrayRef
<std::string
> InputFilenames
,
7941 FileScope
= std::make_unique
<DictScope
>(this->W
);
7942 DictScope
D(this->W
, "FileSummary");
7943 this->W
.printString("File", FileStr
);
7944 this->W
.printString("Format", Obj
.getFileFormatName());
7945 this->W
.printString("Arch", Triple::getArchTypeName(Obj
.getArch()));
7946 this->W
.printString(
7948 std::string(formatv("{0}bit", 8 * Obj
.getBytesInAddress())));
7949 this->printLoadName();
7952 template <class ELFT
>
7953 void JSONELFDumper
<ELFT
>::printZeroSymbolOtherField(
7954 const Elf_Sym
&Symbol
) const {
7955 // We want the JSON format to be uniform, since it is machine readable, so
7956 // always print the `Other` field the same way.
7957 this->printSymbolOtherField(Symbol
);
7960 template <class ELFT
>
7961 void JSONELFDumper
<ELFT
>::printDefaultRelRelaReloc(const Relocation
<ELFT
> &R
,
7962 StringRef SymbolName
,
7963 StringRef RelocName
) {
7964 this->printExpandedRelRelaReloc(R
, SymbolName
, RelocName
);
7967 template <class ELFT
>
7968 void JSONELFDumper
<ELFT
>::printRelocationSectionInfo(const Elf_Shdr
&Sec
,
7970 const unsigned SecNdx
) {
7971 DictScope
Group(this->W
);
7972 this->W
.printNumber("SectionIndex", SecNdx
);
7973 ListScope
D(this->W
, "Relocs");
7974 this->printRelocationsHelper(Sec
);
7977 template <class ELFT
>
7978 std::string JSONELFDumper
<ELFT
>::getGroupSectionHeaderName() const {
7979 return "GroupSections";
7982 template <class ELFT
>
7983 void JSONELFDumper
<ELFT
>::printSectionGroupMembers(StringRef Name
,
7984 uint64_t Idx
) const {
7985 DictScope
Grp(this->W
);
7986 this->W
.printString("Name", Name
);
7987 this->W
.printNumber("Index", Idx
);
7990 template <class ELFT
> void JSONELFDumper
<ELFT
>::printEmptyGroupMessage() const {
7991 // JSON output does not need to print anything for empty groups