1//===- ELFDumper.cpp - ELF-specific dumper --------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements the ELF-specific dumper for llvm-readobj.
11///
12//===----------------------------------------------------------------------===//
13
14#include "ARMEHABIPrinter.h"
15#include "DwarfCFIEHPrinter.h"
16#include "ObjDumper.h"
17#include "StackMapPrinter.h"
18#include "llvm-readobj.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/DenseSet.h"
23#include "llvm/ADT/MapVector.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallSet.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/BinaryFormat/SFrame.h"
35#include "llvm/Demangle/Demangle.h"
36#include "llvm/Object/Archive.h"
37#include "llvm/Object/ELF.h"
38#include "llvm/Object/ELFObjectFile.h"
39#include "llvm/Object/ELFTypes.h"
40#include "llvm/Object/Error.h"
41#include "llvm/Object/ObjectFile.h"
42#include "llvm/Object/RelocationResolver.h"
43#include "llvm/Object/SFrameParser.h"
44#include "llvm/Object/StackMapParser.h"
45#include "llvm/Support/AArch64AttributeParser.h"
46#include "llvm/Support/AMDGPUMetadata.h"
47#include "llvm/Support/ARMAttributeParser.h"
48#include "llvm/Support/ARMBuildAttributes.h"
49#include "llvm/Support/Casting.h"
50#include "llvm/Support/Compiler.h"
51#include "llvm/Support/Endian.h"
52#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/Format.h"
54#include "llvm/Support/FormatVariadic.h"
55#include "llvm/Support/FormattedStream.h"
56#include "llvm/Support/HexagonAttributeParser.h"
57#include "llvm/Support/LEB128.h"
58#include "llvm/Support/MSP430AttributeParser.h"
59#include "llvm/Support/MSP430Attributes.h"
60#include "llvm/Support/MathExtras.h"
61#include "llvm/Support/MipsABIFlags.h"
62#include "llvm/Support/RISCVAttributeParser.h"
63#include "llvm/Support/RISCVAttributes.h"
64#include "llvm/Support/ScopedPrinter.h"
65#include "llvm/Support/raw_ostream.h"
66#include <algorithm>
67#include <array>
68#include <cinttypes>
69#include <cstddef>
70#include <cstdint>
71#include <cstdlib>
72#include <iterator>
73#include <memory>
74#include <optional>
75#include <string>
76#include <system_error>
77#include <vector>
78
79using namespace llvm;
80using namespace llvm::object;
81using namespace llvm::support;
82using namespace ELF;
83
84#define LLVM_READOBJ_ENUM_CASE(ns, enum) \
85 case ns::enum: \
86 return #enum;
87
88#define ENUM_ENT(enum, altName) {{#enum, altName}, ELF::enum}
89
90#define ENUM_ENT_1(enum) {{#enum, #enum}, ELF::enum}
91
92namespace {
93
94template <class ELFT> struct RelSymbol {
95 RelSymbol(const typename ELFT::Sym *S, StringRef N)
96 : Sym(S), Name(N.str()) {}
97 const typename ELFT::Sym *Sym;
98 std::string Name;
99};
100
101/// Represents a contiguous uniform range in the file. We cannot just create a
102/// range directly because when creating one of these from the .dynamic table
103/// the size, entity size and virtual address are different entries in arbitrary
104/// order (DT_REL, DT_RELSZ, DT_RELENT for example).
105struct DynRegionInfo {
106 DynRegionInfo(const Binary &Owner, const ObjDumper &D)
107 : Obj(&Owner), Dumper(&D) {}
108 DynRegionInfo(const Binary &Owner, const ObjDumper &D, const uint8_t *A,
109 uint64_t S, uint64_t ES)
110 : Addr(A), Size(S), EntSize(ES), Obj(&Owner), Dumper(&D) {}
111
112 /// Address in current address space.
113 const uint8_t *Addr = nullptr;
114 /// Size in bytes of the region.
115 uint64_t Size = 0;
116 /// Size of each entity in the region.
117 uint64_t EntSize = 0;
118
119 /// Owner object. Used for error reporting.
120 const Binary *Obj;
121 /// Dumper used for error reporting.
122 const ObjDumper *Dumper;
123 /// Error prefix. Used for error reporting to provide more information.
124 std::string Context;
125 /// Region size name. Used for error reporting.
126 StringRef SizePrintName = "size";
127 /// Entry size name. Used for error reporting. If this field is empty, errors
128 /// will not mention the entry size.
129 StringRef EntSizePrintName = "entry size";
130
131 template <typename Type> ArrayRef<Type> getAsArrayRef() const {
132 const Type *Start = reinterpret_cast<const Type *>(Addr);
133 if (!Start)
134 return {Start, Start};
135
136 const uint64_t Offset =
137 Addr - (const uint8_t *)Obj->getMemoryBufferRef().getBufferStart();
138 const uint64_t ObjSize = Obj->getMemoryBufferRef().getBufferSize();
139
140 if (Size > ObjSize - Offset) {
141 Dumper->reportUniqueWarning(
142 Msg: "unable to read data at 0x" + Twine::utohexstr(Val: Offset) +
143 " of size 0x" + Twine::utohexstr(Val: Size) + " (" + SizePrintName +
144 "): it goes past the end of the file of size 0x" +
145 Twine::utohexstr(Val: ObjSize));
146 return {Start, Start};
147 }
148
149 if (EntSize == sizeof(Type) && (Size % EntSize == 0))
150 return {Start, Start + (Size / EntSize)};
151
152 std::string Msg;
153 if (!Context.empty())
154 Msg += Context + " has ";
155
156 Msg += ("invalid " + SizePrintName + " (0x" + Twine::utohexstr(Val: Size) + ")")
157 .str();
158 if (!EntSizePrintName.empty())
159 Msg +=
160 (" or " + EntSizePrintName + " (0x" + Twine::utohexstr(Val: EntSize) + ")")
161 .str();
162
163 Dumper->reportUniqueWarning(Msg);
164 return {Start, Start};
165 }
166};
167
168struct GroupMember {
169 StringRef Name;
170 uint64_t Index;
171};
172
173struct GroupSection {
174 StringRef Name;
175 std::string Signature;
176 uint64_t ShName;
177 uint64_t Index;
178 uint32_t Link;
179 uint32_t Info;
180 uint32_t Type;
181 std::vector<GroupMember> Members;
182};
183
184// Per-function call graph information.
185struct FunctionCallgraphInfo {
186 uint64_t FunctionAddress;
187 uint8_t FormatVersionNumber;
188 bool IsIndirectTarget;
189 uint64_t FunctionTypeID;
190 SmallSet<uint64_t, 4> DirectCallees;
191 SmallSet<uint64_t, 4> IndirectTypeIDs;
192};
193
194namespace {
195
196struct NoteType {
197 uint32_t ID;
198 StringRef Name;
199};
200
201} // namespace
202
203template <class ELFT> class Relocation {
204public:
205 Relocation(const typename ELFT::Rel &R, bool IsMips64EL)
206 : Type(R.getType(IsMips64EL)), Symbol(R.getSymbol(IsMips64EL)),
207 Offset(R.r_offset), Info(R.r_info) {}
208
209 Relocation(const typename ELFT::Rela &R, bool IsMips64EL)
210 : Relocation((const typename ELFT::Rel &)R, IsMips64EL) {
211 Addend = R.r_addend;
212 }
213
214 uint32_t Type;
215 uint32_t Symbol;
216 typename ELFT::uint Offset;
217 typename ELFT::uint Info;
218 std::optional<int64_t> Addend;
219};
220
221template <class ELFT> class MipsGOTParser;
222
223template <typename ELFT> class ELFDumper : public ObjDumper {
224 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
225
226public:
227 ELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer);
228
229 void printUnwindInfo() override;
230 void printNeededLibraries() override;
231 void printHashTable() override;
232 void printGnuHashTable() override;
233 void printLoadName() override;
234 void printVersionInfo() override;
235 void printArchSpecificInfo() override;
236 void printStackMap() const override;
237 void printMemtag() override;
238 void printSectionsAsSFrame(ArrayRef<std::string> Sections) override;
239
240 ArrayRef<uint8_t> getMemtagGlobalsSectionContents(uint64_t ExpectedAddr);
241
242 // Hash histogram shows statistics of how efficient the hash was for the
243 // dynamic symbol table. The table shows the number of hash buckets for
244 // different lengths of chains as an absolute number and percentage of the
245 // total buckets, and the cumulative coverage of symbols for each set of
246 // buckets.
247 void printHashHistograms() override;
248
249 const object::ELFObjectFile<ELFT> &getElfObject() const { return ObjF; };
250
251 std::string describe(const Elf_Shdr &Sec) const;
252
253 unsigned getHashTableEntSize() const {
254 // EM_S390 and ELF::EM_ALPHA platforms use 8-bytes entries in SHT_HASH
255 // sections. This violates the ELF specification.
256 if (Obj.getHeader().e_machine == ELF::EM_S390 ||
257 Obj.getHeader().e_machine == ELF::EM_ALPHA)
258 return 8;
259 return 4;
260 }
261
262 std::vector<const EnumString<unsigned, 2> *>
263 getOtherFlagsFromSymbol(const Elf_Ehdr &Header, const Elf_Sym &Symbol) const;
264
265 Elf_Dyn_Range dynamic_table() const {
266 // A valid .dynamic section contains an array of entries terminated
267 // with a DT_NULL entry. However, sometimes the section content may
268 // continue past the DT_NULL entry, so to dump the section correctly,
269 // we first find the end of the entries by iterating over them.
270 Elf_Dyn_Range Table = DynamicTable.template getAsArrayRef<Elf_Dyn>();
271
272 size_t Size = 0;
273 while (Size < Table.size())
274 if (Table[Size++].getTag() == DT_NULL)
275 break;
276
277 return Table.slice(0, Size);
278 }
279
280 Elf_Sym_Range dynamic_symbols() const {
281 if (!DynSymRegion)
282 return Elf_Sym_Range();
283 return DynSymRegion->template getAsArrayRef<Elf_Sym>();
284 }
285
286 const Elf_Shdr *findSectionByName(StringRef Name) const;
287
288 StringRef getDynamicStringTable() const { return DynamicStringTable; }
289
290protected:
291 virtual void printVersionSymbolSection(const Elf_Shdr *Sec) = 0;
292 virtual void printVersionDefinitionSection(const Elf_Shdr *Sec) = 0;
293 virtual void printVersionDependencySection(const Elf_Shdr *Sec) = 0;
294
295 void
296 printDependentLibsHelper(function_ref<void(const Elf_Shdr &)> OnSectionStart,
297 function_ref<void(StringRef, uint64_t)> OnLibEntry);
298
299 virtual void printRelRelaReloc(const Relocation<ELFT> &R,
300 const RelSymbol<ELFT> &RelSym) = 0;
301 virtual void printDynamicRelocHeader(unsigned Type, StringRef Name,
302 const DynRegionInfo &Reg) {}
303 void printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
304 const Elf_Shdr &Sec, const Elf_Shdr *SymTab);
305 void printDynamicReloc(const Relocation<ELFT> &R);
306 void printDynamicRelocationsHelper();
307 StringRef getRelocTypeName(uint32_t Type, SmallString<32> &RelocName);
308 void printRelocationsHelper(const Elf_Shdr &Sec);
309 void forEachRelocationDo(
310 const Elf_Shdr &Sec,
311 llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
312 const Elf_Shdr &, const Elf_Shdr *)>
313 RelRelaFn);
314
315 virtual void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
316 bool NonVisibilityBitsUsed,
317 bool ExtraSymInfo) const {};
318 virtual void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
319 DataRegion<Elf_Word> ShndxTable,
320 std::optional<StringRef> StrTable, bool IsDynamic,
321 bool NonVisibilityBitsUsed,
322 bool ExtraSymInfo) const = 0;
323
324 virtual void printMipsABIFlags() = 0;
325 virtual void printMipsGOT(const MipsGOTParser<ELFT> &Parser) = 0;
326 virtual void printMipsPLT(const MipsGOTParser<ELFT> &Parser) = 0;
327
328 virtual void printMemtag(
329 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
330 const ArrayRef<uint8_t> AndroidNoteDesc,
331 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) = 0;
332
333 virtual void printHashHistogram(const Elf_Hash &HashTable) const;
334 virtual void printGnuHashHistogram(const Elf_GnuHash &GnuHashTable) const;
335 virtual void printHashHistogramStats(size_t NBucket, size_t MaxChain,
336 size_t TotalSyms, ArrayRef<size_t> Count,
337 bool IsGnu) const = 0;
338
339 Expected<ArrayRef<Elf_Versym>>
340 getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
341 StringRef *StrTab, const Elf_Shdr **SymTabSec) const;
342 StringRef getPrintableSectionName(const Elf_Shdr &Sec) const;
343
344 std::vector<GroupSection> getGroups();
345
346 // Returns the function symbol index for the given address. Matches the
347 // symbol's section with FunctionSec when specified.
348 // Returns std::nullopt if no function symbol can be found for the address or
349 // in case it is not defined in the specified section.
350 SmallVector<uint32_t> getSymbolIndexesForFunctionAddress(
351 uint64_t SymValue, std::optional<const Elf_Shdr *> FunctionSec);
352 bool printFunctionStackSize(uint64_t SymValue,
353 std::optional<const Elf_Shdr *> FunctionSec,
354 const Elf_Shdr &StackSizeSec, DataExtractor Data,
355 uint64_t *Offset);
356 void printStackSize(const Relocation<ELFT> &R, const Elf_Shdr &RelocSec,
357 unsigned Ndx, const Elf_Shdr *SymTab,
358 const Elf_Shdr *FunctionSec, const Elf_Shdr &StackSizeSec,
359 const RelocationResolver &Resolver, DataExtractor Data);
360 virtual void printStackSizeEntry(uint64_t Size,
361 ArrayRef<std::string> FuncNames) = 0;
362
363 void printRelocatableStackSizes(std::function<void()> PrintHeader);
364 void printNonRelocatableStackSizes(std::function<void()> PrintHeader);
365
366 const object::ELFObjectFile<ELFT> &ObjF;
367 const ELFFile<ELFT> &Obj;
368 StringRef FileName;
369
370 Expected<DynRegionInfo> createDRI(uint64_t Offset, uint64_t Size,
371 uint64_t EntSize) {
372 if (Offset + Size < Offset || Offset + Size > Obj.getBufSize())
373 return createError("offset (0x" + Twine::utohexstr(Val: Offset) +
374 ") + size (0x" + Twine::utohexstr(Val: Size) +
375 ") is greater than the file size (0x" +
376 Twine::utohexstr(Val: Obj.getBufSize()) + ")");
377 return DynRegionInfo(ObjF, *this, Obj.base() + Offset, Size, EntSize);
378 }
379
380 void printAttributes(unsigned, std::unique_ptr<ELFAttributeParser>,
381 llvm::endianness);
382 void printMipsReginfo();
383 void printMipsOptions();
384
385 std::pair<const Elf_Phdr *, const Elf_Shdr *> findDynamic();
386 void loadDynamicTable();
387 void parseDynamicTable();
388
389 Expected<StringRef> getSymbolVersion(const Elf_Sym &Sym,
390 bool &IsDefault) const;
391 Expected<SmallVector<std::optional<VersionEntry>, 0> *> getVersionMap() const;
392
393 DynRegionInfo DynRelRegion;
394 DynRegionInfo DynRelaRegion;
395 DynRegionInfo DynCrelRegion;
396 DynRegionInfo DynRelrRegion;
397 DynRegionInfo DynPLTRelRegion;
398 std::optional<DynRegionInfo> DynSymRegion;
399 DynRegionInfo DynSymTabShndxRegion;
400 DynRegionInfo DynamicTable;
401 StringRef DynamicStringTable;
402 const Elf_Hash *HashTable = nullptr;
403 const Elf_GnuHash *GnuHashTable = nullptr;
404 const Elf_Shdr *DotSymtabSec = nullptr;
405 const Elf_Shdr *DotDynsymSec = nullptr;
406 const Elf_Shdr *DotAddrsigSec = nullptr;
407 DenseMap<const Elf_Shdr *, ArrayRef<Elf_Word>> ShndxTables;
408 std::optional<uint64_t> SONameOffset;
409 std::optional<DenseMap<uint64_t, std::vector<uint32_t>>> AddressToIndexMap;
410
411 const Elf_Shdr *SymbolVersionSection = nullptr; // .gnu.version
412 const Elf_Shdr *SymbolVersionNeedSection = nullptr; // .gnu.version_r
413 const Elf_Shdr *SymbolVersionDefSection = nullptr; // .gnu.version_d
414
415 // Used for tracking the current RISCV vendor name when printing relocations.
416 // When an R_RISCV_VENDOR relocation is encountered, we record the symbol name
417 // and offset so that the immediately following R_RISCV_CUSTOM* relocation at
418 // the same offset can be resolved to its vendor-specific name. Per RISC-V
419 // psABI, R_RISCV_VENDOR must be placed immediately before the vendor-specific
420 // relocation and both must be at the same offset.
421 std::string CurrentRISCVVendorSymbol;
422 uint64_t CurrentRISCVVendorOffset = 0;
423
424 std::string getFullSymbolName(const Elf_Sym &Symbol, unsigned SymIndex,
425 DataRegion<Elf_Word> ShndxTable,
426 std::optional<StringRef> StrTable,
427 bool IsDynamic) const;
428 Expected<unsigned>
429 getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
430 DataRegion<Elf_Word> ShndxTable) const;
431 Expected<StringRef> getSymbolSectionName(const Elf_Sym &Symbol,
432 unsigned SectionIndex) const;
433 std::string getStaticSymbolName(uint32_t Index) const;
434 StringRef getDynamicString(uint64_t Value) const;
435
436 std::pair<Elf_Sym_Range, std::optional<StringRef>> getSymtabAndStrtab() const;
437 void printSymbolsHelper(bool IsDynamic, bool ExtraSymInfo) const;
438 std::string getDynamicEntry(uint64_t Type, uint64_t Value) const;
439
440 Expected<RelSymbol<ELFT>> getRelocationTarget(const Relocation<ELFT> &R,
441 const Elf_Shdr *SymTab) const;
442
443 ArrayRef<Elf_Word> getShndxTable(const Elf_Shdr *Symtab) const;
444
445 void printSFrameHeader(const SFrameParser<ELFT::Endianness> &Parser);
446 void printSFrameFDEs(const SFrameParser<ELFT::Endianness> &Parser,
447 ArrayRef<Relocation<ELFT>> Relocations,
448 const Elf_Shdr *RelocSymTab);
449 uint64_t getAndPrintSFrameFDEStartAddress(
450 const SFrameParser<ELFT::Endianness> &Parser,
451 const typename SFrameParser<ELFT::Endianness>::FDERange::iterator FDE,
452 ArrayRef<Relocation<ELFT>> Relocations, const Elf_Shdr *RelocSymTab);
453 // Read the SHT_LLVM_CALL_GRAPH type sections and process their contents to
454 // populate call graph related data structures which will be used to dump call
455 // graph info. Returns an empty vector if there are no such sections or if
456 // parsing fails.
457 SmallVector<FunctionCallgraphInfo, 16>
458 processCallGraphSection(const Elf_Shdr *CGSection);
459
460 std::string getProgramHeadersNumString();
461
462private:
463 mutable SmallVector<std::optional<VersionEntry>, 0> VersionMap;
464};
465
466template <class ELFT>
467std::string ELFDumper<ELFT>::describe(const Elf_Shdr &Sec) const {
468 return ::describe(Obj, Sec);
469}
470
471namespace {
472
473template <class ELFT> struct SymtabLink {
474 typename ELFT::SymRange Symbols;
475 StringRef StringTable;
476 const typename ELFT::Shdr *SymTab;
477};
478
479// Returns the linked symbol table, symbols and associated string table for a
480// given section.
481template <class ELFT>
482Expected<SymtabLink<ELFT>> getLinkAsSymtab(const ELFFile<ELFT> &Obj,
483 const typename ELFT::Shdr &Sec,
484 unsigned ExpectedType) {
485 Expected<const typename ELFT::Shdr *> SymtabOrErr =
486 Obj.getSection(Sec.sh_link);
487 if (!SymtabOrErr)
488 return createError("invalid section linked to " + describe(Obj, Sec) +
489 ": " + toString(SymtabOrErr.takeError()));
490
491 if ((*SymtabOrErr)->sh_type != ExpectedType)
492 return createError(
493 "invalid section linked to " + describe(Obj, Sec) + ": expected " +
494 object::getELFSectionTypeName(Machine: Obj.getHeader().e_machine, Type: ExpectedType) +
495 ", but got " +
496 object::getELFSectionTypeName(Machine: Obj.getHeader().e_machine,
497 Type: (*SymtabOrErr)->sh_type));
498
499 Expected<StringRef> StrTabOrErr = Obj.getLinkAsStrtab(**SymtabOrErr);
500 if (!StrTabOrErr)
501 return createError(
502 "can't get a string table for the symbol table linked to " +
503 describe(Obj, Sec) + ": " + toString(E: StrTabOrErr.takeError()));
504
505 Expected<typename ELFT::SymRange> SymsOrErr = Obj.symbols(*SymtabOrErr);
506 if (!SymsOrErr)
507 return createError("unable to read symbols from the " + describe(Obj, Sec) +
508 ": " + toString(SymsOrErr.takeError()));
509
510 return SymtabLink<ELFT>{*SymsOrErr, *StrTabOrErr, *SymtabOrErr};
511}
512
513} // namespace
514
515template <class ELFT>
516Expected<ArrayRef<typename ELFT::Versym>>
517ELFDumper<ELFT>::getVersionTable(const Elf_Shdr &Sec, ArrayRef<Elf_Sym> *SymTab,
518 StringRef *StrTab,
519 const Elf_Shdr **SymTabSec) const {
520 assert((!SymTab && !StrTab && !SymTabSec) || (SymTab && StrTab && SymTabSec));
521 if (reinterpret_cast<uintptr_t>(Obj.base() + Sec.sh_offset) %
522 sizeof(uint16_t) !=
523 0)
524 return createError("the " + describe(Sec) + " is misaligned");
525
526 Expected<ArrayRef<Elf_Versym>> VersionsOrErr =
527 Obj.template getSectionContentsAsArray<Elf_Versym>(Sec);
528 if (!VersionsOrErr)
529 return createError("cannot read content of " + describe(Sec) + ": " +
530 toString(VersionsOrErr.takeError()));
531
532 Expected<SymtabLink<ELFT>> SymTabOrErr =
533 getLinkAsSymtab(Obj, Sec, SHT_DYNSYM);
534 if (!SymTabOrErr) {
535 reportUniqueWarning(SymTabOrErr.takeError());
536 return *VersionsOrErr;
537 }
538
539 if (SymTabOrErr->Symbols.size() != VersionsOrErr->size())
540 reportUniqueWarning(describe(Sec) + ": the number of entries (" +
541 Twine(VersionsOrErr->size()) +
542 ") does not match the number of symbols (" +
543 Twine(SymTabOrErr->Symbols.size()) +
544 ") in the symbol table with index " +
545 Twine(Sec.sh_link));
546
547 if (SymTab) {
548 *SymTab = SymTabOrErr->Symbols;
549 *StrTab = SymTabOrErr->StringTable;
550 *SymTabSec = SymTabOrErr->SymTab;
551 }
552 return *VersionsOrErr;
553}
554
555template <class ELFT>
556std::pair<typename ELFDumper<ELFT>::Elf_Sym_Range, std::optional<StringRef>>
557ELFDumper<ELFT>::getSymtabAndStrtab() const {
558 assert(DotSymtabSec);
559 Elf_Sym_Range Syms(nullptr, nullptr);
560 std::optional<StringRef> StrTable;
561 if (Expected<StringRef> StrTableOrErr =
562 Obj.getStringTableForSymtab(*DotSymtabSec))
563 StrTable = *StrTableOrErr;
564 else
565 reportUniqueWarning(
566 "unable to get the string table for the SHT_SYMTAB section: " +
567 toString(E: StrTableOrErr.takeError()));
568
569 if (Expected<Elf_Sym_Range> SymsOrErr = Obj.symbols(DotSymtabSec))
570 Syms = *SymsOrErr;
571 else
572 reportUniqueWarning("unable to read symbols from the SHT_SYMTAB section: " +
573 toString(SymsOrErr.takeError()));
574 return {Syms, StrTable};
575}
576
577template <class ELFT>
578void ELFDumper<ELFT>::printSymbolsHelper(bool IsDynamic,
579 bool ExtraSymInfo) const {
580 std::optional<StringRef> StrTable;
581 size_t Entries = 0;
582 Elf_Sym_Range Syms(nullptr, nullptr);
583 const Elf_Shdr *SymtabSec = IsDynamic ? DotDynsymSec : DotSymtabSec;
584
585 if (IsDynamic) {
586 StrTable = DynamicStringTable;
587 Syms = dynamic_symbols();
588 Entries = Syms.size();
589 } else if (DotSymtabSec) {
590 std::tie(Syms, StrTable) = getSymtabAndStrtab();
591 Entries = DotSymtabSec->getEntityCount();
592 }
593 if (Syms.empty())
594 return;
595
596 // The st_other field has 2 logical parts. The first two bits hold the symbol
597 // visibility (STV_*) and the remainder hold other platform-specific values.
598 bool NonVisibilityBitsUsed =
599 llvm::any_of(Syms, [](const Elf_Sym &S) { return S.st_other & ~0x3; });
600
601 DataRegion<Elf_Word> ShndxTable =
602 IsDynamic ? DataRegion<Elf_Word>(
603 (const Elf_Word *)this->DynSymTabShndxRegion.Addr,
604 this->getElfObject().getELFFile().end())
605 : DataRegion<Elf_Word>(this->getShndxTable(Symtab: SymtabSec));
606
607 printSymtabMessage(Symtab: SymtabSec, Offset: Entries, NonVisibilityBitsUsed, ExtraSymInfo);
608 for (const Elf_Sym &Sym : Syms)
609 printSymbol(Symbol: Sym, SymIndex: &Sym - Syms.begin(), ShndxTable, StrTable, IsDynamic,
610 NonVisibilityBitsUsed, ExtraSymInfo);
611}
612
613template <typename ELFT> class GNUELFDumper : public ELFDumper<ELFT> {
614 formatted_raw_ostream &OS;
615
616public:
617 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
618
619 GNUELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
620 : ELFDumper<ELFT>(ObjF, Writer),
621 OS(static_cast<formatted_raw_ostream &>(Writer.getOStream())) {
622 assert(&this->W.getOStream() == &llvm::fouts());
623 }
624
625 void printFileSummary(StringRef FileStr, ObjectFile &Obj,
626 ArrayRef<std::string> InputFilenames,
627 const Archive *A) override;
628 void printFileHeaders() override;
629 void printGroupSections() override;
630 void printRelocations() override;
631 void printSectionHeaders() override;
632 void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols,
633 bool ExtraSymInfo) override;
634 void printHashSymbols() override;
635 void printSectionDetails() override;
636 void printDependentLibs() override;
637 void printDynamicTable() override;
638 void printDynamicRelocations() override;
639 void printSymtabMessage(const Elf_Shdr *Symtab, size_t Offset,
640 bool NonVisibilityBitsUsed,
641 bool ExtraSymInfo) const override;
642 void printProgramHeaders(bool PrintProgramHeaders,
643 cl::boolOrDefault PrintSectionMapping) override;
644 void printVersionSymbolSection(const Elf_Shdr *Sec) override;
645 void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
646 void printVersionDependencySection(const Elf_Shdr *Sec) override;
647 void printCGProfile() override;
648 void printBBAddrMaps(bool PrettyPGOAnalysis) override;
649 void printAddrsig() override;
650 void printNotes() override;
651 void printELFLinkerOptions() override;
652 void printStackSizes() override;
653 void printMemtag(
654 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
655 const ArrayRef<uint8_t> AndroidNoteDesc,
656 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) override;
657 void printHashHistogramStats(size_t NBucket, size_t MaxChain,
658 size_t TotalSyms, ArrayRef<size_t> Count,
659 bool IsGnu) const override;
660
661private:
662 void printHashTableSymbols(const Elf_Hash &HashTable);
663 void printGnuHashTableSymbols(const Elf_GnuHash &GnuHashTable);
664
665 struct Field {
666 std::string Str;
667 unsigned Column;
668
669 Field(StringRef S, unsigned Col) : Str(std::string(S)), Column(Col) {}
670 Field(unsigned Col) : Column(Col) {}
671 };
672
673 template <typename T, typename TEnum, unsigned NumStrs>
674 std::string printFlags(T Value, EnumStrings<TEnum, NumStrs> EnumValues,
675 TEnum EnumMask1 = {}, TEnum EnumMask2 = {},
676 TEnum EnumMask3 = {}) const {
677 std::string Str;
678 for (const auto &Flag : EnumValues) {
679 if (Flag.value() == 0)
680 continue;
681
682 TEnum EnumMask{};
683 if (Flag.value() & EnumMask1)
684 EnumMask = EnumMask1;
685 else if (Flag.value() & EnumMask2)
686 EnumMask = EnumMask2;
687 else if (Flag.value() & EnumMask3)
688 EnumMask = EnumMask3;
689 bool IsEnum = (Flag.value() & EnumMask) != 0;
690 if ((!IsEnum && (Value & Flag.value()) == Flag.value()) ||
691 (IsEnum && (Value & EnumMask) == Flag.value())) {
692 if (!Str.empty())
693 Str += ", ";
694 Str += Flag.name(NumStrs - 1); // Use GNU string if specified.
695 }
696 }
697 return Str;
698 }
699
700 formatted_raw_ostream &printField(struct Field F) const {
701 if (F.Column != 0)
702 OS.PadToColumn(NewCol: F.Column);
703 OS << F.Str;
704 OS.flush();
705 return OS;
706 }
707 void printHashedSymbol(const Elf_Sym *Sym, unsigned SymIndex,
708 DataRegion<Elf_Word> ShndxTable, StringRef StrTable,
709 uint32_t Bucket);
710 void printRelr(const Elf_Shdr &Sec);
711 void printRelRelaReloc(const Relocation<ELFT> &R,
712 const RelSymbol<ELFT> &RelSym) override;
713 void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
714 DataRegion<Elf_Word> ShndxTable,
715 std::optional<StringRef> StrTable, bool IsDynamic,
716 bool NonVisibilityBitsUsed,
717 bool ExtraSymInfo) const override;
718 void printDynamicRelocHeader(unsigned Type, StringRef Name,
719 const DynRegionInfo &Reg) override;
720
721 std::string getSymbolSectionNdx(const Elf_Sym &Symbol, unsigned SymIndex,
722 DataRegion<Elf_Word> ShndxTable,
723 bool ExtraSymInfo = false) const;
724 void printProgramHeaders() override;
725 void printSectionMapping() override;
726 void printGNUVersionSectionProlog(const typename ELFT::Shdr &Sec,
727 const Twine &Label, unsigned EntriesNum);
728
729 void printStackSizeEntry(uint64_t Size,
730 ArrayRef<std::string> FuncNames) override;
731
732 void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
733 void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
734 void printMipsABIFlags() override;
735};
736
737template <typename ELFT> class LLVMELFDumper : public ELFDumper<ELFT> {
738public:
739 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
740
741 LLVMELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
742 : ELFDumper<ELFT>(ObjF, Writer), W(Writer) {}
743
744 void printFileHeaders() override;
745 void printGroupSections() override;
746 void printRelocations() override;
747 void printSectionHeaders() override;
748 void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols,
749 bool ExtraSymInfo) override;
750 void printDependentLibs() override;
751 void printDynamicTable() override;
752 void printDynamicRelocations() override;
753 void printProgramHeaders(bool PrintProgramHeaders,
754 cl::boolOrDefault PrintSectionMapping) override;
755 void printVersionSymbolSection(const Elf_Shdr *Sec) override;
756 void printVersionDefinitionSection(const Elf_Shdr *Sec) override;
757 void printVersionDependencySection(const Elf_Shdr *Sec) override;
758 void printCGProfile() override;
759 void printCallGraphInfo() override;
760 void printBBAddrMaps(bool PrettyPGOAnalysis) override;
761 void printAddrsig() override;
762 void printNotes() override;
763 void printELFLinkerOptions() override;
764 void printStackSizes() override;
765 void printMemtag(
766 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
767 const ArrayRef<uint8_t> AndroidNoteDesc,
768 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) override;
769 void printSymbolSection(const Elf_Sym &Symbol, unsigned SymIndex,
770 DataRegion<Elf_Word> ShndxTable) const;
771 void printHashHistogramStats(size_t NBucket, size_t MaxChain,
772 size_t TotalSyms, ArrayRef<size_t> Count,
773 bool IsGnu) const override;
774
775private:
776 void printRelRelaReloc(const Relocation<ELFT> &R,
777 const RelSymbol<ELFT> &RelSym) override;
778
779 void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
780 DataRegion<Elf_Word> ShndxTable,
781 std::optional<StringRef> StrTable, bool IsDynamic,
782 bool /*NonVisibilityBitsUsed*/,
783 bool /*ExtraSymInfo*/) const override;
784 void printProgramHeaders() override;
785 void printSectionMapping() override {}
786 void printStackSizeEntry(uint64_t Size,
787 ArrayRef<std::string> FuncNames) override;
788
789 void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override;
790 void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override;
791 void printMipsABIFlags() override;
792 virtual void printZeroSymbolOtherField(const Elf_Sym &Symbol) const;
793
794protected:
795 virtual std::string getGroupSectionHeaderName() const;
796 void printSymbolOtherField(const Elf_Sym &Symbol) const;
797 virtual void printExpandedRelRelaReloc(const Relocation<ELFT> &R,
798 StringRef SymbolName,
799 StringRef RelocName);
800 virtual void printDefaultRelRelaReloc(const Relocation<ELFT> &R,
801 StringRef SymbolName,
802 StringRef RelocName);
803 virtual void printRelocationSectionInfo(const Elf_Shdr &Sec, StringRef Name,
804 const unsigned SecNdx);
805 virtual void printSectionGroupMembers(StringRef Name, uint64_t Idx) const;
806 virtual void printEmptyGroupMessage() const;
807
808 ScopedPrinter &W;
809};
810
811// JSONELFDumper shares most of the same implementation as LLVMELFDumper except
812// it uses a JSONScopedPrinter.
813template <typename ELFT> class JSONELFDumper : public LLVMELFDumper<ELFT> {
814public:
815 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
816
817 JSONELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer)
818 : LLVMELFDumper<ELFT>(ObjF, Writer) {}
819
820 std::string getGroupSectionHeaderName() const override;
821
822 void printFileSummary(StringRef FileStr, ObjectFile &Obj,
823 ArrayRef<std::string> InputFilenames,
824 const Archive *A) override;
825 void printZeroSymbolOtherField(const Elf_Sym &Symbol) const override;
826
827 void printDefaultRelRelaReloc(const Relocation<ELFT> &R,
828 StringRef SymbolName,
829 StringRef RelocName) override;
830
831 void printRelocationSectionInfo(const Elf_Shdr &Sec, StringRef Name,
832 const unsigned SecNdx) override;
833
834 void printSectionGroupMembers(StringRef Name, uint64_t Idx) const override;
835
836 void printEmptyGroupMessage() const override;
837
838 void printDynamicTable() override;
839
840private:
841 void printAuxillaryDynamicTableEntryInfo(const Elf_Dyn &Entry);
842
843 std::unique_ptr<DictScope> FileScope;
844};
845
846} // end anonymous namespace
847
848namespace llvm {
849
850template <class ELFT>
851static std::unique_ptr<ObjDumper>
852createELFDumper(const ELFObjectFile<ELFT> &Obj, ScopedPrinter &Writer) {
853 if (opts::Output == opts::GNU)
854 return std::make_unique<GNUELFDumper<ELFT>>(Obj, Writer);
855 else if (opts::Output == opts::JSON)
856 return std::make_unique<JSONELFDumper<ELFT>>(Obj, Writer);
857 return std::make_unique<LLVMELFDumper<ELFT>>(Obj, Writer);
858}
859
860std::unique_ptr<ObjDumper> createELFDumper(const object::ELFObjectFileBase &Obj,
861 ScopedPrinter &Writer) {
862 // Little-endian 32-bit
863 if (const ELF32LEObjectFile *ELFObj = dyn_cast<ELF32LEObjectFile>(Val: &Obj))
864 return createELFDumper(Obj: *ELFObj, Writer);
865
866 // Big-endian 32-bit
867 if (const ELF32BEObjectFile *ELFObj = dyn_cast<ELF32BEObjectFile>(Val: &Obj))
868 return createELFDumper(Obj: *ELFObj, Writer);
869
870 // Little-endian 64-bit
871 if (const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(Val: &Obj))
872 return createELFDumper(Obj: *ELFObj, Writer);
873
874 // Big-endian 64-bit
875 return createELFDumper(Obj: *cast<ELF64BEObjectFile>(Val: &Obj), Writer);
876}
877
878} // end namespace llvm
879
880template <class ELFT>
881Expected<SmallVector<std::optional<VersionEntry>, 0> *>
882ELFDumper<ELFT>::getVersionMap() const {
883 // If the VersionMap has already been loaded or if there is no dynamic symtab
884 // or version table, there is nothing to do.
885 if (!VersionMap.empty() || !DynSymRegion || !SymbolVersionSection)
886 return &VersionMap;
887
888 Expected<SmallVector<std::optional<VersionEntry>, 0>> MapOrErr =
889 Obj.loadVersionMap(SymbolVersionNeedSection, SymbolVersionDefSection);
890 if (MapOrErr)
891 VersionMap = *MapOrErr;
892 else
893 return MapOrErr.takeError();
894
895 return &VersionMap;
896}
897
898template <typename ELFT>
899Expected<StringRef> ELFDumper<ELFT>::getSymbolVersion(const Elf_Sym &Sym,
900 bool &IsDefault) const {
901 // This is a dynamic symbol. Look in the GNU symbol version table.
902 if (!SymbolVersionSection) {
903 // No version table.
904 IsDefault = false;
905 return "";
906 }
907
908 assert(DynSymRegion && "DynSymRegion has not been initialised");
909 // Determine the position in the symbol table of this entry.
910 size_t EntryIndex = (reinterpret_cast<uintptr_t>(&Sym) -
911 reinterpret_cast<uintptr_t>(DynSymRegion->Addr)) /
912 sizeof(Elf_Sym);
913
914 // Get the corresponding version index entry.
915 Expected<const Elf_Versym *> EntryOrErr =
916 Obj.template getEntry<Elf_Versym>(*SymbolVersionSection, EntryIndex);
917 if (!EntryOrErr)
918 return EntryOrErr.takeError();
919
920 unsigned Version = (*EntryOrErr)->vs_index;
921 if (Version == VER_NDX_LOCAL || Version == VER_NDX_GLOBAL) {
922 IsDefault = false;
923 return "";
924 }
925
926 Expected<SmallVector<std::optional<VersionEntry>, 0> *> MapOrErr =
927 getVersionMap();
928 if (!MapOrErr)
929 return MapOrErr.takeError();
930
931 return Obj.getSymbolVersionByIndex(Version, IsDefault, **MapOrErr,
932 Sym.st_shndx == ELF::SHN_UNDEF);
933}
934
935template <typename ELFT>
936Expected<RelSymbol<ELFT>>
937ELFDumper<ELFT>::getRelocationTarget(const Relocation<ELFT> &R,
938 const Elf_Shdr *SymTab) const {
939 if (R.Symbol == 0)
940 return RelSymbol<ELFT>(nullptr, "");
941
942 Expected<const Elf_Sym *> SymOrErr =
943 Obj.template getEntry<Elf_Sym>(*SymTab, R.Symbol);
944 if (!SymOrErr)
945 return createError("unable to read an entry with index " + Twine(R.Symbol) +
946 " from " + describe(Sec: *SymTab) + ": " +
947 toString(SymOrErr.takeError()));
948 const Elf_Sym *Sym = *SymOrErr;
949 if (!Sym)
950 return RelSymbol<ELFT>(nullptr, "");
951
952 Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(*SymTab);
953 if (!StrTableOrErr)
954 return StrTableOrErr.takeError();
955
956 const Elf_Sym *FirstSym =
957 cantFail(Obj.template getEntry<Elf_Sym>(*SymTab, 0));
958 std::string SymbolName =
959 getFullSymbolName(Symbol: *Sym, SymIndex: Sym - FirstSym, ShndxTable: getShndxTable(Symtab: SymTab),
960 StrTable: *StrTableOrErr, IsDynamic: SymTab->sh_type == SHT_DYNSYM);
961 return RelSymbol<ELFT>(Sym, SymbolName);
962}
963
964template <typename ELFT>
965ArrayRef<typename ELFT::Word>
966ELFDumper<ELFT>::getShndxTable(const Elf_Shdr *Symtab) const {
967 if (Symtab) {
968 auto It = ShndxTables.find(Symtab);
969 if (It != ShndxTables.end())
970 return It->second;
971 }
972 return {};
973}
974
975static std::string maybeDemangle(StringRef Name) {
976 return opts::Demangle ? demangle(MangledName: Name) : Name.str();
977}
978
979template <typename ELFT>
980std::string ELFDumper<ELFT>::getStaticSymbolName(uint32_t Index) const {
981 auto Warn = [&](Error E) -> std::string {
982 reportUniqueWarning("unable to read the name of symbol with index " +
983 Twine(Index) + ": " + toString(E: std::move(E)));
984 return "<?>";
985 };
986
987 Expected<const typename ELFT::Sym *> SymOrErr =
988 Obj.getSymbol(DotSymtabSec, Index);
989 if (!SymOrErr)
990 return Warn(SymOrErr.takeError());
991
992 Expected<StringRef> StrTabOrErr = Obj.getStringTableForSymtab(*DotSymtabSec);
993 if (!StrTabOrErr)
994 return Warn(StrTabOrErr.takeError());
995
996 Expected<StringRef> NameOrErr = (*SymOrErr)->getName(*StrTabOrErr);
997 if (!NameOrErr)
998 return Warn(NameOrErr.takeError());
999 return maybeDemangle(Name: *NameOrErr);
1000}
1001
1002template <typename ELFT>
1003std::string ELFDumper<ELFT>::getFullSymbolName(
1004 const Elf_Sym &Symbol, unsigned SymIndex, DataRegion<Elf_Word> ShndxTable,
1005 std::optional<StringRef> StrTable, bool IsDynamic) const {
1006 if (!StrTable)
1007 return "<?>";
1008
1009 std::string SymbolName;
1010 if (Expected<StringRef> NameOrErr = Symbol.getName(*StrTable)) {
1011 SymbolName = maybeDemangle(Name: *NameOrErr);
1012 } else {
1013 reportUniqueWarning(NameOrErr.takeError());
1014 return "<?>";
1015 }
1016
1017 if (SymbolName.empty() && Symbol.getType() == ELF::STT_SECTION) {
1018 Expected<unsigned> SectionIndex =
1019 getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
1020 if (!SectionIndex) {
1021 reportUniqueWarning(SectionIndex.takeError());
1022 return "<?>";
1023 }
1024 Expected<StringRef> NameOrErr = getSymbolSectionName(Symbol, SectionIndex: *SectionIndex);
1025 if (!NameOrErr) {
1026 reportUniqueWarning(NameOrErr.takeError());
1027 return ("<section " + Twine(*SectionIndex) + ">").str();
1028 }
1029 return std::string(*NameOrErr);
1030 }
1031
1032 if (!IsDynamic)
1033 return SymbolName;
1034
1035 bool IsDefault;
1036 Expected<StringRef> VersionOrErr = getSymbolVersion(Sym: Symbol, IsDefault);
1037 if (!VersionOrErr) {
1038 reportUniqueWarning(VersionOrErr.takeError());
1039 return SymbolName + "@<corrupt>";
1040 }
1041
1042 if (!VersionOrErr->empty()) {
1043 SymbolName += (IsDefault ? "@@" : "@");
1044 SymbolName += *VersionOrErr;
1045 }
1046 return SymbolName;
1047}
1048
1049template <typename ELFT>
1050Expected<unsigned>
1051ELFDumper<ELFT>::getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex,
1052 DataRegion<Elf_Word> ShndxTable) const {
1053 unsigned Ndx = Symbol.st_shndx;
1054 if (Ndx == SHN_XINDEX)
1055 return object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex,
1056 ShndxTable);
1057 if (Ndx != SHN_UNDEF && Ndx < SHN_LORESERVE)
1058 return Ndx;
1059
1060 auto CreateErr = [&](const Twine &Name,
1061 std::optional<unsigned> Offset = std::nullopt) {
1062 std::string Desc;
1063 if (Offset)
1064 Desc = (Name + "+0x" + Twine::utohexstr(Val: *Offset)).str();
1065 else
1066 Desc = Name.str();
1067 return createError(
1068 Err: "unable to get section index for symbol with st_shndx = 0x" +
1069 Twine::utohexstr(Val: Ndx) + " (" + Desc + ")");
1070 };
1071
1072 if (Ndx >= ELF::SHN_LOPROC && Ndx <= ELF::SHN_HIPROC)
1073 return CreateErr("SHN_LOPROC", Ndx - ELF::SHN_LOPROC);
1074 if (Ndx >= ELF::SHN_LOOS && Ndx <= ELF::SHN_HIOS)
1075 return CreateErr("SHN_LOOS", Ndx - ELF::SHN_LOOS);
1076 if (Ndx == ELF::SHN_UNDEF)
1077 return CreateErr("SHN_UNDEF");
1078 if (Ndx == ELF::SHN_ABS)
1079 return CreateErr("SHN_ABS");
1080 if (Ndx == ELF::SHN_COMMON)
1081 return CreateErr("SHN_COMMON");
1082 return CreateErr("SHN_LORESERVE", Ndx - SHN_LORESERVE);
1083}
1084
1085template <typename ELFT>
1086Expected<StringRef>
1087ELFDumper<ELFT>::getSymbolSectionName(const Elf_Sym &Symbol,
1088 unsigned SectionIndex) const {
1089 Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(SectionIndex);
1090 if (!SecOrErr)
1091 return SecOrErr.takeError();
1092 return Obj.getSectionName(**SecOrErr);
1093}
1094
1095template <class ELFO>
1096static const typename ELFO::Elf_Shdr *
1097findNotEmptySectionByAddress(const ELFO &Obj, StringRef FileName,
1098 uint64_t Addr) {
1099 for (const typename ELFO::Elf_Shdr &Shdr : cantFail(Obj.sections()))
1100 if (Shdr.sh_addr == Addr && Shdr.sh_size > 0)
1101 return &Shdr;
1102 return nullptr;
1103}
1104
1105constexpr EnumStringDef<unsigned, 2> ElfClassDefs[] = {
1106 {.Names: {"None", "none"}, .Value: ELF::ELFCLASSNONE},
1107 {.Names: {"32-bit", "ELF32"}, .Value: ELF::ELFCLASS32},
1108 {.Names: {"64-bit", "ELF64"}, .Value: ELF::ELFCLASS64},
1109};
1110constexpr auto ElfClass = BUILD_ENUM_STRINGS(ElfClassDefs);
1111
1112constexpr EnumStringDef<unsigned, 2> ElfDataEncodingDefs[] = {
1113 {.Names: {"None", "none"}, .Value: ELF::ELFDATANONE},
1114 {.Names: {"LittleEndian", "2's complement, little endian"}, .Value: ELF::ELFDATA2LSB},
1115 {.Names: {"BigEndian", "2's complement, big endian"}, .Value: ELF::ELFDATA2MSB},
1116};
1117constexpr auto ElfDataEncoding = BUILD_ENUM_STRINGS(ElfDataEncodingDefs);
1118
1119constexpr EnumStringDef<unsigned, 2> ElfObjectFileTypeDefs[] = {
1120 {.Names: {"None", "NONE (none)"}, .Value: ELF::ET_NONE},
1121 {.Names: {"Relocatable", "REL (Relocatable file)"}, .Value: ELF::ET_REL},
1122 {.Names: {"Executable", "EXEC (Executable file)"}, .Value: ELF::ET_EXEC},
1123 {.Names: {"SharedObject", "DYN (Shared object file)"}, .Value: ELF::ET_DYN},
1124 {.Names: {"Core", "CORE (Core file)"}, .Value: ELF::ET_CORE},
1125};
1126constexpr auto ElfObjectFileType = BUILD_ENUM_STRINGS(ElfObjectFileTypeDefs);
1127
1128constexpr EnumStringDef<unsigned, 2> ElfOSABIDefs[] = {
1129 {.Names: {"SystemV", "UNIX - System V"}, .Value: ELF::ELFOSABI_NONE},
1130 {.Names: {"HPUX", "UNIX - HP-UX"}, .Value: ELF::ELFOSABI_HPUX},
1131 {.Names: {"NetBSD", "UNIX - NetBSD"}, .Value: ELF::ELFOSABI_NETBSD},
1132 {.Names: {"GNU/Linux", "UNIX - GNU"}, .Value: ELF::ELFOSABI_LINUX},
1133 {.Names: {"GNU/Hurd", "GNU/Hurd"}, .Value: ELF::ELFOSABI_HURD},
1134 {.Names: {"Solaris", "UNIX - Solaris"}, .Value: ELF::ELFOSABI_SOLARIS},
1135 {.Names: {"AIX", "UNIX - AIX"}, .Value: ELF::ELFOSABI_AIX},
1136 {.Names: {"IRIX", "UNIX - IRIX"}, .Value: ELF::ELFOSABI_IRIX},
1137 {.Names: {"FreeBSD", "UNIX - FreeBSD"}, .Value: ELF::ELFOSABI_FREEBSD},
1138 {.Names: {"TRU64", "UNIX - TRU64"}, .Value: ELF::ELFOSABI_TRU64},
1139 {.Names: {"Modesto", "Novell - Modesto"}, .Value: ELF::ELFOSABI_MODESTO},
1140 {.Names: {"OpenBSD", "UNIX - OpenBSD"}, .Value: ELF::ELFOSABI_OPENBSD},
1141 {.Names: {"OpenVMS", "VMS - OpenVMS"}, .Value: ELF::ELFOSABI_OPENVMS},
1142 {.Names: {"NSK", "HP - Non-Stop Kernel"}, .Value: ELF::ELFOSABI_NSK},
1143 {.Names: {"AROS", "AROS"}, .Value: ELF::ELFOSABI_AROS},
1144 {.Names: {"FenixOS", "FenixOS"}, .Value: ELF::ELFOSABI_FENIXOS},
1145 {.Names: {"CloudABI", "CloudABI"}, .Value: ELF::ELFOSABI_CLOUDABI},
1146 {.Names: {"CUDA", "NVIDIA - CUDA"}, .Value: ELF::ELFOSABI_CUDA},
1147 {.Names: {"CUDA", "NVIDIA - CUDA"}, .Value: ELF::ELFOSABI_CUDA_V2},
1148 {.Names: {"Standalone", "Standalone App"}, .Value: ELF::ELFOSABI_STANDALONE}};
1149constexpr auto ElfOSABI = BUILD_ENUM_STRINGS(ElfOSABIDefs);
1150
1151constexpr EnumStringDef<unsigned, 2> AMDGPUElfOSABIDefs[] = {
1152 {.Names: {"AMDGPU_HSA", "AMDGPU - HSA"}, .Value: ELF::ELFOSABI_AMDGPU_HSA},
1153 {.Names: {"AMDGPU_PAL", "AMDGPU - PAL"}, .Value: ELF::ELFOSABI_AMDGPU_PAL},
1154 {.Names: {"AMDGPU_MESA3D", "AMDGPU - MESA3D"}, .Value: ELF::ELFOSABI_AMDGPU_MESA3D}};
1155constexpr auto AMDGPUElfOSABI = BUILD_ENUM_STRINGS(AMDGPUElfOSABIDefs);
1156
1157constexpr EnumStringDef<unsigned, 2> ARMElfOSABIDefs[] = {
1158 {.Names: {"ARM", "ARM"}, .Value: ELF::ELFOSABI_ARM},
1159 {.Names: {"ARM FDPIC", "ARM FDPIC"}, .Value: ELF::ELFOSABI_ARM_FDPIC},
1160};
1161constexpr auto ARMElfOSABI = BUILD_ENUM_STRINGS(ARMElfOSABIDefs);
1162
1163constexpr EnumStringDef<unsigned, 2> C6000ElfOSABIDefs[] = {
1164 {.Names: {"C6000_ELFABI", "Bare-metal C6000"}, .Value: ELF::ELFOSABI_C6000_ELFABI},
1165 {.Names: {"C6000_LINUX", "Linux C6000"}, .Value: ELF::ELFOSABI_C6000_LINUX}};
1166constexpr auto C6000ElfOSABI = BUILD_ENUM_STRINGS(C6000ElfOSABIDefs);
1167
1168// clang-format off
1169constexpr EnumStringDef<unsigned, 2> ElfMachineTypeDefs[] = {
1170 ENUM_ENT(EM_NONE, "None"),
1171 ENUM_ENT(EM_M32, "WE32100"),
1172 ENUM_ENT(EM_SPARC, "Sparc"),
1173 ENUM_ENT(EM_386, "Intel 80386"),
1174 ENUM_ENT(EM_68K, "MC68000"),
1175 ENUM_ENT(EM_88K, "MC88000"),
1176 ENUM_ENT(EM_IAMCU, "EM_IAMCU"),
1177 ENUM_ENT(EM_860, "Intel 80860"),
1178 ENUM_ENT(EM_MIPS, "MIPS R3000"),
1179 ENUM_ENT(EM_S370, "IBM System/370"),
1180 ENUM_ENT(EM_MIPS_RS3_LE, "MIPS R3000 little-endian"),
1181 ENUM_ENT(EM_PARISC, "HPPA"),
1182 ENUM_ENT(EM_VPP500, "Fujitsu VPP500"),
1183 ENUM_ENT(EM_SPARC32PLUS, "Sparc v8+"),
1184 ENUM_ENT(EM_960, "Intel 80960"),
1185 ENUM_ENT(EM_PPC, "PowerPC"),
1186 ENUM_ENT(EM_PPC64, "PowerPC64"),
1187 ENUM_ENT(EM_S390, "IBM S/390"),
1188 ENUM_ENT(EM_SPU, "SPU"),
1189 ENUM_ENT(EM_V800, "NEC V800 series"),
1190 ENUM_ENT(EM_FR20, "Fujistsu FR20"),
1191 ENUM_ENT(EM_RH32, "TRW RH-32"),
1192 ENUM_ENT(EM_RCE, "Motorola RCE"),
1193 ENUM_ENT(EM_ARM, "ARM"),
1194 ENUM_ENT(EM_ALPHA, "EM_ALPHA"),
1195 ENUM_ENT(EM_SH, "Hitachi SH"),
1196 ENUM_ENT(EM_SPARCV9, "Sparc v9"),
1197 ENUM_ENT(EM_TRICORE, "Siemens Tricore"),
1198 ENUM_ENT(EM_ARC, "ARC"),
1199 ENUM_ENT(EM_H8_300, "Hitachi H8/300"),
1200 ENUM_ENT(EM_H8_300H, "Hitachi H8/300H"),
1201 ENUM_ENT(EM_H8S, "Hitachi H8S"),
1202 ENUM_ENT(EM_H8_500, "Hitachi H8/500"),
1203 ENUM_ENT(EM_IA_64, "Intel IA-64"),
1204 ENUM_ENT(EM_MIPS_X, "Stanford MIPS-X"),
1205 ENUM_ENT(EM_COLDFIRE, "Motorola Coldfire"),
1206 ENUM_ENT(EM_68HC12, "Motorola MC68HC12 Microcontroller"),
1207 ENUM_ENT(EM_MMA, "Fujitsu Multimedia Accelerator"),
1208 ENUM_ENT(EM_PCP, "Siemens PCP"),
1209 ENUM_ENT(EM_NCPU, "Sony nCPU embedded RISC processor"),
1210 ENUM_ENT(EM_NDR1, "Denso NDR1 microprocesspr"),
1211 ENUM_ENT(EM_STARCORE, "Motorola Star*Core processor"),
1212 ENUM_ENT(EM_ME16, "Toyota ME16 processor"),
1213 ENUM_ENT(EM_ST100, "STMicroelectronics ST100 processor"),
1214 ENUM_ENT(EM_TINYJ, "Advanced Logic Corp. TinyJ embedded processor"),
1215 ENUM_ENT(EM_X86_64, "Advanced Micro Devices X86-64"),
1216 ENUM_ENT(EM_PDSP, "Sony DSP processor"),
1217 ENUM_ENT(EM_PDP10, "Digital Equipment Corp. PDP-10"),
1218 ENUM_ENT(EM_PDP11, "Digital Equipment Corp. PDP-11"),
1219 ENUM_ENT(EM_FX66, "Siemens FX66 microcontroller"),
1220 ENUM_ENT(EM_ST9PLUS, "STMicroelectronics ST9+ 8/16 bit microcontroller"),
1221 ENUM_ENT(EM_ST7, "STMicroelectronics ST7 8-bit microcontroller"),
1222 ENUM_ENT(EM_68HC16, "Motorola MC68HC16 Microcontroller"),
1223 ENUM_ENT(EM_68HC11, "Motorola MC68HC11 Microcontroller"),
1224 ENUM_ENT(EM_68HC08, "Motorola MC68HC08 Microcontroller"),
1225 ENUM_ENT(EM_68HC05, "Motorola MC68HC05 Microcontroller"),
1226 ENUM_ENT(EM_SVX, "Silicon Graphics SVx"),
1227 ENUM_ENT(EM_ST19, "STMicroelectronics ST19 8-bit microcontroller"),
1228 ENUM_ENT(EM_VAX, "Digital VAX"),
1229 ENUM_ENT(EM_CRIS, "Axis Communications 32-bit embedded processor"),
1230 ENUM_ENT(EM_JAVELIN, "Infineon Technologies 32-bit embedded cpu"),
1231 ENUM_ENT(EM_FIREPATH, "Element 14 64-bit DSP processor"),
1232 ENUM_ENT(EM_ZSP, "LSI Logic's 16-bit DSP processor"),
1233 ENUM_ENT(EM_MMIX, "Donald Knuth's educational 64-bit processor"),
1234 ENUM_ENT(EM_HUANY, "Harvard Universitys's machine-independent object format"),
1235 ENUM_ENT(EM_PRISM, "Vitesse Prism"),
1236 ENUM_ENT(EM_AVR, "Atmel AVR 8-bit microcontroller"),
1237 ENUM_ENT(EM_FR30, "Fujitsu FR30"),
1238 ENUM_ENT(EM_D10V, "Mitsubishi D10V"),
1239 ENUM_ENT(EM_D30V, "Mitsubishi D30V"),
1240 ENUM_ENT(EM_V850, "NEC v850"),
1241 ENUM_ENT(EM_M32R, "Renesas M32R (formerly Mitsubishi M32r)"),
1242 ENUM_ENT(EM_MN10300, "Matsushita MN10300"),
1243 ENUM_ENT(EM_MN10200, "Matsushita MN10200"),
1244 ENUM_ENT(EM_PJ, "picoJava"),
1245 ENUM_ENT(EM_OPENRISC, "OpenRISC 32-bit embedded processor"),
1246 ENUM_ENT(EM_ARC_COMPACT, "EM_ARC_COMPACT"),
1247 ENUM_ENT(EM_XTENSA, "Tensilica Xtensa Processor"),
1248 ENUM_ENT(EM_VIDEOCORE, "Alphamosaic VideoCore processor"),
1249 ENUM_ENT(EM_TMM_GPP, "Thompson Multimedia General Purpose Processor"),
1250 ENUM_ENT(EM_NS32K, "National Semiconductor 32000 series"),
1251 ENUM_ENT(EM_TPC, "Tenor Network TPC processor"),
1252 ENUM_ENT(EM_SNP1K, "EM_SNP1K"),
1253 ENUM_ENT(EM_ST200, "STMicroelectronics ST200 microcontroller"),
1254 ENUM_ENT(EM_IP2K, "Ubicom IP2xxx 8-bit microcontrollers"),
1255 ENUM_ENT(EM_MAX, "MAX Processor"),
1256 ENUM_ENT(EM_CR, "National Semiconductor CompactRISC"),
1257 ENUM_ENT(EM_F2MC16, "Fujitsu F2MC16"),
1258 ENUM_ENT(EM_MSP430, "Texas Instruments msp430 microcontroller"),
1259 ENUM_ENT(EM_BLACKFIN, "Analog Devices Blackfin"),
1260 ENUM_ENT(EM_SE_C33, "S1C33 Family of Seiko Epson processors"),
1261 ENUM_ENT(EM_SEP, "Sharp embedded microprocessor"),
1262 ENUM_ENT(EM_ARCA, "Arca RISC microprocessor"),
1263 ENUM_ENT(EM_UNICORE, "Unicore"),
1264 ENUM_ENT(EM_EXCESS, "eXcess 16/32/64-bit configurable embedded CPU"),
1265 ENUM_ENT(EM_DXP, "Icera Semiconductor Inc. Deep Execution Processor"),
1266 ENUM_ENT(EM_ALTERA_NIOS2, "Altera Nios"),
1267 ENUM_ENT(EM_CRX, "National Semiconductor CRX microprocessor"),
1268 ENUM_ENT(EM_XGATE, "Motorola XGATE embedded processor"),
1269 ENUM_ENT(EM_C166, "Infineon Technologies xc16x"),
1270 ENUM_ENT(EM_M16C, "Renesas M16C"),
1271 ENUM_ENT(EM_DSPIC30F, "Microchip Technology dsPIC30F Digital Signal Controller"),
1272 ENUM_ENT(EM_CE, "Freescale Communication Engine RISC core"),
1273 ENUM_ENT(EM_M32C, "Renesas M32C"),
1274 ENUM_ENT(EM_TSK3000, "Altium TSK3000 core"),
1275 ENUM_ENT(EM_RS08, "Freescale RS08 embedded processor"),
1276 ENUM_ENT(EM_SHARC, "EM_SHARC"),
1277 ENUM_ENT(EM_ECOG2, "Cyan Technology eCOG2 microprocessor"),
1278 ENUM_ENT(EM_SCORE7, "SUNPLUS S+Core"),
1279 ENUM_ENT(EM_DSP24, "New Japan Radio (NJR) 24-bit DSP Processor"),
1280 ENUM_ENT(EM_VIDEOCORE3, "Broadcom VideoCore III processor"),
1281 ENUM_ENT(EM_LATTICEMICO32, "Lattice Mico32"),
1282 ENUM_ENT(EM_SE_C17, "Seiko Epson C17 family"),
1283 ENUM_ENT(EM_TI_C6000, "Texas Instruments TMS320C6000 DSP family"),
1284 ENUM_ENT(EM_TI_C2000, "Texas Instruments TMS320C2000 DSP family"),
1285 ENUM_ENT(EM_TI_C5500, "Texas Instruments TMS320C55x DSP family"),
1286 ENUM_ENT(EM_MMDSP_PLUS, "STMicroelectronics 64bit VLIW Data Signal Processor"),
1287 ENUM_ENT(EM_CYPRESS_M8C, "Cypress M8C microprocessor"),
1288 ENUM_ENT(EM_R32C, "Renesas R32C series microprocessors"),
1289 ENUM_ENT(EM_TRIMEDIA, "NXP Semiconductors TriMedia architecture family"),
1290 ENUM_ENT(EM_HEXAGON, "Qualcomm Hexagon"),
1291 ENUM_ENT(EM_8051, "Intel 8051 and variants"),
1292 ENUM_ENT(EM_STXP7X, "STMicroelectronics STxP7x family"),
1293 ENUM_ENT(EM_NDS32, "Andes Technology compact code size embedded RISC processor family"),
1294 ENUM_ENT(EM_ECOG1, "Cyan Technology eCOG1 microprocessor"),
1295 // FIXME: Following EM_ECOG1X definitions is dead code since EM_ECOG1X has
1296 // an identical number to EM_ECOG1.
1297 ENUM_ENT(EM_ECOG1X, "Cyan Technology eCOG1X family"),
1298 ENUM_ENT(EM_MAXQ30, "Dallas Semiconductor MAXQ30 Core microcontrollers"),
1299 ENUM_ENT(EM_XIMO16, "New Japan Radio (NJR) 16-bit DSP Processor"),
1300 ENUM_ENT(EM_MANIK, "M2000 Reconfigurable RISC Microprocessor"),
1301 ENUM_ENT(EM_CRAYNV2, "Cray Inc. NV2 vector architecture"),
1302 ENUM_ENT(EM_RX, "Renesas RX"),
1303 ENUM_ENT(EM_METAG, "Imagination Technologies Meta processor architecture"),
1304 ENUM_ENT(EM_MCST_ELBRUS, "MCST Elbrus general purpose hardware architecture"),
1305 ENUM_ENT(EM_ECOG16, "Cyan Technology eCOG16 family"),
1306 ENUM_ENT(EM_CR16, "National Semiconductor CompactRISC 16-bit processor"),
1307 ENUM_ENT(EM_ETPU, "Freescale Extended Time Processing Unit"),
1308 ENUM_ENT(EM_SLE9X, "Infineon Technologies SLE9X core"),
1309 ENUM_ENT(EM_L10M, "EM_L10M"),
1310 ENUM_ENT(EM_K10M, "EM_K10M"),
1311 ENUM_ENT(EM_AARCH64, "AArch64"),
1312 ENUM_ENT(EM_AVR32, "Atmel Corporation 32-bit microprocessor family"),
1313 ENUM_ENT(EM_STM8, "STMicroeletronics STM8 8-bit microcontroller"),
1314 ENUM_ENT(EM_TILE64, "Tilera TILE64 multicore architecture family"),
1315 ENUM_ENT(EM_TILEPRO, "Tilera TILEPro multicore architecture family"),
1316 ENUM_ENT(EM_MICROBLAZE, "Xilinx MicroBlaze 32-bit RISC soft processor core"),
1317 ENUM_ENT(EM_CUDA, "NVIDIA CUDA architecture"),
1318 ENUM_ENT(EM_TILEGX, "Tilera TILE-Gx multicore architecture family"),
1319 ENUM_ENT(EM_CLOUDSHIELD, "EM_CLOUDSHIELD"),
1320 ENUM_ENT(EM_COREA_1ST, "EM_COREA_1ST"),
1321 ENUM_ENT(EM_COREA_2ND, "EM_COREA_2ND"),
1322 ENUM_ENT(EM_ARC_COMPACT2, "EM_ARC_COMPACT2"),
1323 ENUM_ENT(EM_OPEN8, "EM_OPEN8"),
1324 ENUM_ENT(EM_RL78, "Renesas RL78"),
1325 ENUM_ENT(EM_VIDEOCORE5, "Broadcom VideoCore V processor"),
1326 ENUM_ENT(EM_78KOR, "EM_78KOR"),
1327 ENUM_ENT(EM_56800EX, "EM_56800EX"),
1328 ENUM_ENT(EM_AMDGPU, "EM_AMDGPU"),
1329 ENUM_ENT(EM_RISCV, "RISC-V"),
1330 ENUM_ENT(EM_LANAI, "EM_LANAI"),
1331 ENUM_ENT(EM_BPF, "EM_BPF"),
1332 ENUM_ENT(EM_VE, "NEC SX-Aurora Vector Engine"),
1333 ENUM_ENT(EM_LOONGARCH, "LoongArch"),
1334 ENUM_ENT(EM_INTELGT, "Intel Graphics Technology"),
1335};
1336// clang-format on
1337constexpr auto ElfMachineType = BUILD_ENUM_STRINGS(ElfMachineTypeDefs);
1338
1339constexpr EnumStringDef<unsigned, 2> ElfSymbolBindingsDefs[] = {
1340 {.Names: {"Local", "LOCAL"}, .Value: ELF::STB_LOCAL},
1341 {.Names: {"Global", "GLOBAL"}, .Value: ELF::STB_GLOBAL},
1342 {.Names: {"Weak", "WEAK"}, .Value: ELF::STB_WEAK},
1343 {.Names: {"Unique", "UNIQUE"}, .Value: ELF::STB_GNU_UNIQUE}};
1344constexpr auto ElfSymbolBindings = BUILD_ENUM_STRINGS(ElfSymbolBindingsDefs);
1345
1346constexpr EnumStringDef<unsigned, 2> ElfSymbolVisibilitiesDefs[] = {
1347 {.Names: {"DEFAULT", "DEFAULT"}, .Value: ELF::STV_DEFAULT},
1348 {.Names: {"INTERNAL", "INTERNAL"}, .Value: ELF::STV_INTERNAL},
1349 {.Names: {"HIDDEN", "HIDDEN"}, .Value: ELF::STV_HIDDEN},
1350 {.Names: {"PROTECTED", "PROTECTED"}, .Value: ELF::STV_PROTECTED}};
1351constexpr auto ElfSymbolVisibilities =
1352 BUILD_ENUM_STRINGS(ElfSymbolVisibilitiesDefs);
1353
1354constexpr EnumStringDef<unsigned, 1> AMDGPUSymbolTypesDefs[] = {
1355 {.Names: {"AMDGPU_HSA_KERNEL"}, .Value: ELF::STT_AMDGPU_HSA_KERNEL}};
1356constexpr auto AMDGPUSymbolTypes = BUILD_ENUM_STRINGS(AMDGPUSymbolTypesDefs);
1357
1358static const char *getGroupType(uint32_t Flag) {
1359 if (Flag & ELF::GRP_COMDAT)
1360 return "COMDAT";
1361 else
1362 return "(unknown)";
1363}
1364
1365constexpr EnumStringDef<unsigned, 2> ElfSectionFlagsDefs[] = {
1366 ENUM_ENT(SHF_WRITE, "W"), ENUM_ENT(SHF_ALLOC, "A"),
1367 ENUM_ENT(SHF_EXECINSTR, "X"), ENUM_ENT(SHF_MERGE, "M"),
1368 ENUM_ENT(SHF_STRINGS, "S"), ENUM_ENT(SHF_INFO_LINK, "I"),
1369 ENUM_ENT(SHF_LINK_ORDER, "L"), ENUM_ENT(SHF_OS_NONCONFORMING, "O"),
1370 ENUM_ENT(SHF_GROUP, "G"), ENUM_ENT(SHF_TLS, "T"),
1371 ENUM_ENT(SHF_COMPRESSED, "C"), ENUM_ENT(SHF_EXCLUDE, "E"),
1372};
1373constexpr auto ElfSectionFlags = BUILD_ENUM_STRINGS(ElfSectionFlagsDefs);
1374
1375constexpr EnumStringDef<unsigned, 2> ElfGNUSectionFlagsDefs[] = {
1376 ENUM_ENT(SHF_GNU_RETAIN, "R")};
1377constexpr auto ElfGNUSectionFlags = BUILD_ENUM_STRINGS(ElfGNUSectionFlagsDefs);
1378
1379constexpr EnumStringDef<unsigned, 2> ElfSolarisSectionFlagsDefs[] = {
1380 ENUM_ENT(SHF_SUNW_NODISCARD, "R")};
1381constexpr auto ElfSolarisSectionFlags =
1382 BUILD_ENUM_STRINGS(ElfSolarisSectionFlagsDefs);
1383
1384constexpr EnumStringDef<unsigned, 2> ElfXCoreSectionFlagsDefs[] = {
1385 ENUM_ENT(XCORE_SHF_CP_SECTION, ""), ENUM_ENT(XCORE_SHF_DP_SECTION, "")};
1386constexpr auto ElfXCoreSectionFlags =
1387 BUILD_ENUM_STRINGS(ElfXCoreSectionFlagsDefs);
1388
1389constexpr EnumStringDef<unsigned, 2> ElfAArch64SectionFlagsDefs[] = {
1390 ENUM_ENT(SHF_AARCH64_PURECODE, "y")};
1391constexpr auto ElfAArch64SectionFlags =
1392 BUILD_ENUM_STRINGS(ElfAArch64SectionFlagsDefs);
1393
1394constexpr EnumStringDef<unsigned, 2> ElfARMSectionFlagsDefs[] = {
1395 ENUM_ENT(SHF_ARM_PURECODE, "y")};
1396constexpr auto ElfARMSectionFlags = BUILD_ENUM_STRINGS(ElfARMSectionFlagsDefs);
1397
1398constexpr EnumStringDef<unsigned, 2> ElfHexagonSectionFlagsDefs[] = {
1399 ENUM_ENT(SHF_HEX_GPREL, "")};
1400constexpr auto ElfHexagonSectionFlags =
1401 BUILD_ENUM_STRINGS(ElfHexagonSectionFlagsDefs);
1402
1403constexpr EnumStringDef<unsigned, 2> ElfMipsSectionFlagsDefs[] = {
1404 ENUM_ENT(SHF_MIPS_NODUPES, ""), ENUM_ENT(SHF_MIPS_NAMES, ""),
1405 ENUM_ENT(SHF_MIPS_LOCAL, ""), ENUM_ENT(SHF_MIPS_NOSTRIP, ""),
1406 ENUM_ENT(SHF_MIPS_GPREL, ""), ENUM_ENT(SHF_MIPS_MERGE, ""),
1407 ENUM_ENT(SHF_MIPS_ADDR, ""), ENUM_ENT(SHF_MIPS_STRING, "")};
1408constexpr auto ElfMipsSectionFlags =
1409 BUILD_ENUM_STRINGS(ElfMipsSectionFlagsDefs);
1410
1411constexpr EnumStringDef<unsigned, 2> ElfX86_64SectionFlagsDefs[] = {
1412 ENUM_ENT(SHF_X86_64_LARGE, "l")};
1413constexpr auto ElfX86_64SectionFlags =
1414 BUILD_ENUM_STRINGS(ElfX86_64SectionFlagsDefs);
1415
1416static std::vector<const EnumString<unsigned, 2> *>
1417getSectionFlagsForTarget(unsigned EOSAbi, unsigned EMachine) {
1418 std::vector<const EnumString<unsigned, 2> *> Ret;
1419 for (const auto &Entry : EnumStrings(ElfSectionFlags))
1420 Ret.push_back(x: &Entry);
1421 switch (EOSAbi) {
1422 case ELFOSABI_SOLARIS:
1423 for (const auto &Entry : EnumStrings(ElfSolarisSectionFlags))
1424 Ret.push_back(x: &Entry);
1425 break;
1426 default:
1427 for (const auto &Entry : EnumStrings(ElfGNUSectionFlags))
1428 Ret.push_back(x: &Entry);
1429 break;
1430 }
1431 switch (EMachine) {
1432 case EM_AARCH64:
1433 for (const auto &Entry : EnumStrings(ElfAArch64SectionFlags))
1434 Ret.push_back(x: &Entry);
1435 break;
1436 case EM_ARM:
1437 for (const auto &Entry : EnumStrings(ElfARMSectionFlags))
1438 Ret.push_back(x: &Entry);
1439 break;
1440 case EM_HEXAGON:
1441 for (const auto &Entry : EnumStrings(ElfHexagonSectionFlags))
1442 Ret.push_back(x: &Entry);
1443 break;
1444 case EM_MIPS:
1445 for (const auto &Entry : EnumStrings(ElfMipsSectionFlags))
1446 Ret.push_back(x: &Entry);
1447 break;
1448 case EM_X86_64:
1449 for (const auto &Entry : EnumStrings(ElfX86_64SectionFlags))
1450 Ret.push_back(x: &Entry);
1451 break;
1452 case EM_XCORE:
1453 for (const auto &Entry : EnumStrings(ElfXCoreSectionFlags))
1454 Ret.push_back(x: &Entry);
1455 break;
1456 default:
1457 break;
1458 }
1459 return Ret;
1460}
1461
1462static std::string getGNUFlags(unsigned EOSAbi, unsigned EMachine,
1463 uint64_t Flags) {
1464 // Here we are trying to build the flags string in the same way as GNU does.
1465 // It is not that straightforward. Imagine we have sh_flags == 0x90000000.
1466 // SHF_EXCLUDE ("E") has a value of 0x80000000 and SHF_MASKPROC is 0xf0000000.
1467 // GNU readelf will not print "E" or "Ep" in this case, but will print just
1468 // "p". It only will print "E" when no other processor flag is set.
1469 std::string Str;
1470 bool HasUnknownFlag = false;
1471 bool HasOSFlag = false;
1472 bool HasProcFlag = false;
1473 auto FlagsList = getSectionFlagsForTarget(EOSAbi, EMachine);
1474 while (Flags) {
1475 // Take the least significant bit as a flag.
1476 uint64_t Flag = Flags & -Flags;
1477 Flags -= Flag;
1478
1479 // Find the flag in the known flags list.
1480 auto I = llvm::find_if(Range&: FlagsList, P: [=](const EnumString<unsigned, 2> *E) {
1481 // Flags with empty names are not printed in GNU style output.
1482 return E->value() == Flag && !E->name(Idx: 1).empty();
1483 });
1484 if (I != FlagsList.end()) {
1485 Str += (*I)->name(Idx: 1);
1486 continue;
1487 }
1488
1489 // If we did not find a matching regular flag, then we deal with an OS
1490 // specific flag, processor specific flag or an unknown flag.
1491 if (Flag & ELF::SHF_MASKOS) {
1492 HasOSFlag = true;
1493 Flags &= ~ELF::SHF_MASKOS;
1494 } else if (Flag & ELF::SHF_MASKPROC) {
1495 HasProcFlag = true;
1496 // Mask off all the processor-specific bits. This removes the SHF_EXCLUDE
1497 // bit if set so that it doesn't also get printed.
1498 Flags &= ~ELF::SHF_MASKPROC;
1499 } else {
1500 HasUnknownFlag = true;
1501 }
1502 }
1503
1504 // "o", "p" and "x" are printed last.
1505 if (HasOSFlag)
1506 Str += "o";
1507 if (HasProcFlag)
1508 Str += "p";
1509 if (HasUnknownFlag)
1510 Str += "x";
1511 return Str;
1512}
1513
1514static StringRef segmentTypeToString(unsigned Arch, unsigned Type) {
1515 // Check potentially overlapped processor-specific program header type.
1516 switch (Arch) {
1517 case ELF::EM_ARM:
1518 switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_ARM_EXIDX); }
1519 break;
1520 case ELF::EM_MIPS:
1521 case ELF::EM_MIPS_RS3_LE:
1522 switch (Type) {
1523 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_REGINFO);
1524 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_RTPROC);
1525 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_OPTIONS);
1526 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_ABIFLAGS);
1527 }
1528 break;
1529 case ELF::EM_RISCV:
1530 switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_RISCV_ATTRIBUTES); }
1531 }
1532
1533 switch (Type) {
1534 LLVM_READOBJ_ENUM_CASE(ELF, PT_NULL);
1535 LLVM_READOBJ_ENUM_CASE(ELF, PT_LOAD);
1536 LLVM_READOBJ_ENUM_CASE(ELF, PT_DYNAMIC);
1537 LLVM_READOBJ_ENUM_CASE(ELF, PT_INTERP);
1538 LLVM_READOBJ_ENUM_CASE(ELF, PT_NOTE);
1539 LLVM_READOBJ_ENUM_CASE(ELF, PT_SHLIB);
1540 LLVM_READOBJ_ENUM_CASE(ELF, PT_PHDR);
1541 LLVM_READOBJ_ENUM_CASE(ELF, PT_TLS);
1542
1543 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_EH_FRAME);
1544 LLVM_READOBJ_ENUM_CASE(ELF, PT_SUNW_UNWIND);
1545
1546 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_STACK);
1547 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_RELRO);
1548 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_PROPERTY);
1549 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_SFRAME);
1550
1551 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_MUTABLE);
1552 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_RANDOMIZE);
1553 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_WXNEEDED);
1554 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_NOBTCFI);
1555 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_SYSCALLS);
1556 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_BOOTDATA);
1557 default:
1558 return "";
1559 }
1560}
1561
1562static std::string getGNUPtType(unsigned Arch, unsigned Type) {
1563 StringRef Seg = segmentTypeToString(Arch, Type);
1564 if (Seg.empty())
1565 return std::string("<unknown>: ") + to_string(Value: format_hex(N: Type, Width: 1));
1566
1567 // E.g. "PT_ARM_EXIDX" -> "EXIDX".
1568 if (Seg.consume_front(Prefix: "PT_ARM_"))
1569 return Seg.str();
1570
1571 // E.g. "PT_MIPS_REGINFO" -> "REGINFO".
1572 if (Seg.consume_front(Prefix: "PT_MIPS_"))
1573 return Seg.str();
1574
1575 // E.g. "PT_RISCV_ATTRIBUTES"
1576 if (Seg.consume_front(Prefix: "PT_RISCV_"))
1577 return Seg.str();
1578
1579 // E.g. "PT_LOAD" -> "LOAD".
1580 assert(Seg.starts_with("PT_"));
1581 return Seg.drop_front(N: 3).str();
1582}
1583
1584constexpr EnumStringDef<unsigned, 2> ElfSegmentFlagsDefs[] = {
1585 ENUM_ENT_1(PF_X),
1586 ENUM_ENT_1(PF_W),
1587 ENUM_ENT_1(PF_R),
1588};
1589constexpr auto ElfSegmentFlags = BUILD_ENUM_STRINGS(ElfSegmentFlagsDefs);
1590
1591constexpr EnumStringDef<unsigned, 2> ElfHeaderMipsFlagsDefs[] = {
1592 ENUM_ENT(EF_MIPS_NOREORDER, "noreorder"),
1593 ENUM_ENT(EF_MIPS_PIC, "pic"),
1594 ENUM_ENT(EF_MIPS_CPIC, "cpic"),
1595 ENUM_ENT(EF_MIPS_ABI2, "abi2"),
1596 ENUM_ENT(EF_MIPS_32BITMODE, "32bitmode"),
1597 ENUM_ENT(EF_MIPS_FP64, "fp64"),
1598 ENUM_ENT(EF_MIPS_NAN2008, "nan2008"),
1599 ENUM_ENT(EF_MIPS_ABI_O32, "o32"),
1600 ENUM_ENT(EF_MIPS_ABI_O64, "o64"),
1601 ENUM_ENT(EF_MIPS_ABI_EABI32, "eabi32"),
1602 ENUM_ENT(EF_MIPS_ABI_EABI64, "eabi64"),
1603 ENUM_ENT(EF_MIPS_MACH_3900, "3900"),
1604 ENUM_ENT(EF_MIPS_MACH_4010, "4010"),
1605 ENUM_ENT(EF_MIPS_MACH_4100, "4100"),
1606 ENUM_ENT(EF_MIPS_MACH_4650, "4650"),
1607 ENUM_ENT(EF_MIPS_MACH_4120, "4120"),
1608 ENUM_ENT(EF_MIPS_MACH_4111, "4111"),
1609 ENUM_ENT(EF_MIPS_MACH_SB1, "sb1"),
1610 ENUM_ENT(EF_MIPS_MACH_OCTEON, "octeon"),
1611 ENUM_ENT(EF_MIPS_MACH_XLR, "xlr"),
1612 ENUM_ENT(EF_MIPS_MACH_OCTEON2, "octeon2"),
1613 ENUM_ENT(EF_MIPS_MACH_OCTEON3, "octeon3"),
1614 ENUM_ENT(EF_MIPS_MACH_5400, "5400"),
1615 ENUM_ENT(EF_MIPS_MACH_5900, "5900"),
1616 ENUM_ENT(EF_MIPS_MACH_5500, "5500"),
1617 ENUM_ENT(EF_MIPS_MACH_9000, "9000"),
1618 ENUM_ENT(EF_MIPS_MACH_LS2E, "loongson-2e"),
1619 ENUM_ENT(EF_MIPS_MACH_LS2F, "loongson-2f"),
1620 ENUM_ENT(EF_MIPS_MACH_LS3A, "loongson-3a"),
1621 ENUM_ENT(EF_MIPS_MICROMIPS, "micromips"),
1622 ENUM_ENT(EF_MIPS_ARCH_ASE_M16, "mips16"),
1623 ENUM_ENT(EF_MIPS_ARCH_ASE_MDMX, "mdmx"),
1624 ENUM_ENT(EF_MIPS_ARCH_1, "mips1"),
1625 ENUM_ENT(EF_MIPS_ARCH_2, "mips2"),
1626 ENUM_ENT(EF_MIPS_ARCH_3, "mips3"),
1627 ENUM_ENT(EF_MIPS_ARCH_4, "mips4"),
1628 ENUM_ENT(EF_MIPS_ARCH_5, "mips5"),
1629 ENUM_ENT(EF_MIPS_ARCH_32, "mips32"),
1630 ENUM_ENT(EF_MIPS_ARCH_64, "mips64"),
1631 ENUM_ENT(EF_MIPS_ARCH_32R2, "mips32r2"),
1632 ENUM_ENT(EF_MIPS_ARCH_64R2, "mips64r2"),
1633 ENUM_ENT(EF_MIPS_ARCH_32R6, "mips32r6"),
1634 ENUM_ENT(EF_MIPS_ARCH_64R6, "mips64r6"),
1635};
1636constexpr auto ElfHeaderMipsFlags = BUILD_ENUM_STRINGS(ElfHeaderMipsFlagsDefs);
1637
1638#define X(NUM, ENUM, NAME) ENUM_ENT(ENUM, NAME),
1639#define AMDGPU_MACH_ENUM_ENTS \
1640 AMDGPU_MACH_LIST(X) ENUM_ENT(EF_AMDGPU_MACH_NONE, "none")
1641
1642constexpr EnumStringDef<unsigned, 2> ElfHeaderAMDGPUFlagsABIVersion3Defs[] = {
1643 AMDGPU_MACH_ENUM_ENTS,
1644 ENUM_ENT(EF_AMDGPU_FEATURE_XNACK_V3, "xnack"),
1645 ENUM_ENT(EF_AMDGPU_FEATURE_SRAMECC_V3, "sramecc"),
1646};
1647constexpr auto ElfHeaderAMDGPUFlagsABIVersion3 =
1648 BUILD_ENUM_STRINGS(ElfHeaderAMDGPUFlagsABIVersion3Defs);
1649
1650constexpr EnumStringDef<unsigned, 2> ElfHeaderAMDGPUFlagsABIVersion4Defs[] = {
1651 AMDGPU_MACH_ENUM_ENTS,
1652 ENUM_ENT(EF_AMDGPU_FEATURE_XNACK_ANY_V4, "xnack"),
1653 ENUM_ENT(EF_AMDGPU_FEATURE_XNACK_OFF_V4, "xnack-"),
1654 ENUM_ENT(EF_AMDGPU_FEATURE_XNACK_ON_V4, "xnack+"),
1655 ENUM_ENT(EF_AMDGPU_FEATURE_SRAMECC_ANY_V4, "sramecc"),
1656 ENUM_ENT(EF_AMDGPU_FEATURE_SRAMECC_OFF_V4, "sramecc-"),
1657 ENUM_ENT(EF_AMDGPU_FEATURE_SRAMECC_ON_V4, "sramecc+"),
1658};
1659constexpr auto ElfHeaderAMDGPUFlagsABIVersion4 =
1660 BUILD_ENUM_STRINGS(ElfHeaderAMDGPUFlagsABIVersion4Defs);
1661
1662constexpr EnumStringDef<unsigned, 2> ElfHeaderNVPTXFlagsDefs[] = {
1663 ENUM_ENT(EF_CUDA_SM20, "sm_20"),
1664 ENUM_ENT(EF_CUDA_SM21, "sm_21"),
1665 ENUM_ENT(EF_CUDA_SM30, "sm_30"),
1666 ENUM_ENT(EF_CUDA_SM32, "sm_32"),
1667 ENUM_ENT(EF_CUDA_SM35, "sm_35"),
1668 ENUM_ENT(EF_CUDA_SM37, "sm_37"),
1669 ENUM_ENT(EF_CUDA_SM50, "sm_50"),
1670 ENUM_ENT(EF_CUDA_SM52, "sm_52"),
1671 ENUM_ENT(EF_CUDA_SM53, "sm_53"),
1672 ENUM_ENT(EF_CUDA_SM60, "sm_60"),
1673 ENUM_ENT(EF_CUDA_SM61, "sm_61"),
1674 ENUM_ENT(EF_CUDA_SM62, "sm_62"),
1675 ENUM_ENT(EF_CUDA_SM70, "sm_70"),
1676 ENUM_ENT(EF_CUDA_SM72, "sm_72"),
1677 ENUM_ENT(EF_CUDA_SM75, "sm_75"),
1678 ENUM_ENT(EF_CUDA_SM80, "sm_80"),
1679 ENUM_ENT(EF_CUDA_SM86, "sm_86"),
1680 ENUM_ENT(EF_CUDA_SM87, "sm_87"),
1681 ENUM_ENT(EF_CUDA_SM88, "sm_88"),
1682 ENUM_ENT(EF_CUDA_SM89, "sm_89"),
1683 ENUM_ENT(EF_CUDA_SM90, "sm_90"),
1684 ENUM_ENT(EF_CUDA_SM100, "sm_100"),
1685 ENUM_ENT(EF_CUDA_SM101, "sm_101"),
1686 ENUM_ENT(EF_CUDA_SM103, "sm_103"),
1687 ENUM_ENT(EF_CUDA_SM110, "sm_110"),
1688 ENUM_ENT(EF_CUDA_SM120, "sm_120"),
1689 ENUM_ENT(EF_CUDA_SM121, "sm_121"),
1690 ENUM_ENT(EF_CUDA_SM20 << EF_CUDA_SM_OFFSET, "sm_20"),
1691 ENUM_ENT(EF_CUDA_SM21 << EF_CUDA_SM_OFFSET, "sm_21"),
1692 ENUM_ENT(EF_CUDA_SM30 << EF_CUDA_SM_OFFSET, "sm_30"),
1693 ENUM_ENT(EF_CUDA_SM32 << EF_CUDA_SM_OFFSET, "sm_32"),
1694 ENUM_ENT(EF_CUDA_SM35 << EF_CUDA_SM_OFFSET, "sm_35"),
1695 ENUM_ENT(EF_CUDA_SM37 << EF_CUDA_SM_OFFSET, "sm_37"),
1696 ENUM_ENT(EF_CUDA_SM50 << EF_CUDA_SM_OFFSET, "sm_50"),
1697 ENUM_ENT(EF_CUDA_SM52 << EF_CUDA_SM_OFFSET, "sm_52"),
1698 ENUM_ENT(EF_CUDA_SM53 << EF_CUDA_SM_OFFSET, "sm_53"),
1699 ENUM_ENT(EF_CUDA_SM60 << EF_CUDA_SM_OFFSET, "sm_60"),
1700 ENUM_ENT(EF_CUDA_SM61 << EF_CUDA_SM_OFFSET, "sm_61"),
1701 ENUM_ENT(EF_CUDA_SM62 << EF_CUDA_SM_OFFSET, "sm_62"),
1702 ENUM_ENT(EF_CUDA_SM70 << EF_CUDA_SM_OFFSET, "sm_70"),
1703 ENUM_ENT(EF_CUDA_SM72 << EF_CUDA_SM_OFFSET, "sm_72"),
1704 ENUM_ENT(EF_CUDA_SM75 << EF_CUDA_SM_OFFSET, "sm_75"),
1705 ENUM_ENT(EF_CUDA_SM80 << EF_CUDA_SM_OFFSET, "sm_80"),
1706 ENUM_ENT(EF_CUDA_SM86 << EF_CUDA_SM_OFFSET, "sm_86"),
1707 ENUM_ENT(EF_CUDA_SM87 << EF_CUDA_SM_OFFSET, "sm_87"),
1708 ENUM_ENT(EF_CUDA_SM88 << EF_CUDA_SM_OFFSET, "sm_88"),
1709 ENUM_ENT(EF_CUDA_SM89 << EF_CUDA_SM_OFFSET, "sm_89"),
1710 ENUM_ENT(EF_CUDA_SM90 << EF_CUDA_SM_OFFSET, "sm_90"),
1711 ENUM_ENT(EF_CUDA_SM100 << EF_CUDA_SM_OFFSET, "sm_100"),
1712 ENUM_ENT(EF_CUDA_SM101 << EF_CUDA_SM_OFFSET, "sm_101"),
1713 ENUM_ENT(EF_CUDA_SM103 << EF_CUDA_SM_OFFSET, "sm_103"),
1714 ENUM_ENT(EF_CUDA_SM110 << EF_CUDA_SM_OFFSET, "sm_110"),
1715 ENUM_ENT(EF_CUDA_SM120 << EF_CUDA_SM_OFFSET, "sm_120"),
1716 ENUM_ENT(EF_CUDA_SM121 << EF_CUDA_SM_OFFSET, "sm_121"),
1717};
1718constexpr auto ElfHeaderNVPTXFlags =
1719 BUILD_ENUM_STRINGS(ElfHeaderNVPTXFlagsDefs);
1720
1721constexpr EnumStringDef<unsigned, 2> ElfHeaderRISCVFlagsDefs[] = {
1722 ENUM_ENT(EF_RISCV_RVC, "RVC"),
1723 ENUM_ENT(EF_RISCV_FLOAT_ABI_SINGLE, "single-float ABI"),
1724 ENUM_ENT(EF_RISCV_FLOAT_ABI_DOUBLE, "double-float ABI"),
1725 ENUM_ENT(EF_RISCV_FLOAT_ABI_QUAD, "quad-float ABI"),
1726 ENUM_ENT(EF_RISCV_RVE, "RVE"),
1727 ENUM_ENT(EF_RISCV_TSO, "TSO"),
1728};
1729constexpr auto ElfHeaderRISCVFlags =
1730 BUILD_ENUM_STRINGS(ElfHeaderRISCVFlagsDefs);
1731
1732constexpr EnumStringDef<unsigned, 2> ElfHeaderSPARCFlagsDefs[] = {
1733 ENUM_ENT(EF_SPARC_32PLUS, "V8+ ABI"),
1734 ENUM_ENT(EF_SPARC_SUN_US1, "Sun UltraSPARC I extensions"),
1735 ENUM_ENT(EF_SPARC_HAL_R1, "HAL/Fujitsu R1 extensions"),
1736 ENUM_ENT(EF_SPARC_SUN_US3, "Sun UltraSPARC III extensions"),
1737 ENUM_ENT(EF_SPARCV9_TSO, "Total Store Ordering"),
1738 ENUM_ENT(EF_SPARCV9_PSO, "Partial Store Ordering"),
1739 ENUM_ENT(EF_SPARCV9_RMO, "Relaxed Memory Ordering"),
1740};
1741constexpr auto ElfHeaderSPARCFlags =
1742 BUILD_ENUM_STRINGS(ElfHeaderSPARCFlagsDefs);
1743
1744constexpr EnumStringDef<unsigned, 2> ElfHeaderAVRFlagsDefs[] = {
1745 ENUM_ENT_1(EF_AVR_ARCH_AVR1),
1746 ENUM_ENT_1(EF_AVR_ARCH_AVR2),
1747 ENUM_ENT_1(EF_AVR_ARCH_AVR25),
1748 ENUM_ENT_1(EF_AVR_ARCH_AVR3),
1749 ENUM_ENT_1(EF_AVR_ARCH_AVR31),
1750 ENUM_ENT_1(EF_AVR_ARCH_AVR35),
1751 ENUM_ENT_1(EF_AVR_ARCH_AVR4),
1752 ENUM_ENT_1(EF_AVR_ARCH_AVR5),
1753 ENUM_ENT_1(EF_AVR_ARCH_AVR51),
1754 ENUM_ENT_1(EF_AVR_ARCH_AVR6),
1755 ENUM_ENT_1(EF_AVR_ARCH_AVRTINY),
1756 ENUM_ENT_1(EF_AVR_ARCH_XMEGA1),
1757 ENUM_ENT_1(EF_AVR_ARCH_XMEGA2),
1758 ENUM_ENT_1(EF_AVR_ARCH_XMEGA3),
1759 ENUM_ENT_1(EF_AVR_ARCH_XMEGA4),
1760 ENUM_ENT_1(EF_AVR_ARCH_XMEGA5),
1761 ENUM_ENT_1(EF_AVR_ARCH_XMEGA6),
1762 ENUM_ENT_1(EF_AVR_ARCH_XMEGA7),
1763 ENUM_ENT(EF_AVR_LINKRELAX_PREPARED, "relaxable"),
1764};
1765constexpr auto ElfHeaderAVRFlags = BUILD_ENUM_STRINGS(ElfHeaderAVRFlagsDefs);
1766
1767constexpr EnumStringDef<unsigned, 2> ElfHeaderLoongArchFlagsDefs[] = {
1768 ENUM_ENT(EF_LOONGARCH_ABI_SOFT_FLOAT, "SOFT-FLOAT"),
1769 ENUM_ENT(EF_LOONGARCH_ABI_SINGLE_FLOAT, "SINGLE-FLOAT"),
1770 ENUM_ENT(EF_LOONGARCH_ABI_DOUBLE_FLOAT, "DOUBLE-FLOAT"),
1771 ENUM_ENT(EF_LOONGARCH_OBJABI_V0, "OBJ-v0"),
1772 ENUM_ENT(EF_LOONGARCH_OBJABI_V1, "OBJ-v1"),
1773};
1774constexpr auto ElfHeaderLoongArchFlags =
1775 BUILD_ENUM_STRINGS(ElfHeaderLoongArchFlagsDefs);
1776
1777constexpr EnumStringDef<unsigned, 2> ElfHeaderXtensaFlagsDefs[] = {
1778 ENUM_ENT_1(EF_XTENSA_MACH_NONE),
1779 ENUM_ENT_1(EF_XTENSA_XT_INSN),
1780 ENUM_ENT_1(EF_XTENSA_XT_LIT),
1781};
1782constexpr auto ElfHeaderXtensaFlags =
1783 BUILD_ENUM_STRINGS(ElfHeaderXtensaFlagsDefs);
1784
1785constexpr EnumStringDef<unsigned, 2> ElfSymOtherFlagsDefs[] = {
1786 ENUM_ENT_1(STV_INTERNAL),
1787 ENUM_ENT_1(STV_HIDDEN),
1788 ENUM_ENT_1(STV_PROTECTED),
1789};
1790constexpr auto ElfSymOtherFlags = BUILD_ENUM_STRINGS(ElfSymOtherFlagsDefs);
1791
1792constexpr EnumStringDef<unsigned, 2> ElfMipsSymOtherFlagsDefs[] = {
1793 ENUM_ENT_1(STO_MIPS_OPTIONAL),
1794 ENUM_ENT_1(STO_MIPS_PLT),
1795 ENUM_ENT_1(STO_MIPS_PIC),
1796 ENUM_ENT_1(STO_MIPS_MICROMIPS),
1797};
1798constexpr auto ElfMipsSymOtherFlags =
1799 BUILD_ENUM_STRINGS(ElfMipsSymOtherFlagsDefs);
1800
1801constexpr EnumStringDef<unsigned, 2> ElfAArch64SymOtherFlagsDefs[] = {
1802 ENUM_ENT_1(STO_AARCH64_VARIANT_PCS),
1803};
1804constexpr auto ElfAArch64SymOtherFlags =
1805 BUILD_ENUM_STRINGS(ElfAArch64SymOtherFlagsDefs);
1806
1807constexpr EnumStringDef<unsigned, 2> ElfMips16SymOtherFlagsDefs[] = {
1808 ENUM_ENT_1(STO_MIPS_OPTIONAL),
1809 ENUM_ENT_1(STO_MIPS_PLT),
1810 ENUM_ENT_1(STO_MIPS_MIPS16),
1811};
1812constexpr auto ElfMips16SymOtherFlags =
1813 BUILD_ENUM_STRINGS(ElfMips16SymOtherFlagsDefs);
1814
1815constexpr EnumStringDef<unsigned, 2> ElfRISCVSymOtherFlagsDefs[] = {
1816 ENUM_ENT_1(STO_RISCV_VARIANT_CC),
1817};
1818constexpr auto ElfRISCVSymOtherFlags =
1819 BUILD_ENUM_STRINGS(ElfRISCVSymOtherFlagsDefs);
1820
1821static const char *getElfMipsOptionsOdkType(unsigned Odk) {
1822 switch (Odk) {
1823 LLVM_READOBJ_ENUM_CASE(ELF, ODK_NULL);
1824 LLVM_READOBJ_ENUM_CASE(ELF, ODK_REGINFO);
1825 LLVM_READOBJ_ENUM_CASE(ELF, ODK_EXCEPTIONS);
1826 LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAD);
1827 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWPATCH);
1828 LLVM_READOBJ_ENUM_CASE(ELF, ODK_FILL);
1829 LLVM_READOBJ_ENUM_CASE(ELF, ODK_TAGS);
1830 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWAND);
1831 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWOR);
1832 LLVM_READOBJ_ENUM_CASE(ELF, ODK_GP_GROUP);
1833 LLVM_READOBJ_ENUM_CASE(ELF, ODK_IDENT);
1834 LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAGESIZE);
1835 default:
1836 return "Unknown";
1837 }
1838}
1839
1840template <typename ELFT>
1841std::pair<const typename ELFT::Phdr *, const typename ELFT::Shdr *>
1842ELFDumper<ELFT>::findDynamic() {
1843 // Try to locate the PT_DYNAMIC header.
1844 const Elf_Phdr *DynamicPhdr = nullptr;
1845 if (Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = Obj.program_headers()) {
1846 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
1847 if (Phdr.p_type != ELF::PT_DYNAMIC)
1848 continue;
1849 DynamicPhdr = &Phdr;
1850 break;
1851 }
1852 } else {
1853 reportUniqueWarning(
1854 "unable to read program headers to locate the PT_DYNAMIC segment: " +
1855 toString(PhdrsOrErr.takeError()));
1856 }
1857
1858 // Try to locate the .dynamic section in the sections header table.
1859 const Elf_Shdr *DynamicSec = nullptr;
1860 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
1861 if (Sec.sh_type != ELF::SHT_DYNAMIC)
1862 continue;
1863 DynamicSec = &Sec;
1864 break;
1865 }
1866
1867 if (DynamicPhdr && ((DynamicPhdr->p_offset + DynamicPhdr->p_filesz >
1868 ObjF.getMemoryBufferRef().getBufferSize()) ||
1869 (DynamicPhdr->p_offset + DynamicPhdr->p_filesz <
1870 DynamicPhdr->p_offset))) {
1871 reportUniqueWarning(
1872 "PT_DYNAMIC segment offset (0x" +
1873 Twine::utohexstr(Val: DynamicPhdr->p_offset) + ") + file size (0x" +
1874 Twine::utohexstr(Val: DynamicPhdr->p_filesz) +
1875 ") exceeds the size of the file (0x" +
1876 Twine::utohexstr(Val: ObjF.getMemoryBufferRef().getBufferSize()) + ")");
1877 // Don't use the broken dynamic header.
1878 DynamicPhdr = nullptr;
1879 }
1880
1881 if (DynamicPhdr && DynamicSec) {
1882 if (DynamicSec->sh_addr + DynamicSec->sh_size >
1883 DynamicPhdr->p_vaddr + DynamicPhdr->p_memsz ||
1884 DynamicSec->sh_addr < DynamicPhdr->p_vaddr)
1885 reportUniqueWarning(describe(Sec: *DynamicSec) +
1886 " is not contained within the "
1887 "PT_DYNAMIC segment");
1888
1889 if (DynamicSec->sh_addr != DynamicPhdr->p_vaddr)
1890 reportUniqueWarning(describe(Sec: *DynamicSec) + " is not at the start of "
1891 "PT_DYNAMIC segment");
1892 }
1893
1894 return std::make_pair(DynamicPhdr, DynamicSec);
1895}
1896
1897template <typename ELFT>
1898void ELFDumper<ELFT>::loadDynamicTable() {
1899 const Elf_Phdr *DynamicPhdr;
1900 const Elf_Shdr *DynamicSec;
1901 std::tie(DynamicPhdr, DynamicSec) = findDynamic();
1902 if (!DynamicPhdr && !DynamicSec)
1903 return;
1904
1905 DynRegionInfo FromPhdr(ObjF, *this);
1906 bool IsPhdrTableValid = false;
1907 if (DynamicPhdr) {
1908 // Use cantFail(), because p_offset/p_filesz fields of a PT_DYNAMIC are
1909 // validated in findDynamic() and so createDRI() is not expected to fail.
1910 FromPhdr = cantFail(createDRI(Offset: DynamicPhdr->p_offset, Size: DynamicPhdr->p_filesz,
1911 EntSize: sizeof(Elf_Dyn)));
1912 FromPhdr.SizePrintName = "PT_DYNAMIC size";
1913 FromPhdr.EntSizePrintName = "";
1914 IsPhdrTableValid = !FromPhdr.template getAsArrayRef<Elf_Dyn>().empty();
1915 }
1916
1917 // Locate the dynamic table described in a section header.
1918 // Ignore sh_entsize and use the expected value for entry size explicitly.
1919 // This allows us to dump dynamic sections with a broken sh_entsize
1920 // field.
1921 DynRegionInfo FromSec(ObjF, *this);
1922 bool IsSecTableValid = false;
1923 if (DynamicSec) {
1924 Expected<DynRegionInfo> RegOrErr =
1925 createDRI(Offset: DynamicSec->sh_offset, Size: DynamicSec->sh_size, EntSize: sizeof(Elf_Dyn));
1926 if (RegOrErr) {
1927 FromSec = *RegOrErr;
1928 FromSec.Context = describe(Sec: *DynamicSec);
1929 FromSec.EntSizePrintName = "";
1930 IsSecTableValid = !FromSec.template getAsArrayRef<Elf_Dyn>().empty();
1931 } else {
1932 reportUniqueWarning("unable to read the dynamic table from " +
1933 describe(Sec: *DynamicSec) + ": " +
1934 toString(E: RegOrErr.takeError()));
1935 }
1936 }
1937
1938 // When we only have information from one of the SHT_DYNAMIC section header or
1939 // PT_DYNAMIC program header, just use that.
1940 if (!DynamicPhdr || !DynamicSec) {
1941 if ((DynamicPhdr && IsPhdrTableValid) || (DynamicSec && IsSecTableValid)) {
1942 DynamicTable = DynamicPhdr ? FromPhdr : FromSec;
1943 parseDynamicTable();
1944 } else {
1945 reportUniqueWarning("no valid dynamic table was found");
1946 }
1947 return;
1948 }
1949
1950 // At this point we have tables found from the section header and from the
1951 // dynamic segment. Usually they match, but we have to do sanity checks to
1952 // verify that.
1953
1954 if (FromPhdr.Addr != FromSec.Addr)
1955 reportUniqueWarning("SHT_DYNAMIC section header and PT_DYNAMIC "
1956 "program header disagree about "
1957 "the location of the dynamic table");
1958
1959 if (!IsPhdrTableValid && !IsSecTableValid) {
1960 reportUniqueWarning("no valid dynamic table was found");
1961 return;
1962 }
1963
1964 // Information in the PT_DYNAMIC program header has priority over the
1965 // information in a section header.
1966 if (IsPhdrTableValid) {
1967 if (!IsSecTableValid)
1968 reportUniqueWarning(
1969 "SHT_DYNAMIC dynamic table is invalid: PT_DYNAMIC will be used");
1970 DynamicTable = std::move(FromPhdr);
1971 } else {
1972 reportUniqueWarning(
1973 "PT_DYNAMIC dynamic table is invalid: SHT_DYNAMIC will be used");
1974 DynamicTable = std::move(FromSec);
1975 }
1976
1977 parseDynamicTable();
1978}
1979
1980template <typename ELFT>
1981ELFDumper<ELFT>::ELFDumper(const object::ELFObjectFile<ELFT> &O,
1982 ScopedPrinter &Writer)
1983 : ObjDumper(Writer, O.getFileName()), ObjF(O), Obj(O.getELFFile()),
1984 FileName(O.getFileName()), DynRelRegion(O, *this),
1985 DynRelaRegion(O, *this), DynCrelRegion(O, *this), DynRelrRegion(O, *this),
1986 DynPLTRelRegion(O, *this), DynSymTabShndxRegion(O, *this),
1987 DynamicTable(O, *this) {
1988 if (!O.IsContentValid())
1989 return;
1990
1991 typename ELFT::ShdrRange Sections = cantFail(Obj.sections());
1992 for (const Elf_Shdr &Sec : Sections) {
1993 switch (Sec.sh_type) {
1994 case ELF::SHT_SYMTAB:
1995 if (!DotSymtabSec)
1996 DotSymtabSec = &Sec;
1997 break;
1998 case ELF::SHT_DYNSYM:
1999 if (!DotDynsymSec)
2000 DotDynsymSec = &Sec;
2001
2002 if (!DynSymRegion) {
2003 Expected<DynRegionInfo> RegOrErr =
2004 createDRI(Offset: Sec.sh_offset, Size: Sec.sh_size, EntSize: Sec.sh_entsize);
2005 if (RegOrErr) {
2006 DynSymRegion = *RegOrErr;
2007 DynSymRegion->Context = describe(Sec);
2008
2009 if (Expected<StringRef> E = Obj.getStringTableForSymtab(Sec))
2010 DynamicStringTable = *E;
2011 else
2012 reportUniqueWarning("unable to get the string table for the " +
2013 describe(Sec) + ": " + toString(E: E.takeError()));
2014 } else {
2015 reportUniqueWarning("unable to read dynamic symbols from " +
2016 describe(Sec) + ": " +
2017 toString(E: RegOrErr.takeError()));
2018 }
2019 }
2020 break;
2021 case ELF::SHT_SYMTAB_SHNDX: {
2022 uint32_t SymtabNdx = Sec.sh_link;
2023 if (SymtabNdx >= Sections.size()) {
2024 reportUniqueWarning(
2025 "unable to get the associated symbol table for " + describe(Sec) +
2026 ": sh_link (" + Twine(SymtabNdx) +
2027 ") is greater than or equal to the total number of sections (" +
2028 Twine(Sections.size()) + ")");
2029 continue;
2030 }
2031
2032 if (Expected<ArrayRef<Elf_Word>> ShndxTableOrErr =
2033 Obj.getSHNDXTable(Sec)) {
2034 if (!ShndxTables.insert({&Sections[SymtabNdx], *ShndxTableOrErr})
2035 .second)
2036 reportUniqueWarning(
2037 "multiple SHT_SYMTAB_SHNDX sections are linked to " +
2038 describe(Sec));
2039 } else {
2040 reportUniqueWarning(ShndxTableOrErr.takeError());
2041 }
2042 break;
2043 }
2044 case ELF::SHT_GNU_versym:
2045 if (!SymbolVersionSection)
2046 SymbolVersionSection = &Sec;
2047 break;
2048 case ELF::SHT_GNU_verdef:
2049 if (!SymbolVersionDefSection)
2050 SymbolVersionDefSection = &Sec;
2051 break;
2052 case ELF::SHT_GNU_verneed:
2053 if (!SymbolVersionNeedSection)
2054 SymbolVersionNeedSection = &Sec;
2055 break;
2056 case ELF::SHT_LLVM_ADDRSIG:
2057 if (!DotAddrsigSec)
2058 DotAddrsigSec = &Sec;
2059 break;
2060 }
2061 }
2062
2063 loadDynamicTable();
2064}
2065
2066template <typename ELFT> void ELFDumper<ELFT>::parseDynamicTable() {
2067 auto toMappedAddr = [&](uint64_t Tag, uint64_t VAddr) -> const uint8_t * {
2068 auto MappedAddrOrError = Obj.toMappedAddr(VAddr, [&](const Twine &Msg) {
2069 this->reportUniqueWarning(Msg);
2070 return Error::success();
2071 });
2072 if (!MappedAddrOrError) {
2073 this->reportUniqueWarning("unable to parse DT_" +
2074 Obj.getDynamicTagAsString(Tag) + ": " +
2075 llvm::toString(MappedAddrOrError.takeError()));
2076 return nullptr;
2077 }
2078 return MappedAddrOrError.get();
2079 };
2080
2081 const char *StringTableBegin = nullptr;
2082 uint64_t StringTableSize = 0;
2083 std::optional<DynRegionInfo> DynSymFromTable;
2084 for (const Elf_Dyn &Dyn : dynamic_table()) {
2085 if (Obj.getHeader().e_machine == EM_AARCH64) {
2086 switch (Dyn.d_tag) {
2087 case ELF::DT_AARCH64_AUTH_RELRSZ:
2088 DynRelrRegion.Size = Dyn.getVal();
2089 DynRelrRegion.SizePrintName = "DT_AARCH64_AUTH_RELRSZ value";
2090 continue;
2091 case ELF::DT_AARCH64_AUTH_RELRENT:
2092 DynRelrRegion.EntSize = Dyn.getVal();
2093 DynRelrRegion.EntSizePrintName = "DT_AARCH64_AUTH_RELRENT value";
2094 continue;
2095 }
2096 }
2097 switch (Dyn.d_tag) {
2098 case ELF::DT_HASH:
2099 HashTable = reinterpret_cast<const Elf_Hash *>(
2100 toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
2101 break;
2102 case ELF::DT_GNU_HASH:
2103 GnuHashTable = reinterpret_cast<const Elf_GnuHash *>(
2104 toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
2105 break;
2106 case ELF::DT_STRTAB:
2107 StringTableBegin = reinterpret_cast<const char *>(
2108 toMappedAddr(Dyn.getTag(), Dyn.getPtr()));
2109 break;
2110 case ELF::DT_STRSZ:
2111 StringTableSize = Dyn.getVal();
2112 break;
2113 case ELF::DT_SYMTAB: {
2114 // If we can't map the DT_SYMTAB value to an address (e.g. when there are
2115 // no program headers), we ignore its value.
2116 if (const uint8_t *VA = toMappedAddr(Dyn.getTag(), Dyn.getPtr())) {
2117 DynSymFromTable.emplace(ObjF, *this);
2118 DynSymFromTable->Addr = VA;
2119 DynSymFromTable->EntSize = sizeof(Elf_Sym);
2120 DynSymFromTable->EntSizePrintName = "";
2121 }
2122 break;
2123 }
2124 case ELF::DT_SYMENT: {
2125 uint64_t Val = Dyn.getVal();
2126 if (Val != sizeof(Elf_Sym))
2127 this->reportUniqueWarning("DT_SYMENT value of 0x" +
2128 Twine::utohexstr(Val) +
2129 " is not the size of a symbol (0x" +
2130 Twine::utohexstr(Val: sizeof(Elf_Sym)) + ")");
2131 break;
2132 }
2133 case ELF::DT_RELA:
2134 DynRelaRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2135 break;
2136 case ELF::DT_RELASZ:
2137 DynRelaRegion.Size = Dyn.getVal();
2138 DynRelaRegion.SizePrintName = "DT_RELASZ value";
2139 break;
2140 case ELF::DT_RELAENT:
2141 DynRelaRegion.EntSize = Dyn.getVal();
2142 DynRelaRegion.EntSizePrintName = "DT_RELAENT value";
2143 break;
2144 case ELF::DT_CREL:
2145 DynCrelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2146 break;
2147 case ELF::DT_SONAME:
2148 SONameOffset = Dyn.getVal();
2149 break;
2150 case ELF::DT_REL:
2151 DynRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2152 break;
2153 case ELF::DT_RELSZ:
2154 DynRelRegion.Size = Dyn.getVal();
2155 DynRelRegion.SizePrintName = "DT_RELSZ value";
2156 break;
2157 case ELF::DT_RELENT:
2158 DynRelRegion.EntSize = Dyn.getVal();
2159 DynRelRegion.EntSizePrintName = "DT_RELENT value";
2160 break;
2161 case ELF::DT_RELR:
2162 case ELF::DT_ANDROID_RELR:
2163 case ELF::DT_AARCH64_AUTH_RELR:
2164 DynRelrRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2165 break;
2166 case ELF::DT_RELRSZ:
2167 case ELF::DT_ANDROID_RELRSZ:
2168 case ELF::DT_AARCH64_AUTH_RELRSZ:
2169 DynRelrRegion.Size = Dyn.getVal();
2170 DynRelrRegion.SizePrintName = Dyn.d_tag == ELF::DT_RELRSZ
2171 ? "DT_RELRSZ value"
2172 : "DT_ANDROID_RELRSZ value";
2173 break;
2174 case ELF::DT_RELRENT:
2175 case ELF::DT_ANDROID_RELRENT:
2176 case ELF::DT_AARCH64_AUTH_RELRENT:
2177 DynRelrRegion.EntSize = Dyn.getVal();
2178 DynRelrRegion.EntSizePrintName = Dyn.d_tag == ELF::DT_RELRENT
2179 ? "DT_RELRENT value"
2180 : "DT_ANDROID_RELRENT value";
2181 break;
2182 case ELF::DT_PLTREL:
2183 if (Dyn.getVal() == DT_REL)
2184 DynPLTRelRegion.EntSize = sizeof(Elf_Rel);
2185 else if (Dyn.getVal() == DT_RELA)
2186 DynPLTRelRegion.EntSize = sizeof(Elf_Rela);
2187 else if (Dyn.getVal() == DT_CREL)
2188 DynPLTRelRegion.EntSize = 1;
2189 else
2190 reportUniqueWarning(Twine("unknown DT_PLTREL value of ") +
2191 Twine((uint64_t)Dyn.getVal()));
2192 DynPLTRelRegion.EntSizePrintName = "PLTREL entry size";
2193 break;
2194 case ELF::DT_JMPREL:
2195 DynPLTRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2196 break;
2197 case ELF::DT_PLTRELSZ:
2198 DynPLTRelRegion.Size = Dyn.getVal();
2199 DynPLTRelRegion.SizePrintName = "DT_PLTRELSZ value";
2200 break;
2201 case ELF::DT_SYMTAB_SHNDX:
2202 DynSymTabShndxRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr());
2203 DynSymTabShndxRegion.EntSize = sizeof(Elf_Word);
2204 break;
2205 }
2206 }
2207
2208 if (StringTableBegin) {
2209 const uint64_t FileSize = Obj.getBufSize();
2210 const uint64_t Offset = (const uint8_t *)StringTableBegin - Obj.base();
2211 if (StringTableSize > FileSize - Offset)
2212 reportUniqueWarning(
2213 "the dynamic string table at 0x" + Twine::utohexstr(Val: Offset) +
2214 " goes past the end of the file (0x" + Twine::utohexstr(Val: FileSize) +
2215 ") with DT_STRSZ = 0x" + Twine::utohexstr(Val: StringTableSize));
2216 else
2217 DynamicStringTable = StringRef(StringTableBegin, StringTableSize);
2218 }
2219
2220 const bool IsHashTableSupported = getHashTableEntSize() == 4;
2221 if (DynSymRegion) {
2222 // Often we find the information about the dynamic symbol table
2223 // location in the SHT_DYNSYM section header. However, the value in
2224 // DT_SYMTAB has priority, because it is used by dynamic loaders to
2225 // locate .dynsym at runtime. The location we find in the section header
2226 // and the location we find here should match.
2227 if (DynSymFromTable && DynSymFromTable->Addr != DynSymRegion->Addr)
2228 reportUniqueWarning(
2229 createError(Err: "SHT_DYNSYM section header and DT_SYMTAB disagree about "
2230 "the location of the dynamic symbol table"));
2231
2232 // According to the ELF gABI: "The number of symbol table entries should
2233 // equal nchain". Check to see if the DT_HASH hash table nchain value
2234 // conflicts with the number of symbols in the dynamic symbol table
2235 // according to the section header.
2236 if (HashTable && IsHashTableSupported) {
2237 if (DynSymRegion->EntSize == 0)
2238 reportUniqueWarning("SHT_DYNSYM section has sh_entsize == 0");
2239 else if (HashTable->nchain != DynSymRegion->Size / DynSymRegion->EntSize)
2240 reportUniqueWarning(
2241 "hash table nchain (" + Twine(HashTable->nchain) +
2242 ") differs from symbol count derived from SHT_DYNSYM section "
2243 "header (" +
2244 Twine(DynSymRegion->Size / DynSymRegion->EntSize) + ")");
2245 }
2246 }
2247
2248 // Delay the creation of the actual dynamic symbol table until now, so that
2249 // checks can always be made against the section header-based properties,
2250 // without worrying about tag order.
2251 if (DynSymFromTable) {
2252 if (!DynSymRegion) {
2253 DynSymRegion = std::move(DynSymFromTable);
2254 } else {
2255 DynSymRegion->Addr = DynSymFromTable->Addr;
2256 DynSymRegion->EntSize = DynSymFromTable->EntSize;
2257 DynSymRegion->EntSizePrintName = DynSymFromTable->EntSizePrintName;
2258 }
2259 }
2260
2261 // Derive the dynamic symbol table size from the DT_HASH hash table, if
2262 // present.
2263 if (HashTable && IsHashTableSupported && DynSymRegion) {
2264 const uint64_t FileSize = Obj.getBufSize();
2265 const uint64_t DerivedSize =
2266 (uint64_t)HashTable->nchain * DynSymRegion->EntSize;
2267 const uint64_t Offset = DynSymRegion->Addr - Obj.base();
2268 if (DerivedSize > FileSize - Offset)
2269 reportUniqueWarning(
2270 "the size (0x" + Twine::utohexstr(Val: DerivedSize) +
2271 ") of the dynamic symbol table at 0x" + Twine::utohexstr(Val: Offset) +
2272 ", derived from the hash table, goes past the end of the file (0x" +
2273 Twine::utohexstr(Val: FileSize) + ") and will be ignored");
2274 else
2275 DynSymRegion->Size = HashTable->nchain * DynSymRegion->EntSize;
2276 }
2277}
2278
2279template <typename ELFT> void ELFDumper<ELFT>::printVersionInfo() {
2280 // Dump version symbol section.
2281 printVersionSymbolSection(Sec: SymbolVersionSection);
2282
2283 // Dump version definition section.
2284 printVersionDefinitionSection(Sec: SymbolVersionDefSection);
2285
2286 // Dump version dependency section.
2287 printVersionDependencySection(Sec: SymbolVersionNeedSection);
2288}
2289
2290#define LLVM_READOBJ_DT_FLAG_ENT(prefix, enum) {{#enum}, prefix##_##enum}
2291
2292constexpr EnumStringDef<unsigned> ElfDynamicDTFlagsDefs[] = {
2293 LLVM_READOBJ_DT_FLAG_ENT(DF, ORIGIN),
2294 LLVM_READOBJ_DT_FLAG_ENT(DF, SYMBOLIC),
2295 LLVM_READOBJ_DT_FLAG_ENT(DF, TEXTREL),
2296 LLVM_READOBJ_DT_FLAG_ENT(DF, BIND_NOW),
2297 LLVM_READOBJ_DT_FLAG_ENT(DF, STATIC_TLS),
2298};
2299constexpr auto ElfDynamicDTFlags = BUILD_ENUM_STRINGS(ElfDynamicDTFlagsDefs);
2300
2301constexpr EnumStringDef<unsigned> ElfDynamicDTFlags1Defs[] = {
2302 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOW),
2303 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAL),
2304 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GROUP),
2305 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODELETE),
2306 LLVM_READOBJ_DT_FLAG_ENT(DF_1, LOADFLTR),
2307 LLVM_READOBJ_DT_FLAG_ENT(DF_1, INITFIRST),
2308 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOOPEN),
2309 LLVM_READOBJ_DT_FLAG_ENT(DF_1, ORIGIN),
2310 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DIRECT),
2311 LLVM_READOBJ_DT_FLAG_ENT(DF_1, TRANS),
2312 LLVM_READOBJ_DT_FLAG_ENT(DF_1, INTERPOSE),
2313 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODEFLIB),
2314 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODUMP),
2315 LLVM_READOBJ_DT_FLAG_ENT(DF_1, CONFALT),
2316 LLVM_READOBJ_DT_FLAG_ENT(DF_1, ENDFILTEE),
2317 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELDNE),
2318 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELPND),
2319 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODIRECT),
2320 LLVM_READOBJ_DT_FLAG_ENT(DF_1, IGNMULDEF),
2321 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOKSYMS),
2322 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOHDR),
2323 LLVM_READOBJ_DT_FLAG_ENT(DF_1, EDITED),
2324 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NORELOC),
2325 LLVM_READOBJ_DT_FLAG_ENT(DF_1, SYMINTPOSE),
2326 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAUDIT),
2327 LLVM_READOBJ_DT_FLAG_ENT(DF_1, SINGLETON),
2328 LLVM_READOBJ_DT_FLAG_ENT(DF_1, PIE),
2329};
2330constexpr auto ElfDynamicDTFlags1 = BUILD_ENUM_STRINGS(ElfDynamicDTFlags1Defs);
2331
2332constexpr EnumStringDef<unsigned> ElfDynamicDTMipsFlagsDefs[] = {
2333 LLVM_READOBJ_DT_FLAG_ENT(RHF, NONE),
2334 LLVM_READOBJ_DT_FLAG_ENT(RHF, QUICKSTART),
2335 LLVM_READOBJ_DT_FLAG_ENT(RHF, NOTPOT),
2336 LLVM_READOBJ_DT_FLAG_ENT(RHS, NO_LIBRARY_REPLACEMENT),
2337 LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_MOVE),
2338 LLVM_READOBJ_DT_FLAG_ENT(RHF, SGI_ONLY),
2339 LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_INIT),
2340 LLVM_READOBJ_DT_FLAG_ENT(RHF, DELTA_C_PLUS_PLUS),
2341 LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_START_INIT),
2342 LLVM_READOBJ_DT_FLAG_ENT(RHF, PIXIE),
2343 LLVM_READOBJ_DT_FLAG_ENT(RHF, DEFAULT_DELAY_LOAD),
2344 LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTART),
2345 LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTARTED),
2346 LLVM_READOBJ_DT_FLAG_ENT(RHF, CORD),
2347 LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_UNRES_UNDEF),
2348 LLVM_READOBJ_DT_FLAG_ENT(RHF, RLD_ORDER_SAFE),
2349};
2350constexpr auto ElfDynamicDTMipsFlags =
2351 BUILD_ENUM_STRINGS(ElfDynamicDTMipsFlagsDefs);
2352
2353#undef LLVM_READOBJ_DT_FLAG_ENT
2354
2355template <typename T, typename TFlag, unsigned NumStrs>
2356void printFlags(T Value, EnumStrings<TFlag, NumStrs> Flags, raw_ostream &OS) {
2357 for (const auto &Flag : Flags)
2358 if (Flag.value() != 0 && (Value & Flag.value()) == Flag.value())
2359 OS << Flag.name() << " ";
2360}
2361
2362template <class ELFT>
2363const typename ELFT::Shdr *
2364ELFDumper<ELFT>::findSectionByName(StringRef Name) const {
2365 for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
2366 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Shdr)) {
2367 if (*NameOrErr == Name)
2368 return &Shdr;
2369 } else {
2370 reportUniqueWarning("unable to read the name of " + describe(Sec: Shdr) +
2371 ": " + toString(E: NameOrErr.takeError()));
2372 }
2373 }
2374 return nullptr;
2375}
2376
2377template <class ELFT>
2378std::string ELFDumper<ELFT>::getDynamicEntry(uint64_t Type,
2379 uint64_t Value) const {
2380 auto FormatHexValue = [](uint64_t V) {
2381 std::string Str;
2382 raw_string_ostream OS(Str);
2383 const char *ConvChar =
2384 (opts::Output == opts::GNU) ? "0x%" PRIx64 : "0x%" PRIX64;
2385 OS << format(Fmt: ConvChar, Vals: V);
2386 return Str;
2387 };
2388
2389 auto FormatFlags = [](uint64_t V, EnumStrings<unsigned int> Array) {
2390 std::string Str;
2391 raw_string_ostream OS(Str);
2392 printFlags(Value: V, Flags: Array, OS);
2393 return Str;
2394 };
2395
2396 // Handle custom printing of architecture specific tags
2397 switch (Obj.getHeader().e_machine) {
2398 case EM_AARCH64:
2399 switch (Type) {
2400 case DT_AARCH64_BTI_PLT:
2401 case DT_AARCH64_PAC_PLT:
2402 case DT_AARCH64_VARIANT_PCS:
2403 case DT_AARCH64_MEMTAG_GLOBALSSZ:
2404 return std::to_string(val: Value);
2405 case DT_AARCH64_MEMTAG_MODE:
2406 switch (Value) {
2407 case 0:
2408 return "Synchronous (0)";
2409 case 1:
2410 return "Asynchronous (1)";
2411 default:
2412 return (Twine("Unknown (") + Twine(Value) + ")").str();
2413 }
2414 case DT_AARCH64_MEMTAG_HEAP:
2415 case DT_AARCH64_MEMTAG_STACK:
2416 switch (Value) {
2417 case 0:
2418 return "Disabled (0)";
2419 case 1:
2420 return "Enabled (1)";
2421 default:
2422 return (Twine("Unknown (") + Twine(Value) + ")").str();
2423 }
2424 case DT_AARCH64_MEMTAG_GLOBALS:
2425 return (Twine("0x") + utohexstr(X: Value, /*LowerCase=*/true)).str();
2426 default:
2427 break;
2428 }
2429 break;
2430 case EM_HEXAGON:
2431 switch (Type) {
2432 case DT_HEXAGON_VER:
2433 return std::to_string(val: Value);
2434 case DT_HEXAGON_SYMSZ:
2435 case DT_HEXAGON_PLT:
2436 return FormatHexValue(Value);
2437 default:
2438 break;
2439 }
2440 break;
2441 case EM_MIPS:
2442 switch (Type) {
2443 case DT_MIPS_RLD_VERSION:
2444 case DT_MIPS_LOCAL_GOTNO:
2445 case DT_MIPS_SYMTABNO:
2446 case DT_MIPS_UNREFEXTNO:
2447 return std::to_string(val: Value);
2448 case DT_MIPS_TIME_STAMP:
2449 case DT_MIPS_ICHECKSUM:
2450 case DT_MIPS_IVERSION:
2451 case DT_MIPS_BASE_ADDRESS:
2452 case DT_MIPS_MSYM:
2453 case DT_MIPS_CONFLICT:
2454 case DT_MIPS_LIBLIST:
2455 case DT_MIPS_CONFLICTNO:
2456 case DT_MIPS_LIBLISTNO:
2457 case DT_MIPS_GOTSYM:
2458 case DT_MIPS_HIPAGENO:
2459 case DT_MIPS_RLD_MAP:
2460 case DT_MIPS_DELTA_CLASS:
2461 case DT_MIPS_DELTA_CLASS_NO:
2462 case DT_MIPS_DELTA_INSTANCE:
2463 case DT_MIPS_DELTA_RELOC:
2464 case DT_MIPS_DELTA_RELOC_NO:
2465 case DT_MIPS_DELTA_SYM:
2466 case DT_MIPS_DELTA_SYM_NO:
2467 case DT_MIPS_DELTA_CLASSSYM:
2468 case DT_MIPS_DELTA_CLASSSYM_NO:
2469 case DT_MIPS_CXX_FLAGS:
2470 case DT_MIPS_PIXIE_INIT:
2471 case DT_MIPS_SYMBOL_LIB:
2472 case DT_MIPS_LOCALPAGE_GOTIDX:
2473 case DT_MIPS_LOCAL_GOTIDX:
2474 case DT_MIPS_HIDDEN_GOTIDX:
2475 case DT_MIPS_PROTECTED_GOTIDX:
2476 case DT_MIPS_OPTIONS:
2477 case DT_MIPS_INTERFACE:
2478 case DT_MIPS_DYNSTR_ALIGN:
2479 case DT_MIPS_INTERFACE_SIZE:
2480 case DT_MIPS_RLD_TEXT_RESOLVE_ADDR:
2481 case DT_MIPS_PERF_SUFFIX:
2482 case DT_MIPS_COMPACT_SIZE:
2483 case DT_MIPS_GP_VALUE:
2484 case DT_MIPS_AUX_DYNAMIC:
2485 case DT_MIPS_PLTGOT:
2486 case DT_MIPS_RWPLT:
2487 case DT_MIPS_RLD_MAP_REL:
2488 case DT_MIPS_XHASH:
2489 return FormatHexValue(Value);
2490 case DT_MIPS_FLAGS:
2491 return FormatFlags(Value, ElfDynamicDTMipsFlags);
2492 default:
2493 break;
2494 }
2495 break;
2496 default:
2497 break;
2498 }
2499
2500 switch (Type) {
2501 case DT_PLTREL:
2502 if (Value == DT_REL)
2503 return "REL";
2504 if (Value == DT_RELA)
2505 return "RELA";
2506 if (Value == DT_CREL)
2507 return "CREL";
2508 [[fallthrough]];
2509 case DT_PLTGOT:
2510 case DT_HASH:
2511 case DT_STRTAB:
2512 case DT_SYMTAB:
2513 case DT_RELA:
2514 case DT_INIT:
2515 case DT_FINI:
2516 case DT_REL:
2517 case DT_JMPREL:
2518 case DT_INIT_ARRAY:
2519 case DT_FINI_ARRAY:
2520 case DT_PREINIT_ARRAY:
2521 case DT_DEBUG:
2522 case DT_CREL:
2523 case DT_VERDEF:
2524 case DT_VERNEED:
2525 case DT_VERSYM:
2526 case DT_GNU_HASH:
2527 case DT_NULL:
2528 return FormatHexValue(Value);
2529 case DT_RELACOUNT:
2530 case DT_RELCOUNT:
2531 case DT_VERDEFNUM:
2532 case DT_VERNEEDNUM:
2533 return std::to_string(val: Value);
2534 case DT_PLTRELSZ:
2535 case DT_RELASZ:
2536 case DT_RELAENT:
2537 case DT_STRSZ:
2538 case DT_SYMENT:
2539 case DT_RELSZ:
2540 case DT_RELENT:
2541 case DT_INIT_ARRAYSZ:
2542 case DT_FINI_ARRAYSZ:
2543 case DT_PREINIT_ARRAYSZ:
2544 case DT_RELRSZ:
2545 case DT_RELRENT:
2546 case DT_AARCH64_AUTH_RELRSZ:
2547 case DT_AARCH64_AUTH_RELRENT:
2548 case DT_ANDROID_RELSZ:
2549 case DT_ANDROID_RELASZ:
2550 return std::to_string(val: Value) + " (bytes)";
2551 case DT_NEEDED:
2552 case DT_SONAME:
2553 case DT_AUXILIARY:
2554 case DT_USED:
2555 case DT_FILTER:
2556 case DT_RPATH:
2557 case DT_RUNPATH: {
2558 const std::map<uint64_t, const char *> TagNames = {
2559 {DT_NEEDED, "Shared library"}, {DT_SONAME, "Library soname"},
2560 {DT_AUXILIARY, "Auxiliary library"}, {DT_USED, "Not needed object"},
2561 {DT_FILTER, "Filter library"}, {DT_RPATH, "Library rpath"},
2562 {DT_RUNPATH, "Library runpath"},
2563 };
2564
2565 return (Twine(TagNames.at(k: Type)) + ": [" + getDynamicString(Value) + "]")
2566 .str();
2567 }
2568 case DT_FLAGS:
2569 return FormatFlags(Value, ElfDynamicDTFlags);
2570 case DT_FLAGS_1:
2571 return FormatFlags(Value, ElfDynamicDTFlags1);
2572 default:
2573 return FormatHexValue(Value);
2574 }
2575}
2576
2577template <class ELFT>
2578StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const {
2579 if (DynamicStringTable.empty() && !DynamicStringTable.data()) {
2580 reportUniqueWarning("string table was not found");
2581 return "<?>";
2582 }
2583
2584 auto WarnAndReturn = [this](const Twine &Msg, uint64_t Offset) {
2585 reportUniqueWarning("string table at offset 0x" + Twine::utohexstr(Val: Offset) +
2586 Msg);
2587 return "<?>";
2588 };
2589
2590 const uint64_t FileSize = Obj.getBufSize();
2591 const uint64_t Offset =
2592 (const uint8_t *)DynamicStringTable.data() - Obj.base();
2593 if (DynamicStringTable.size() > FileSize - Offset)
2594 return WarnAndReturn(" with size 0x" +
2595 Twine::utohexstr(Val: DynamicStringTable.size()) +
2596 " goes past the end of the file (0x" +
2597 Twine::utohexstr(Val: FileSize) + ")",
2598 Offset);
2599
2600 if (Value >= DynamicStringTable.size())
2601 return WarnAndReturn(
2602 ": unable to read the string at 0x" + Twine::utohexstr(Val: Offset + Value) +
2603 ": it goes past the end of the table (0x" +
2604 Twine::utohexstr(Val: Offset + DynamicStringTable.size()) + ")",
2605 Offset);
2606
2607 if (DynamicStringTable.back() != '\0')
2608 return WarnAndReturn(": unable to read the string at 0x" +
2609 Twine::utohexstr(Val: Offset + Value) +
2610 ": the string table is not null-terminated",
2611 Offset);
2612
2613 return DynamicStringTable.data() + Value;
2614}
2615
2616template <class ELFT> void ELFDumper<ELFT>::printUnwindInfo() {
2617 DwarfCFIEH::PrinterContext<ELFT> Ctx(W, ObjF);
2618 Ctx.printUnwindInformation();
2619}
2620
2621// The namespace is needed to fix the compilation with GCC older than 7.0+.
2622namespace {
2623template <> void ELFDumper<ELF32LE>::printUnwindInfo() {
2624 if (Obj.getHeader().e_machine == EM_ARM) {
2625 ARM::EHABI::PrinterContext<ELF32LE> Ctx(W, Obj, ObjF.getFileName(),
2626 DotSymtabSec);
2627 Ctx.PrintUnwindInformation();
2628 }
2629 DwarfCFIEH::PrinterContext<ELF32LE> Ctx(W, ObjF);
2630 Ctx.printUnwindInformation();
2631}
2632} // namespace
2633
2634template <class ELFT> void ELFDumper<ELFT>::printNeededLibraries() {
2635 ListScope D(W, "NeededLibraries");
2636
2637 std::vector<StringRef> Libs;
2638 for (const auto &Entry : dynamic_table())
2639 if (Entry.d_tag == ELF::DT_NEEDED)
2640 Libs.push_back(getDynamicString(Value: Entry.d_un.d_val));
2641
2642 llvm::sort(C&: Libs);
2643
2644 for (StringRef L : Libs)
2645 W.printString(L);
2646}
2647
2648template <class ELFT>
2649static Error checkHashTable(const ELFDumper<ELFT> &Dumper,
2650 const typename ELFT::Hash *H,
2651 bool *IsHeaderValid = nullptr) {
2652 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
2653 const uint64_t SecOffset = (const uint8_t *)H - Obj.base();
2654 if (Dumper.getHashTableEntSize() == 8) {
2655 StringRef Machine =
2656 EnumStrings(ElfMachineType).toString(Obj.getHeader().e_machine, 1);
2657 if (IsHeaderValid)
2658 *IsHeaderValid = false;
2659 return createError(Err: "the hash table at 0x" + Twine::utohexstr(Val: SecOffset) +
2660 " is not supported: it contains non-standard 8 "
2661 "byte entries on " +
2662 Machine + " platform");
2663 }
2664
2665 auto MakeError = [&](const Twine &Msg = "") {
2666 return createError("the hash table at offset 0x" +
2667 Twine::utohexstr(Val: SecOffset) +
2668 " goes past the end of the file (0x" +
2669 Twine::utohexstr(Val: Obj.getBufSize()) + ")" + Msg);
2670 };
2671
2672 // Each SHT_HASH section starts from two 32-bit fields: nbucket and nchain.
2673 const unsigned HeaderSize = 2 * sizeof(typename ELFT::Word);
2674
2675 if (IsHeaderValid)
2676 *IsHeaderValid = Obj.getBufSize() - SecOffset >= HeaderSize;
2677
2678 if (Obj.getBufSize() - SecOffset < HeaderSize)
2679 return MakeError();
2680
2681 if (Obj.getBufSize() - SecOffset - HeaderSize <
2682 ((uint64_t)H->nbucket + H->nchain) * sizeof(typename ELFT::Word))
2683 return MakeError(", nbucket = " + Twine(H->nbucket) +
2684 ", nchain = " + Twine(H->nchain));
2685 return Error::success();
2686}
2687
2688template <class ELFT>
2689static Error checkGNUHashTable(const ELFFile<ELFT> &Obj,
2690 const typename ELFT::GnuHash *GnuHashTable,
2691 bool *IsHeaderValid = nullptr) {
2692 const uint8_t *TableData = reinterpret_cast<const uint8_t *>(GnuHashTable);
2693 assert(TableData >= Obj.base() && TableData < Obj.base() + Obj.getBufSize() &&
2694 "GnuHashTable must always point to a location inside the file");
2695
2696 uint64_t TableOffset = TableData - Obj.base();
2697 if (IsHeaderValid)
2698 *IsHeaderValid = TableOffset + /*Header size:*/ 16 < Obj.getBufSize();
2699 if (TableOffset + 16 + (uint64_t)GnuHashTable->nbuckets * 4 +
2700 (uint64_t)GnuHashTable->maskwords * sizeof(typename ELFT::Off) >=
2701 Obj.getBufSize())
2702 return createError(Err: "unable to dump the SHT_GNU_HASH "
2703 "section at 0x" +
2704 Twine::utohexstr(Val: TableOffset) +
2705 ": it goes past the end of the file");
2706 return Error::success();
2707}
2708
2709template <typename ELFT> void ELFDumper<ELFT>::printHashTable() {
2710 DictScope D(W, "HashTable");
2711 if (!HashTable)
2712 return;
2713
2714 bool IsHeaderValid;
2715 Error Err = checkHashTable(*this, HashTable, &IsHeaderValid);
2716 if (IsHeaderValid) {
2717 W.printNumber("Num Buckets", HashTable->nbucket);
2718 W.printNumber("Num Chains", HashTable->nchain);
2719 }
2720
2721 if (Err) {
2722 reportUniqueWarning(std::move(Err));
2723 return;
2724 }
2725
2726 W.printList("Buckets", HashTable->buckets());
2727 W.printList("Chains", HashTable->chains());
2728}
2729
2730template <class ELFT>
2731static Expected<ArrayRef<typename ELFT::Word>>
2732getGnuHashTableChains(std::optional<DynRegionInfo> DynSymRegion,
2733 const typename ELFT::GnuHash *GnuHashTable) {
2734 if (!DynSymRegion)
2735 return createError(Err: "no dynamic symbol table found");
2736
2737 ArrayRef<typename ELFT::Sym> DynSymTable =
2738 DynSymRegion->template getAsArrayRef<typename ELFT::Sym>();
2739 size_t NumSyms = DynSymTable.size();
2740 if (!NumSyms)
2741 return createError(Err: "the dynamic symbol table is empty");
2742
2743 if (GnuHashTable->symndx < NumSyms)
2744 return GnuHashTable->values(NumSyms);
2745
2746 // A normal empty GNU hash table section produced by linker might have
2747 // symndx set to the number of dynamic symbols + 1 (for the zero symbol)
2748 // and have dummy null values in the Bloom filter and in the buckets
2749 // vector (or no values at all). It happens because the value of symndx is not
2750 // important for dynamic loaders when the GNU hash table is empty. They just
2751 // skip the whole object during symbol lookup. In such cases, the symndx value
2752 // is irrelevant and we should not report a warning.
2753 ArrayRef<typename ELFT::Word> Buckets = GnuHashTable->buckets();
2754 if (!llvm::all_of(Buckets, [](typename ELFT::Word V) { return V == 0; }))
2755 return createError(
2756 Err: "the first hashed symbol index (" + Twine(GnuHashTable->symndx) +
2757 ") is greater than or equal to the number of dynamic symbols (" +
2758 Twine(NumSyms) + ")");
2759 // There is no way to represent an array of (dynamic symbols count - symndx)
2760 // length.
2761 return ArrayRef<typename ELFT::Word>();
2762}
2763
2764template <typename ELFT>
2765void ELFDumper<ELFT>::printGnuHashTable() {
2766 DictScope D(W, "GnuHashTable");
2767 if (!GnuHashTable)
2768 return;
2769
2770 bool IsHeaderValid;
2771 Error Err = checkGNUHashTable<ELFT>(Obj, GnuHashTable, &IsHeaderValid);
2772 if (IsHeaderValid) {
2773 W.printNumber("Num Buckets", GnuHashTable->nbuckets);
2774 W.printNumber("First Hashed Symbol Index", GnuHashTable->symndx);
2775 W.printNumber("Num Mask Words", GnuHashTable->maskwords);
2776 W.printNumber("Shift Count", GnuHashTable->shift2);
2777 }
2778
2779 if (Err) {
2780 reportUniqueWarning(std::move(Err));
2781 return;
2782 }
2783
2784 ArrayRef<typename ELFT::Off> BloomFilter = GnuHashTable->filter();
2785 W.printHexList("Bloom Filter", BloomFilter);
2786
2787 ArrayRef<Elf_Word> Buckets = GnuHashTable->buckets();
2788 W.printList("Buckets", Buckets);
2789
2790 Expected<ArrayRef<Elf_Word>> Chains =
2791 getGnuHashTableChains<ELFT>(DynSymRegion, GnuHashTable);
2792 if (!Chains) {
2793 reportUniqueWarning("unable to dump 'Values' for the SHT_GNU_HASH "
2794 "section: " +
2795 toString(Chains.takeError()));
2796 return;
2797 }
2798
2799 W.printHexList("Values", *Chains);
2800}
2801
2802template <typename ELFT> void ELFDumper<ELFT>::printHashHistograms() {
2803 // Print histogram for the .hash section.
2804 if (this->HashTable) {
2805 if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
2806 this->reportUniqueWarning(std::move(E));
2807 else
2808 printHashHistogram(HashTable: *this->HashTable);
2809 }
2810
2811 // Print histogram for the .gnu.hash section.
2812 if (this->GnuHashTable) {
2813 if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
2814 this->reportUniqueWarning(std::move(E));
2815 else
2816 printGnuHashHistogram(GnuHashTable: *this->GnuHashTable);
2817 }
2818}
2819
2820template <typename ELFT>
2821void ELFDumper<ELFT>::printHashHistogram(const Elf_Hash &HashTable) const {
2822 size_t NBucket = HashTable.nbucket;
2823 size_t NChain = HashTable.nchain;
2824 ArrayRef<Elf_Word> Buckets = HashTable.buckets();
2825 ArrayRef<Elf_Word> Chains = HashTable.chains();
2826 size_t TotalSyms = 0;
2827 // If hash table is correct, we have at least chains with 0 length.
2828 size_t MaxChain = 1;
2829
2830 if (NChain == 0 || NBucket == 0)
2831 return;
2832
2833 std::vector<size_t> ChainLen(NBucket, 0);
2834 // Go over all buckets and note chain lengths of each bucket (total
2835 // unique chain lengths).
2836 for (size_t B = 0; B < NBucket; ++B) {
2837 BitVector Visited(NChain);
2838 for (size_t C = Buckets[B]; C < NChain; C = Chains[C]) {
2839 if (C == ELF::STN_UNDEF)
2840 break;
2841 if (Visited[C]) {
2842 this->reportUniqueWarning(
2843 ".hash section is invalid: bucket " + Twine(C) +
2844 ": a cycle was detected in the linked chain");
2845 break;
2846 }
2847 Visited[C] = true;
2848 if (MaxChain <= ++ChainLen[B])
2849 ++MaxChain;
2850 }
2851 TotalSyms += ChainLen[B];
2852 }
2853
2854 if (!TotalSyms)
2855 return;
2856
2857 std::vector<size_t> Count(MaxChain, 0);
2858 // Count how long is the chain for each bucket.
2859 for (size_t B = 0; B < NBucket; B++)
2860 ++Count[ChainLen[B]];
2861 // Print Number of buckets with each chain lengths and their cumulative
2862 // coverage of the symbols.
2863 printHashHistogramStats(NBucket, MaxChain, TotalSyms, Count, /*IsGnu=*/false);
2864}
2865
2866template <class ELFT>
2867void ELFDumper<ELFT>::printGnuHashHistogram(
2868 const Elf_GnuHash &GnuHashTable) const {
2869 Expected<ArrayRef<Elf_Word>> ChainsOrErr =
2870 getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHashTable);
2871 if (!ChainsOrErr) {
2872 this->reportUniqueWarning("unable to print the GNU hash table histogram: " +
2873 toString(ChainsOrErr.takeError()));
2874 return;
2875 }
2876
2877 ArrayRef<Elf_Word> Chains = *ChainsOrErr;
2878 size_t Symndx = GnuHashTable.symndx;
2879 size_t TotalSyms = 0;
2880 size_t MaxChain = 1;
2881
2882 size_t NBucket = GnuHashTable.nbuckets;
2883 if (Chains.empty() || NBucket == 0)
2884 return;
2885
2886 ArrayRef<Elf_Word> Buckets = GnuHashTable.buckets();
2887 std::vector<size_t> ChainLen(NBucket, 0);
2888 for (size_t B = 0; B < NBucket; ++B) {
2889 if (!Buckets[B])
2890 continue;
2891 size_t Len = 1;
2892 for (size_t C = Buckets[B] - Symndx;
2893 C < Chains.size() && (Chains[C] & 1) == 0; ++C)
2894 if (MaxChain < ++Len)
2895 ++MaxChain;
2896 ChainLen[B] = Len;
2897 TotalSyms += Len;
2898 }
2899 ++MaxChain;
2900
2901 if (!TotalSyms)
2902 return;
2903
2904 std::vector<size_t> Count(MaxChain, 0);
2905 for (size_t B = 0; B < NBucket; ++B)
2906 ++Count[ChainLen[B]];
2907 // Print Number of buckets with each chain lengths and their cumulative
2908 // coverage of the symbols.
2909 printHashHistogramStats(NBucket, MaxChain, TotalSyms, Count, /*IsGnu=*/true);
2910}
2911
2912template <typename ELFT> void ELFDumper<ELFT>::printLoadName() {
2913 StringRef SOName = "<Not found>";
2914 if (SONameOffset)
2915 SOName = getDynamicString(Value: *SONameOffset);
2916 W.printString("LoadName", SOName);
2917}
2918
2919template <class ELFT> void ELFDumper<ELFT>::printArchSpecificInfo() {
2920 switch (Obj.getHeader().e_machine) {
2921 case EM_HEXAGON:
2922 printAttributes(ELF::SHT_HEXAGON_ATTRIBUTES,
2923 std::make_unique<HexagonAttributeParser>(&W),
2924 llvm::endianness::little);
2925 break;
2926 case EM_ARM:
2927 printAttributes(
2928 ELF::SHT_ARM_ATTRIBUTES, std::make_unique<ARMAttributeParser>(&W),
2929 Obj.isLE() ? llvm::endianness::little : llvm::endianness::big);
2930 break;
2931 case EM_AARCH64:
2932 printAttributes(ELF::SHT_AARCH64_ATTRIBUTES,
2933 std::make_unique<AArch64AttributeParser>(&W),
2934 Obj.isLE() ? llvm::endianness::little
2935 : llvm::endianness::big);
2936 break;
2937 case EM_RISCV:
2938 if (Obj.isLE())
2939 printAttributes(ELF::SHT_RISCV_ATTRIBUTES,
2940 std::make_unique<RISCVAttributeParser>(&W),
2941 llvm::endianness::little);
2942 else
2943 reportUniqueWarning("attribute printing not implemented for big-endian "
2944 "RISC-V objects");
2945 break;
2946 case EM_MSP430:
2947 printAttributes(ELF::SHT_MSP430_ATTRIBUTES,
2948 std::make_unique<MSP430AttributeParser>(&W),
2949 llvm::endianness::little);
2950 break;
2951 case EM_MIPS: {
2952 printMipsABIFlags();
2953 printMipsOptions();
2954 printMipsReginfo();
2955 MipsGOTParser<ELFT> Parser(*this);
2956 if (Error E = Parser.findGOT(dynamic_table(), dynamic_symbols()))
2957 reportUniqueWarning(std::move(E));
2958 else if (!Parser.isGotEmpty())
2959 printMipsGOT(Parser);
2960
2961 if (Error E = Parser.findPLT(dynamic_table()))
2962 reportUniqueWarning(std::move(E));
2963 else if (!Parser.isPltEmpty())
2964 printMipsPLT(Parser);
2965 break;
2966 }
2967 default:
2968 break;
2969 }
2970}
2971
2972template <class ELFT>
2973void ELFDumper<ELFT>::printAttributes(
2974 unsigned AttrShType, std::unique_ptr<ELFAttributeParser> AttrParser,
2975 llvm::endianness Endianness) {
2976 assert((AttrShType != ELF::SHT_NULL) && AttrParser &&
2977 "Incomplete ELF attribute implementation");
2978 DictScope BA(W, "BuildAttributes");
2979 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
2980 if (Sec.sh_type != AttrShType)
2981 continue;
2982
2983 ArrayRef<uint8_t> Contents;
2984 if (Expected<ArrayRef<uint8_t>> ContentOrErr =
2985 Obj.getSectionContents(Sec)) {
2986 Contents = *ContentOrErr;
2987 if (Contents.empty()) {
2988 reportUniqueWarning("the " + describe(Sec) + " is empty");
2989 continue;
2990 }
2991 } else {
2992 reportUniqueWarning("unable to read the content of the " + describe(Sec) +
2993 ": " + toString(E: ContentOrErr.takeError()));
2994 continue;
2995 }
2996
2997 W.printHex("FormatVersion", Contents[0]);
2998
2999 if (Error E = AttrParser->parse(Section: Contents, Endian: Endianness))
3000 reportUniqueWarning("unable to dump attributes from the " +
3001 describe(Sec) + ": " + toString(E: std::move(E)));
3002 }
3003}
3004
3005namespace {
3006
3007template <class ELFT> class MipsGOTParser {
3008public:
3009 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
3010 using Entry = typename ELFT::Addr;
3011 using Entries = ArrayRef<Entry>;
3012
3013 const bool IsStatic;
3014 const ELFFile<ELFT> &Obj;
3015 const ELFDumper<ELFT> &Dumper;
3016
3017 MipsGOTParser(const ELFDumper<ELFT> &D);
3018 Error findGOT(Elf_Dyn_Range DynTable, Elf_Sym_Range DynSyms);
3019 Error findPLT(Elf_Dyn_Range DynTable);
3020
3021 bool isGotEmpty() const { return GotEntries.empty(); }
3022 bool isPltEmpty() const { return PltEntries.empty(); }
3023
3024 uint64_t getGp() const;
3025
3026 const Entry *getGotLazyResolver() const;
3027 const Entry *getGotModulePointer() const;
3028 const Entry *getPltLazyResolver() const;
3029 const Entry *getPltModulePointer() const;
3030
3031 Entries getLocalEntries() const;
3032 Entries getGlobalEntries() const;
3033 Entries getOtherEntries() const;
3034 Entries getPltEntries() const;
3035
3036 uint64_t getGotAddress(const Entry * E) const;
3037 int64_t getGotOffset(const Entry * E) const;
3038 const Elf_Sym *getGotSym(const Entry *E) const;
3039
3040 uint64_t getPltAddress(const Entry * E) const;
3041 const Elf_Sym *getPltSym(const Entry *E) const;
3042
3043 StringRef getPltStrTable() const { return PltStrTable; }
3044 const Elf_Shdr *getPltSymTable() const { return PltSymTable; }
3045
3046private:
3047 const Elf_Shdr *GotSec;
3048 size_t LocalNum;
3049 size_t GlobalNum;
3050
3051 const Elf_Shdr *PltSec;
3052 const Elf_Shdr *PltRelSec;
3053 const Elf_Shdr *PltSymTable;
3054 StringRef FileName;
3055
3056 Elf_Sym_Range GotDynSyms;
3057 StringRef PltStrTable;
3058
3059 Entries GotEntries;
3060 Entries PltEntries;
3061};
3062
3063} // end anonymous namespace
3064
3065template <class ELFT>
3066MipsGOTParser<ELFT>::MipsGOTParser(const ELFDumper<ELFT> &D)
3067 : IsStatic(D.dynamic_table().empty()), Obj(D.getElfObject().getELFFile()),
3068 Dumper(D), GotSec(nullptr), LocalNum(0), GlobalNum(0), PltSec(nullptr),
3069 PltRelSec(nullptr), PltSymTable(nullptr),
3070 FileName(D.getElfObject().getFileName()) {}
3071
3072template <class ELFT>
3073Error MipsGOTParser<ELFT>::findGOT(Elf_Dyn_Range DynTable,
3074 Elf_Sym_Range DynSyms) {
3075 // See "Global Offset Table" in Chapter 5 in the following document
3076 // for detailed GOT description.
3077 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
3078
3079 // Find static GOT secton.
3080 if (IsStatic) {
3081 GotSec = Dumper.findSectionByName(".got");
3082 if (!GotSec)
3083 return Error::success();
3084
3085 ArrayRef<uint8_t> Content =
3086 unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
3087 GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
3088 Content.size() / sizeof(Entry));
3089 LocalNum = GotEntries.size();
3090 return Error::success();
3091 }
3092
3093 // Lookup dynamic table tags which define the GOT layout.
3094 std::optional<uint64_t> DtPltGot;
3095 std::optional<uint64_t> DtLocalGotNum;
3096 std::optional<uint64_t> DtGotSym;
3097 for (const auto &Entry : DynTable) {
3098 switch (Entry.getTag()) {
3099 case ELF::DT_PLTGOT:
3100 DtPltGot = Entry.getVal();
3101 break;
3102 case ELF::DT_MIPS_LOCAL_GOTNO:
3103 DtLocalGotNum = Entry.getVal();
3104 break;
3105 case ELF::DT_MIPS_GOTSYM:
3106 DtGotSym = Entry.getVal();
3107 break;
3108 }
3109 }
3110
3111 if (!DtPltGot && !DtLocalGotNum && !DtGotSym)
3112 return Error::success();
3113
3114 if (!DtPltGot)
3115 return createError(Err: "cannot find PLTGOT dynamic tag");
3116 if (!DtLocalGotNum)
3117 return createError(Err: "cannot find MIPS_LOCAL_GOTNO dynamic tag");
3118 if (!DtGotSym)
3119 return createError(Err: "cannot find MIPS_GOTSYM dynamic tag");
3120
3121 size_t DynSymTotal = DynSyms.size();
3122 if (*DtGotSym > DynSymTotal)
3123 return createError(Err: "DT_MIPS_GOTSYM value (" + Twine(*DtGotSym) +
3124 ") exceeds the number of dynamic symbols (" +
3125 Twine(DynSymTotal) + ")");
3126
3127 GotSec = findNotEmptySectionByAddress(Obj, FileName, *DtPltGot);
3128 if (!GotSec)
3129 return createError(Err: "there is no non-empty GOT section at 0x" +
3130 Twine::utohexstr(Val: *DtPltGot));
3131
3132 LocalNum = *DtLocalGotNum;
3133 GlobalNum = DynSymTotal - *DtGotSym;
3134
3135 ArrayRef<uint8_t> Content =
3136 unwrapOrError(FileName, Obj.getSectionContents(*GotSec));
3137 GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()),
3138 Content.size() / sizeof(Entry));
3139 GotDynSyms = DynSyms.drop_front(*DtGotSym);
3140
3141 return Error::success();
3142}
3143
3144template <class ELFT>
3145Error MipsGOTParser<ELFT>::findPLT(Elf_Dyn_Range DynTable) {
3146 // Lookup dynamic table tags which define the PLT layout.
3147 std::optional<uint64_t> DtMipsPltGot;
3148 std::optional<uint64_t> DtJmpRel;
3149 for (const auto &Entry : DynTable) {
3150 switch (Entry.getTag()) {
3151 case ELF::DT_MIPS_PLTGOT:
3152 DtMipsPltGot = Entry.getVal();
3153 break;
3154 case ELF::DT_JMPREL:
3155 DtJmpRel = Entry.getVal();
3156 break;
3157 }
3158 }
3159
3160 if (!DtMipsPltGot && !DtJmpRel)
3161 return Error::success();
3162
3163 // Find PLT section.
3164 if (!DtMipsPltGot)
3165 return createError(Err: "cannot find MIPS_PLTGOT dynamic tag");
3166 if (!DtJmpRel)
3167 return createError(Err: "cannot find JMPREL dynamic tag");
3168
3169 PltSec = findNotEmptySectionByAddress(Obj, FileName, *DtMipsPltGot);
3170 if (!PltSec)
3171 return createError(Err: "there is no non-empty PLTGOT section at 0x" +
3172 Twine::utohexstr(Val: *DtMipsPltGot));
3173
3174 PltRelSec = findNotEmptySectionByAddress(Obj, FileName, *DtJmpRel);
3175 if (!PltRelSec)
3176 return createError(Err: "there is no non-empty RELPLT section at 0x" +
3177 Twine::utohexstr(Val: *DtJmpRel));
3178
3179 if (Expected<ArrayRef<uint8_t>> PltContentOrErr =
3180 Obj.getSectionContents(*PltSec))
3181 PltEntries =
3182 Entries(reinterpret_cast<const Entry *>(PltContentOrErr->data()),
3183 PltContentOrErr->size() / sizeof(Entry));
3184 else
3185 return createError(Err: "unable to read PLTGOT section content: " +
3186 toString(E: PltContentOrErr.takeError()));
3187
3188 if (Expected<const Elf_Shdr *> PltSymTableOrErr =
3189 Obj.getSection(PltRelSec->sh_link))
3190 PltSymTable = *PltSymTableOrErr;
3191 else
3192 return createError("unable to get a symbol table linked to the " +
3193 describe(Obj, *PltRelSec) + ": " +
3194 toString(PltSymTableOrErr.takeError()));
3195
3196 if (Expected<StringRef> StrTabOrErr =
3197 Obj.getStringTableForSymtab(*PltSymTable))
3198 PltStrTable = *StrTabOrErr;
3199 else
3200 return createError("unable to get a string table for the " +
3201 describe(Obj, *PltSymTable) + ": " +
3202 toString(E: StrTabOrErr.takeError()));
3203
3204 return Error::success();
3205}
3206
3207template <class ELFT> uint64_t MipsGOTParser<ELFT>::getGp() const {
3208 return GotSec->sh_addr + 0x7ff0;
3209}
3210
3211template <class ELFT>
3212const typename MipsGOTParser<ELFT>::Entry *
3213MipsGOTParser<ELFT>::getGotLazyResolver() const {
3214 return LocalNum > 0 ? &GotEntries[0] : nullptr;
3215}
3216
3217template <class ELFT>
3218const typename MipsGOTParser<ELFT>::Entry *
3219MipsGOTParser<ELFT>::getGotModulePointer() const {
3220 if (LocalNum < 2)
3221 return nullptr;
3222 const Entry &E = GotEntries[1];
3223 if ((E >> (sizeof(Entry) * 8 - 1)) == 0)
3224 return nullptr;
3225 return &E;
3226}
3227
3228template <class ELFT>
3229typename MipsGOTParser<ELFT>::Entries
3230MipsGOTParser<ELFT>::getLocalEntries() const {
3231 size_t Skip = getGotModulePointer() ? 2 : 1;
3232 if (LocalNum - Skip <= 0)
3233 return Entries();
3234 return GotEntries.slice(Skip, LocalNum - Skip);
3235}
3236
3237template <class ELFT>
3238typename MipsGOTParser<ELFT>::Entries
3239MipsGOTParser<ELFT>::getGlobalEntries() const {
3240 if (GlobalNum == 0)
3241 return Entries();
3242 return GotEntries.slice(LocalNum, GlobalNum);
3243}
3244
3245template <class ELFT>
3246typename MipsGOTParser<ELFT>::Entries
3247MipsGOTParser<ELFT>::getOtherEntries() const {
3248 size_t OtherNum = GotEntries.size() - LocalNum - GlobalNum;
3249 if (OtherNum == 0)
3250 return Entries();
3251 return GotEntries.slice(LocalNum + GlobalNum, OtherNum);
3252}
3253
3254template <class ELFT>
3255uint64_t MipsGOTParser<ELFT>::getGotAddress(const Entry *E) const {
3256 int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
3257 return GotSec->sh_addr + Offset;
3258}
3259
3260template <class ELFT>
3261int64_t MipsGOTParser<ELFT>::getGotOffset(const Entry *E) const {
3262 int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry);
3263 return Offset - 0x7ff0;
3264}
3265
3266template <class ELFT>
3267const typename MipsGOTParser<ELFT>::Elf_Sym *
3268MipsGOTParser<ELFT>::getGotSym(const Entry *E) const {
3269 int64_t Offset = std::distance(GotEntries.data(), E);
3270 return &GotDynSyms[Offset - LocalNum];
3271}
3272
3273template <class ELFT>
3274const typename MipsGOTParser<ELFT>::Entry *
3275MipsGOTParser<ELFT>::getPltLazyResolver() const {
3276 return PltEntries.empty() ? nullptr : &PltEntries[0];
3277}
3278
3279template <class ELFT>
3280const typename MipsGOTParser<ELFT>::Entry *
3281MipsGOTParser<ELFT>::getPltModulePointer() const {
3282 return PltEntries.size() < 2 ? nullptr : &PltEntries[1];
3283}
3284
3285template <class ELFT>
3286typename MipsGOTParser<ELFT>::Entries
3287MipsGOTParser<ELFT>::getPltEntries() const {
3288 if (PltEntries.size() <= 2)
3289 return Entries();
3290 return PltEntries.slice(2, PltEntries.size() - 2);
3291}
3292
3293template <class ELFT>
3294uint64_t MipsGOTParser<ELFT>::getPltAddress(const Entry *E) const {
3295 int64_t Offset = std::distance(PltEntries.data(), E) * sizeof(Entry);
3296 return PltSec->sh_addr + Offset;
3297}
3298
3299template <class ELFT>
3300const typename MipsGOTParser<ELFT>::Elf_Sym *
3301MipsGOTParser<ELFT>::getPltSym(const Entry *E) const {
3302 int64_t Offset = std::distance(getPltEntries().data(), E);
3303 if (PltRelSec->sh_type == ELF::SHT_REL) {
3304 Elf_Rel_Range Rels = unwrapOrError(FileName, Obj.rels(*PltRelSec));
3305 return unwrapOrError(FileName,
3306 Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
3307 } else {
3308 Elf_Rela_Range Rels = unwrapOrError(FileName, Obj.relas(*PltRelSec));
3309 return unwrapOrError(FileName,
3310 Obj.getRelocationSymbol(Rels[Offset], PltSymTable));
3311 }
3312}
3313
3314// clang-format off
3315constexpr EnumStringDef<unsigned> ElfMipsISAExtTypeDefs[] = {
3316 {.Names: {"None"}, .Value: Mips::AFL_EXT_NONE},
3317 {.Names: {"Broadcom SB-1"}, .Value: Mips::AFL_EXT_SB1},
3318 {.Names: {"Cavium Networks Octeon"}, .Value: Mips::AFL_EXT_OCTEON},
3319 {.Names: {"Cavium Networks Octeon2"}, .Value: Mips::AFL_EXT_OCTEON2},
3320 {.Names: {"Cavium Networks OcteonP"}, .Value: Mips::AFL_EXT_OCTEONP},
3321 {.Names: {"Cavium Networks Octeon3"}, .Value: Mips::AFL_EXT_OCTEON3},
3322 {.Names: {"LSI R4010"}, .Value: Mips::AFL_EXT_4010},
3323 {.Names: {"Loongson 2E"}, .Value: Mips::AFL_EXT_LOONGSON_2E},
3324 {.Names: {"Loongson 2F"}, .Value: Mips::AFL_EXT_LOONGSON_2F},
3325 {.Names: {"Loongson 3A"}, .Value: Mips::AFL_EXT_LOONGSON_3A},
3326 {.Names: {"MIPS R4650"}, .Value: Mips::AFL_EXT_4650},
3327 {.Names: {"MIPS R10000"}, .Value: Mips::AFL_EXT_10000},
3328 {.Names: {"NEC VR4100"}, .Value: Mips::AFL_EXT_4100},
3329 {.Names: {"NEC VR4111/VR4181"}, .Value: Mips::AFL_EXT_4111},
3330 {.Names: {"NEC VR4120"}, .Value: Mips::AFL_EXT_4120},
3331 {.Names: {"NEC VR5400"}, .Value: Mips::AFL_EXT_5400},
3332 {.Names: {"NEC VR5500"}, .Value: Mips::AFL_EXT_5500},
3333 {.Names: {"RMI Xlr"}, .Value: Mips::AFL_EXT_XLR},
3334 {.Names: {"Toshiba R3900"}, .Value: Mips::AFL_EXT_3900},
3335 {.Names: {"Toshiba R5900"}, .Value: Mips::AFL_EXT_5900},
3336};
3337// clang-format on
3338constexpr auto ElfMipsISAExtType = BUILD_ENUM_STRINGS(ElfMipsISAExtTypeDefs);
3339
3340constexpr EnumStringDef<unsigned> ElfMipsASEFlagsDefs[] = {
3341 {.Names: {"DSP"}, .Value: Mips::AFL_ASE_DSP},
3342 {.Names: {"DSPR2"}, .Value: Mips::AFL_ASE_DSPR2},
3343 {.Names: {"Enhanced VA Scheme"}, .Value: Mips::AFL_ASE_EVA},
3344 {.Names: {"MCU"}, .Value: Mips::AFL_ASE_MCU},
3345 {.Names: {"MDMX"}, .Value: Mips::AFL_ASE_MDMX},
3346 {.Names: {"MIPS-3D"}, .Value: Mips::AFL_ASE_MIPS3D},
3347 {.Names: {"MT"}, .Value: Mips::AFL_ASE_MT},
3348 {.Names: {"SmartMIPS"}, .Value: Mips::AFL_ASE_SMARTMIPS},
3349 {.Names: {"VZ"}, .Value: Mips::AFL_ASE_VIRT},
3350 {.Names: {"MSA"}, .Value: Mips::AFL_ASE_MSA},
3351 {.Names: {"MIPS16"}, .Value: Mips::AFL_ASE_MIPS16},
3352 {.Names: {"microMIPS"}, .Value: Mips::AFL_ASE_MICROMIPS},
3353 {.Names: {"XPA"}, .Value: Mips::AFL_ASE_XPA},
3354 {.Names: {"CRC"}, .Value: Mips::AFL_ASE_CRC},
3355 {.Names: {"GINV"}, .Value: Mips::AFL_ASE_GINV},
3356};
3357constexpr auto ElfMipsASEFlags = BUILD_ENUM_STRINGS(ElfMipsASEFlagsDefs);
3358
3359constexpr EnumStringDef<unsigned> ElfMipsFpABITypeDefs[] = {
3360 {.Names: {"Hard or soft float"}, .Value: Mips::Val_GNU_MIPS_ABI_FP_ANY},
3361 {.Names: {"Hard float (double precision)"}, .Value: Mips::Val_GNU_MIPS_ABI_FP_DOUBLE},
3362 {.Names: {"Hard float (single precision)"}, .Value: Mips::Val_GNU_MIPS_ABI_FP_SINGLE},
3363 {.Names: {"Soft float"}, .Value: Mips::Val_GNU_MIPS_ABI_FP_SOFT},
3364 {.Names: {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)"},
3365 .Value: Mips::Val_GNU_MIPS_ABI_FP_OLD_64},
3366 {.Names: {"Hard float (32-bit CPU, Any FPU)"}, .Value: Mips::Val_GNU_MIPS_ABI_FP_XX},
3367 {.Names: {"Hard float (32-bit CPU, 64-bit FPU)"}, .Value: Mips::Val_GNU_MIPS_ABI_FP_64},
3368 {.Names: {"Hard float compat (32-bit CPU, 64-bit FPU)"},
3369 .Value: Mips::Val_GNU_MIPS_ABI_FP_64A}};
3370constexpr auto ElfMipsFpABIType = BUILD_ENUM_STRINGS(ElfMipsFpABITypeDefs);
3371
3372constexpr EnumStringDef<unsigned> ElfMipsFlags1Defs[]{
3373 {.Names: {"ODDSPREG"}, .Value: Mips::AFL_FLAGS1_ODDSPREG},
3374};
3375constexpr auto ElfMipsFlags1 = BUILD_ENUM_STRINGS(ElfMipsFlags1Defs);
3376
3377static int getMipsRegisterSize(uint8_t Flag) {
3378 switch (Flag) {
3379 case Mips::AFL_REG_NONE:
3380 return 0;
3381 case Mips::AFL_REG_32:
3382 return 32;
3383 case Mips::AFL_REG_64:
3384 return 64;
3385 case Mips::AFL_REG_128:
3386 return 128;
3387 default:
3388 return -1;
3389 }
3390}
3391
3392template <class ELFT>
3393static void printMipsReginfoData(ScopedPrinter &W,
3394 const Elf_Mips_RegInfo<ELFT> &Reginfo) {
3395 W.printHex("GP", Reginfo.ri_gp_value);
3396 W.printHex("General Mask", Reginfo.ri_gprmask);
3397 W.printHex("Co-Proc Mask0", Reginfo.ri_cprmask[0]);
3398 W.printHex("Co-Proc Mask1", Reginfo.ri_cprmask[1]);
3399 W.printHex("Co-Proc Mask2", Reginfo.ri_cprmask[2]);
3400 W.printHex("Co-Proc Mask3", Reginfo.ri_cprmask[3]);
3401}
3402
3403template <class ELFT> void ELFDumper<ELFT>::printMipsReginfo() {
3404 const Elf_Shdr *RegInfoSec = findSectionByName(Name: ".reginfo");
3405 if (!RegInfoSec) {
3406 W.startLine() << "There is no .reginfo section in the file.\n";
3407 return;
3408 }
3409
3410 Expected<ArrayRef<uint8_t>> ContentsOrErr =
3411 Obj.getSectionContents(*RegInfoSec);
3412 if (!ContentsOrErr) {
3413 this->reportUniqueWarning(
3414 "unable to read the content of the .reginfo section (" +
3415 describe(Sec: *RegInfoSec) + "): " + toString(E: ContentsOrErr.takeError()));
3416 return;
3417 }
3418
3419 if (ContentsOrErr->size() < sizeof(Elf_Mips_RegInfo<ELFT>)) {
3420 this->reportUniqueWarning("the .reginfo section has an invalid size (0x" +
3421 Twine::utohexstr(Val: ContentsOrErr->size()) + ")");
3422 return;
3423 }
3424
3425 DictScope GS(W, "MIPS RegInfo");
3426 printMipsReginfoData(W, *reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(
3427 ContentsOrErr->data()));
3428}
3429
3430template <class ELFT>
3431static Expected<const Elf_Mips_Options<ELFT> *>
3432readMipsOptions(const uint8_t *SecBegin, ArrayRef<uint8_t> &SecData,
3433 bool &IsSupported) {
3434 if (SecData.size() < sizeof(Elf_Mips_Options<ELFT>))
3435 return createError(Err: "the .MIPS.options section has an invalid size (0x" +
3436 Twine::utohexstr(Val: SecData.size()) + ")");
3437
3438 const Elf_Mips_Options<ELFT> *O =
3439 reinterpret_cast<const Elf_Mips_Options<ELFT> *>(SecData.data());
3440 const uint8_t Size = O->size;
3441 if (Size > SecData.size()) {
3442 const uint64_t Offset = SecData.data() - SecBegin;
3443 const uint64_t SecSize = Offset + SecData.size();
3444 return createError(Err: "a descriptor of size 0x" + Twine::utohexstr(Val: Size) +
3445 " at offset 0x" + Twine::utohexstr(Val: Offset) +
3446 " goes past the end of the .MIPS.options "
3447 "section of size 0x" +
3448 Twine::utohexstr(Val: SecSize));
3449 }
3450
3451 IsSupported = O->kind == ODK_REGINFO;
3452 const size_t ExpectedSize =
3453 sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>);
3454
3455 if (IsSupported)
3456 if (Size < ExpectedSize)
3457 return createError(
3458 Err: "a .MIPS.options entry of kind " +
3459 Twine(getElfMipsOptionsOdkType(O->kind)) +
3460 " has an invalid size (0x" + Twine::utohexstr(Val: Size) +
3461 "), the expected size is 0x" + Twine::utohexstr(Val: ExpectedSize));
3462
3463 SecData = SecData.drop_front(N: Size);
3464 return O;
3465}
3466
3467template <class ELFT> void ELFDumper<ELFT>::printMipsOptions() {
3468 const Elf_Shdr *MipsOpts = findSectionByName(Name: ".MIPS.options");
3469 if (!MipsOpts) {
3470 W.startLine() << "There is no .MIPS.options section in the file.\n";
3471 return;
3472 }
3473
3474 DictScope GS(W, "MIPS Options");
3475
3476 ArrayRef<uint8_t> Data =
3477 unwrapOrError(ObjF.getFileName(), Obj.getSectionContents(*MipsOpts));
3478 const uint8_t *const SecBegin = Data.begin();
3479 while (!Data.empty()) {
3480 bool IsSupported;
3481 Expected<const Elf_Mips_Options<ELFT> *> OptsOrErr =
3482 readMipsOptions<ELFT>(SecBegin, Data, IsSupported);
3483 if (!OptsOrErr) {
3484 reportUniqueWarning(OptsOrErr.takeError());
3485 break;
3486 }
3487
3488 unsigned Kind = (*OptsOrErr)->kind;
3489 const char *Type = getElfMipsOptionsOdkType(Odk: Kind);
3490 if (!IsSupported) {
3491 W.startLine() << "Unsupported MIPS options tag: " << Type << " (" << Kind
3492 << ")\n";
3493 continue;
3494 }
3495
3496 DictScope GS(W, Type);
3497 if (Kind == ODK_REGINFO)
3498 printMipsReginfoData(W, (*OptsOrErr)->getRegInfo());
3499 else
3500 llvm_unreachable("unexpected .MIPS.options section descriptor kind");
3501 }
3502}
3503
3504template <class ELFT> void ELFDumper<ELFT>::printStackMap() const {
3505 const Elf_Shdr *StackMapSection = findSectionByName(Name: ".llvm_stackmaps");
3506 if (!StackMapSection)
3507 return;
3508
3509 auto Warn = [&](Error &&E) {
3510 this->reportUniqueWarning("unable to read the stack map from " +
3511 describe(Sec: *StackMapSection) + ": " +
3512 toString(E: std::move(E)));
3513 };
3514
3515 Expected<ArrayRef<uint8_t>> ContentOrErr =
3516 Obj.getSectionContents(*StackMapSection);
3517 if (!ContentOrErr) {
3518 Warn(ContentOrErr.takeError());
3519 return;
3520 }
3521
3522 if (Error E =
3523 StackMapParser<ELFT::Endianness>::validateHeader(*ContentOrErr)) {
3524 Warn(std::move(E));
3525 return;
3526 }
3527
3528 prettyPrintStackMap(W, StackMapParser<ELFT::Endianness>(*ContentOrErr));
3529}
3530
3531template <class ELFT>
3532void ELFDumper<ELFT>::printReloc(const Relocation<ELFT> &R, unsigned RelIndex,
3533 const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
3534 Expected<RelSymbol<ELFT>> Target = getRelocationTarget(R, SymTab);
3535 if (!Target) {
3536 reportUniqueWarning("unable to print relocation " + Twine(RelIndex) +
3537 " in " + describe(Sec) + ": " +
3538 toString(Target.takeError()));
3539 return;
3540 }
3541
3542 // Track RISCV vendor symbol for resolving vendor-specific relocations.
3543 // Per RISC-V psABI, R_RISCV_VENDOR must be placed immediately before the
3544 // vendor-specific relocation at the same offset.
3545 if (Obj.getHeader().e_machine == ELF::EM_RISCV) {
3546 if (R.Type == ELF::R_RISCV_VENDOR) {
3547 // Store vendor symbol name and offset for the next relocation.
3548 CurrentRISCVVendorSymbol = Target->Name;
3549 CurrentRISCVVendorOffset = R.Offset;
3550 } else if (!CurrentRISCVVendorSymbol.empty()) {
3551 // We have a pending vendor symbol. Clear it if this relocation doesn't
3552 // form a valid pair: either the offset doesn't match or this is not a
3553 // vendor-specific (CUSTOM) relocation.
3554 if (R.Offset != CurrentRISCVVendorOffset ||
3555 R.Type < ELF::R_RISCV_CUSTOM192 || R.Type > ELF::R_RISCV_CUSTOM255) {
3556 CurrentRISCVVendorSymbol.clear();
3557 }
3558 // If it IS a valid CUSTOM relocation at matching offset,
3559 // getRelocTypeName will use and clear the vendor symbol.
3560 }
3561 }
3562
3563 printRelRelaReloc(R, RelSym: *Target);
3564}
3565
3566template <class ELFT>
3567StringRef ELFDumper<ELFT>::getRelocTypeName(uint32_t Type,
3568 SmallString<32> &RelocName) {
3569 Obj.getRelocationTypeName(Type, RelocName);
3570
3571 // For RISCV vendor-specific relocations, use the vendor-specific name
3572 // if we have a vendor symbol from a preceding R_RISCV_VENDOR relocation.
3573 // Per RISC-V psABI, R_RISCV_VENDOR must be placed immediately before the
3574 // vendor-specific relocation, so we consume the vendor symbol after use.
3575 if (Obj.getHeader().e_machine == ELF::EM_RISCV &&
3576 Type >= ELF::R_RISCV_CUSTOM192 && Type <= ELF::R_RISCV_CUSTOM255 &&
3577 !CurrentRISCVVendorSymbol.empty()) {
3578 StringRef VendorRelocName =
3579 getRISCVVendorRelocationTypeName(Type, Vendor: CurrentRISCVVendorSymbol);
3580 CurrentRISCVVendorSymbol.clear();
3581 // Only use the vendor-specific name if the vendor is known.
3582 // Otherwise, keep the generic R_RISCV_CUSTOM* name.
3583 if (VendorRelocName != "Unknown")
3584 return VendorRelocName;
3585 }
3586 return RelocName;
3587}
3588
3589template <class ELFT>
3590std::vector<const EnumString<unsigned, 2> *>
3591ELFDumper<ELFT>::getOtherFlagsFromSymbol(const Elf_Ehdr &Header,
3592 const Elf_Sym &Symbol) const {
3593 std::vector<const EnumString<unsigned, 2> *> SymOtherFlags;
3594 for (const auto &Entry : EnumStrings(ElfSymOtherFlags))
3595 SymOtherFlags.push_back(x: &Entry);
3596 if (Header.e_machine == EM_MIPS) {
3597 // Someone in their infinite wisdom decided to make STO_MIPS_MIPS16
3598 // flag overlap with other ST_MIPS_xxx flags. So consider both
3599 // cases separately.
3600 if ((Symbol.st_other & STO_MIPS_MIPS16) == STO_MIPS_MIPS16)
3601 for (const auto &Entry : EnumStrings(ElfMips16SymOtherFlags))
3602 SymOtherFlags.push_back(x: &Entry);
3603 else
3604 for (const auto &Entry : EnumStrings(ElfMipsSymOtherFlags))
3605 SymOtherFlags.push_back(x: &Entry);
3606 } else if (Header.e_machine == EM_AARCH64) {
3607 for (const auto &Entry : EnumStrings(ElfAArch64SymOtherFlags))
3608 SymOtherFlags.push_back(x: &Entry);
3609 } else if (Header.e_machine == EM_RISCV) {
3610 for (const auto &Entry : EnumStrings(ElfRISCVSymOtherFlags))
3611 SymOtherFlags.push_back(x: &Entry);
3612 }
3613 return SymOtherFlags;
3614}
3615
3616static inline void printFields(formatted_raw_ostream &OS, StringRef Str1,
3617 StringRef Str2) {
3618 OS.PadToColumn(NewCol: 2u);
3619 OS << Str1;
3620 OS.PadToColumn(NewCol: 37u);
3621 OS << Str2 << "\n";
3622 OS.flush();
3623}
3624
3625template <class ELFT>
3626std::string ELFDumper<ELFT>::getProgramHeadersNumString() {
3627 const ELFFile<ELFT> &Obj = this->Obj;
3628 Expected<uint32_t> PhNumOrErr = Obj.getPhNum();
3629 if (!PhNumOrErr) {
3630 this->reportUniqueWarning(PhNumOrErr.takeError());
3631 return "<?>";
3632 }
3633
3634 uint32_t PhNum;
3635 PhNum = *PhNumOrErr;
3636 if (Obj.getHeader().e_phnum != ELF::PN_XNUM)
3637 return to_string(Value: PhNum);
3638 return "65535 (" + to_string(Value: PhNum) + ")";
3639}
3640
3641template <class ELFT>
3642static std::string getSectionHeadersNumString(const ELFFile<ELFT> &Obj,
3643 StringRef FileName) {
3644 const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3645 if (ElfHeader.e_shnum != 0)
3646 return to_string(ElfHeader.e_shnum);
3647
3648 Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3649 if (!ArrOrErr) {
3650 // In this case we can ignore an error, because we have already reported a
3651 // warning about the broken section header table earlier.
3652 consumeError(ArrOrErr.takeError());
3653 return "<?>";
3654 }
3655
3656 if (ArrOrErr->empty())
3657 return "0";
3658 return "0 (" + to_string((*ArrOrErr)[0].sh_size) + ")";
3659}
3660
3661template <class ELFT>
3662static std::string getSectionHeaderTableIndexString(const ELFFile<ELFT> &Obj,
3663 StringRef FileName) {
3664 const typename ELFT::Ehdr &ElfHeader = Obj.getHeader();
3665 if (ElfHeader.e_shstrndx != SHN_XINDEX)
3666 return to_string(ElfHeader.e_shstrndx);
3667
3668 Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections();
3669 if (!ArrOrErr) {
3670 // In this case we can ignore an error, because we have already reported a
3671 // warning about the broken section header table earlier.
3672 consumeError(ArrOrErr.takeError());
3673 return "<?>";
3674 }
3675
3676 if (ArrOrErr->empty())
3677 return "65535 (corrupt: out of range)";
3678 return to_string(ElfHeader.e_shstrndx) + " (" +
3679 to_string((*ArrOrErr)[0].sh_link) + ")";
3680}
3681
3682template <class ELFT>
3683void GNUELFDumper<ELFT>::printFileSummary(StringRef FileStr, ObjectFile &Obj,
3684 ArrayRef<std::string> InputFilenames,
3685 const Archive *A) {
3686 if (InputFilenames.size() > 1 || A) {
3687 this->W.startLine() << "\n";
3688 this->W.printString("File", FileStr);
3689 }
3690}
3691
3692template <class ELFT> void GNUELFDumper<ELFT>::printFileHeaders() {
3693 const Elf_Ehdr &e = this->Obj.getHeader();
3694 OS << "ELF Header:\n";
3695 OS << " Magic: ";
3696 std::string Str;
3697 for (int i = 0; i < ELF::EI_NIDENT; i++)
3698 OS << format(Fmt: " %02x", Vals: static_cast<int>(e.e_ident[i]));
3699 OS << "\n";
3700 Str = EnumStrings(ElfClass).toStringOrHex(e.e_ident[ELF::EI_CLASS], 1);
3701 printFields(OS, Str1: "Class:", Str2: Str);
3702 Str = EnumStrings(ElfDataEncoding).toStringOrHex(e.e_ident[ELF::EI_DATA], 1);
3703 printFields(OS, Str1: "Data:", Str2: Str);
3704 OS.PadToColumn(NewCol: 2u);
3705 OS << "Version:";
3706 OS.PadToColumn(NewCol: 37u);
3707 OS << utohexstr(e.e_ident[ELF::EI_VERSION], /*LowerCase=*/true);
3708 if (e.e_version == ELF::EV_CURRENT)
3709 OS << " (current)";
3710 OS << "\n";
3711 EnumStrings<unsigned, 2> OSABI = EnumStrings(ElfOSABI);
3712 if (e.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH &&
3713 e.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) {
3714 switch (e.e_machine) {
3715 case ELF::EM_ARM:
3716 OSABI = EnumStrings(ARMElfOSABI);
3717 break;
3718 case ELF::EM_AMDGPU:
3719 OSABI = EnumStrings(AMDGPUElfOSABI);
3720 break;
3721 default:
3722 break;
3723 }
3724 }
3725 Str = OSABI.toStringOrHex(e.e_ident[ELF::EI_OSABI], 1);
3726 printFields(OS, Str1: "OS/ABI:", Str2: Str);
3727 printFields(OS,
3728 "ABI Version:", std::to_string(e.e_ident[ELF::EI_ABIVERSION]));
3729
3730 if (StringRef Name = EnumStrings(ElfObjectFileType).toString(e.e_type, 1);
3731 !Name.empty()) {
3732 Str = Name.str();
3733 } else {
3734 if (e.e_type >= ET_LOPROC)
3735 Str = "Processor Specific: (" + utohexstr(e.e_type, /*LowerCase=*/true) + ")";
3736 else if (e.e_type >= ET_LOOS)
3737 Str = "OS Specific: (" + utohexstr(e.e_type, /*LowerCase=*/true) + ")";
3738 else
3739 Str = "<unknown>: " + utohexstr(e.e_type, /*LowerCase=*/true);
3740 }
3741 printFields(OS, Str1: "Type:", Str2: Str);
3742
3743 Str = EnumStrings(ElfMachineType).toStringOrHex(e.e_machine, 1);
3744 printFields(OS, Str1: "Machine:", Str2: Str);
3745 Str = "0x" + utohexstr(e.e_version, /*LowerCase=*/true);
3746 printFields(OS, Str1: "Version:", Str2: Str);
3747 Str = "0x" + utohexstr(e.e_entry, /*LowerCase=*/true);
3748 printFields(OS, Str1: "Entry point address:", Str2: Str);
3749 Str = to_string(e.e_phoff) + " (bytes into file)";
3750 printFields(OS, Str1: "Start of program headers:", Str2: Str);
3751 Str = to_string(e.e_shoff) + " (bytes into file)";
3752 printFields(OS, Str1: "Start of section headers:", Str2: Str);
3753 std::string ElfFlags;
3754 if (e.e_machine == EM_MIPS)
3755 ElfFlags = printFlags(
3756 e.e_flags, EnumStrings(ElfHeaderMipsFlags), unsigned(ELF::EF_MIPS_ARCH),
3757 unsigned(ELF::EF_MIPS_ABI), unsigned(ELF::EF_MIPS_MACH));
3758 else if (e.e_machine == EM_RISCV)
3759 ElfFlags = printFlags(e.e_flags, EnumStrings(ElfHeaderRISCVFlags));
3760 else if (e.e_machine == EM_SPARC32PLUS || e.e_machine == EM_SPARCV9)
3761 ElfFlags = printFlags(e.e_flags, EnumStrings(ElfHeaderSPARCFlags),
3762 unsigned(ELF::EF_SPARCV9_MM));
3763 else if (e.e_machine == EM_AVR)
3764 ElfFlags = printFlags(e.e_flags, EnumStrings(ElfHeaderAVRFlags),
3765 unsigned(ELF::EF_AVR_ARCH_MASK));
3766 else if (e.e_machine == EM_LOONGARCH)
3767 ElfFlags = printFlags(e.e_flags, EnumStrings(ElfHeaderLoongArchFlags),
3768 unsigned(ELF::EF_LOONGARCH_ABI_MODIFIER_MASK),
3769 unsigned(ELF::EF_LOONGARCH_OBJABI_MASK));
3770 else if (e.e_machine == EM_XTENSA)
3771 ElfFlags = printFlags(e.e_flags, EnumStrings(ElfHeaderXtensaFlags),
3772 unsigned(ELF::EF_XTENSA_MACH));
3773 else if (e.e_machine == EM_CUDA) {
3774 unsigned Mask = e.e_ident[ELF::EI_ABIVERSION] == ELF::ELFABIVERSION_CUDA_V1
3775 ? ELF::EF_CUDA_SM
3776 : ELF::EF_CUDA_SM_MASK;
3777 ElfFlags = printFlags(e.e_flags, EnumStrings(ElfHeaderNVPTXFlags), Mask);
3778 if (e.e_ident[ELF::EI_ABIVERSION] == ELF::ELFABIVERSION_CUDA_V1 &&
3779 (e.e_flags & ELF::EF_CUDA_ACCELERATORS_V1))
3780 ElfFlags += "a";
3781 else if (e.e_ident[ELF::EI_ABIVERSION] == ELF::ELFABIVERSION_CUDA_V2 &&
3782 (e.e_flags & ELF::EF_CUDA_ACCELERATORS))
3783 ElfFlags += "a";
3784 } else if (e.e_machine == EM_AMDGPU) {
3785 switch (e.e_ident[ELF::EI_ABIVERSION]) {
3786 default:
3787 break;
3788 case 0:
3789 // ELFOSABI_AMDGPU_PAL, ELFOSABI_AMDGPU_MESA3D support *_V3 flags.
3790 [[fallthrough]];
3791 case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
3792 ElfFlags =
3793 printFlags(e.e_flags, EnumStrings(ElfHeaderAMDGPUFlagsABIVersion3),
3794 unsigned(ELF::EF_AMDGPU_MACH));
3795 break;
3796 case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
3797 case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
3798 ElfFlags =
3799 printFlags(e.e_flags, EnumStrings(ElfHeaderAMDGPUFlagsABIVersion4),
3800 unsigned(ELF::EF_AMDGPU_MACH),
3801 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
3802 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
3803 break;
3804 case ELF::ELFABIVERSION_AMDGPU_HSA_V6: {
3805 ElfFlags =
3806 printFlags(e.e_flags, EnumStrings(ElfHeaderAMDGPUFlagsABIVersion4),
3807 unsigned(ELF::EF_AMDGPU_MACH),
3808 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
3809 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
3810 if (auto GenericV = e.e_flags & ELF::EF_AMDGPU_GENERIC_VERSION) {
3811 ElfFlags +=
3812 ", generic_v" +
3813 to_string(GenericV >> ELF::EF_AMDGPU_GENERIC_VERSION_OFFSET);
3814 }
3815 } break;
3816 }
3817 }
3818 Str = "0x" + utohexstr(e.e_flags, /*LowerCase=*/true);
3819 if (!ElfFlags.empty())
3820 Str = Str + ", " + ElfFlags;
3821 printFields(OS, Str1: "Flags:", Str2: Str);
3822 Str = to_string(e.e_ehsize) + " (bytes)";
3823 printFields(OS, Str1: "Size of this header:", Str2: Str);
3824 Str = to_string(e.e_phentsize) + " (bytes)";
3825 printFields(OS, Str1: "Size of program headers:", Str2: Str);
3826 Str = this->getProgramHeadersNumString();
3827 printFields(OS, Str1: "Number of program headers:", Str2: Str);
3828 Str = to_string(e.e_shentsize) + " (bytes)";
3829 printFields(OS, Str1: "Size of section headers:", Str2: Str);
3830 Str = getSectionHeadersNumString(this->Obj, this->FileName);
3831 printFields(OS, Str1: "Number of section headers:", Str2: Str);
3832 Str = getSectionHeaderTableIndexString(this->Obj, this->FileName);
3833 printFields(OS, Str1: "Section header string table index:", Str2: Str);
3834}
3835
3836template <class ELFT> std::vector<GroupSection> ELFDumper<ELFT>::getGroups() {
3837 auto GetSignature = [&](const Elf_Sym &Sym, unsigned SymNdx,
3838 const Elf_Shdr &Symtab) -> StringRef {
3839 Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(Symtab);
3840 if (!StrTableOrErr) {
3841 reportUniqueWarning("unable to get the string table for " +
3842 describe(Sec: Symtab) + ": " +
3843 toString(E: StrTableOrErr.takeError()));
3844 return "<?>";
3845 }
3846
3847 StringRef Strings = *StrTableOrErr;
3848 if (Sym.st_name >= Strings.size()) {
3849 reportUniqueWarning("unable to get the name of the symbol with index " +
3850 Twine(SymNdx) + ": st_name (0x" +
3851 Twine::utohexstr(Val: Sym.st_name) +
3852 ") is past the end of the string table of size 0x" +
3853 Twine::utohexstr(Val: Strings.size()));
3854 return "<?>";
3855 }
3856
3857 return StrTableOrErr->data() + Sym.st_name;
3858 };
3859
3860 std::vector<GroupSection> Ret;
3861 uint64_t I = 0;
3862 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
3863 ++I;
3864 if (Sec.sh_type != ELF::SHT_GROUP)
3865 continue;
3866
3867 StringRef Signature = "<?>";
3868 if (Expected<const Elf_Shdr *> SymtabOrErr = Obj.getSection(Sec.sh_link)) {
3869 if (Expected<const Elf_Sym *> SymOrErr =
3870 Obj.template getEntry<Elf_Sym>(**SymtabOrErr, Sec.sh_info))
3871 Signature = GetSignature(**SymOrErr, Sec.sh_info, **SymtabOrErr);
3872 else
3873 reportUniqueWarning("unable to get the signature symbol for " +
3874 describe(Sec) + ": " +
3875 toString(SymOrErr.takeError()));
3876 } else {
3877 reportUniqueWarning("unable to get the symbol table for " +
3878 describe(Sec) + ": " +
3879 toString(SymtabOrErr.takeError()));
3880 }
3881
3882 ArrayRef<Elf_Word> Data;
3883 if (Expected<ArrayRef<Elf_Word>> ContentsOrErr =
3884 Obj.template getSectionContentsAsArray<Elf_Word>(Sec)) {
3885 if (ContentsOrErr->empty())
3886 reportUniqueWarning("unable to read the section group flag from the " +
3887 describe(Sec) + ": the section is empty");
3888 else
3889 Data = *ContentsOrErr;
3890 } else {
3891 reportUniqueWarning("unable to get the content of the " + describe(Sec) +
3892 ": " + toString(ContentsOrErr.takeError()));
3893 }
3894
3895 Ret.push_back({getPrintableSectionName(Sec),
3896 maybeDemangle(Name: Signature),
3897 Sec.sh_name,
3898 I - 1,
3899 Sec.sh_link,
3900 Sec.sh_info,
3901 Data.empty() ? Elf_Word(0) : Data[0],
3902 {}});
3903
3904 if (Data.empty())
3905 continue;
3906
3907 std::vector<GroupMember> &GM = Ret.back().Members;
3908 for (uint32_t Ndx : Data.slice(1)) {
3909 if (Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(Ndx)) {
3910 GM.push_back({getPrintableSectionName(Sec: **SecOrErr), Ndx});
3911 } else {
3912 reportUniqueWarning("unable to get the section with index " +
3913 Twine(Ndx) + " when dumping the " + describe(Sec) +
3914 ": " + toString(SecOrErr.takeError()));
3915 GM.push_back(x: {.Name: "<?>", .Index: Ndx});
3916 }
3917 }
3918 }
3919 return Ret;
3920}
3921
3922static DenseMap<uint64_t, const GroupSection *>
3923mapSectionsToGroups(ArrayRef<GroupSection> Groups) {
3924 DenseMap<uint64_t, const GroupSection *> Ret;
3925 for (const GroupSection &G : Groups)
3926 for (const GroupMember &GM : G.Members)
3927 Ret.insert(KV: {GM.Index, &G});
3928 return Ret;
3929}
3930
3931template <class ELFT> void GNUELFDumper<ELFT>::printGroupSections() {
3932 std::vector<GroupSection> V = this->getGroups();
3933 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(Groups: V);
3934 for (const GroupSection &G : V) {
3935 OS << "\n"
3936 << getGroupType(Flag: G.Type) << " group section ["
3937 << format_decimal(N: G.Index, Width: 5) << "] `" << G.Name << "' [" << G.Signature
3938 << "] contains " << G.Members.size() << " sections:\n"
3939 << " [Index] Name\n";
3940 for (const GroupMember &GM : G.Members) {
3941 const GroupSection *MainGroup = Map[GM.Index];
3942 if (MainGroup != &G)
3943 this->reportUniqueWarning(
3944 "section with index " + Twine(GM.Index) +
3945 ", included in the group section with index " +
3946 Twine(MainGroup->Index) +
3947 ", was also found in the group section with index " +
3948 Twine(G.Index));
3949 OS << " [" << format_decimal(N: GM.Index, Width: 5) << "] " << GM.Name << "\n";
3950 }
3951 }
3952
3953 if (V.empty())
3954 OS << "There are no section groups in this file.\n";
3955}
3956
3957template <class ELFT>
3958void GNUELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
3959 const RelSymbol<ELFT> &RelSym) {
3960 // First two fields are bit width dependent. The rest of them are fixed width.
3961 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3962 Field Fields[5] = {0, 10 + Bias, 19 + 2 * Bias, 42 + 2 * Bias, 53 + 2 * Bias};
3963 unsigned Width = ELFT::Is64Bits ? 16 : 8;
3964
3965 Fields[0].Str = to_string(format_hex_no_prefix(R.Offset, Width));
3966 Fields[1].Str = to_string(format_hex_no_prefix(R.Info, Width));
3967
3968 SmallString<32> RelocName;
3969 Fields[2].Str = this->getRelocTypeName(R.Type, RelocName);
3970
3971 if (RelSym.Sym)
3972 Fields[3].Str =
3973 to_string(format_hex_no_prefix(RelSym.Sym->getValue(), Width));
3974 if (RelSym.Sym && RelSym.Name.empty())
3975 Fields[4].Str = "<null>";
3976 else
3977 Fields[4].Str = std::string(RelSym.Name);
3978
3979 for (const Field &F : Fields)
3980 printField(F);
3981
3982 std::string Addend;
3983 if (std::optional<int64_t> A = R.Addend) {
3984 int64_t RelAddend = *A;
3985 if (!Fields[4].Str.empty()) {
3986 if (RelAddend < 0) {
3987 Addend = " - ";
3988 RelAddend = -static_cast<uint64_t>(RelAddend);
3989 } else {
3990 Addend = " + ";
3991 }
3992 }
3993 Addend += utohexstr(X: RelAddend, /*LowerCase=*/true);
3994 }
3995 OS << Addend << "\n";
3996}
3997
3998template <class ELFT>
3999static void printRelocHeaderFields(formatted_raw_ostream &OS, unsigned SType,
4000 const typename ELFT::Ehdr &EHeader,
4001 uint64_t CrelHdr = 0) {
4002 bool IsRela = SType == ELF::SHT_RELA || SType == ELF::SHT_ANDROID_RELA;
4003 if (ELFT::Is64Bits)
4004 OS << " Offset Info Type Symbol's "
4005 "Value Symbol's Name";
4006 else
4007 OS << " Offset Info Type Sym. Value Symbol's Name";
4008 if (IsRela || (SType == ELF::SHT_CREL && (CrelHdr & CREL_HDR_ADDEND)))
4009 OS << " + Addend";
4010 OS << "\n";
4011}
4012
4013template <class ELFT>
4014void GNUELFDumper<ELFT>::printDynamicRelocHeader(unsigned Type, StringRef Name,
4015 const DynRegionInfo &Reg) {
4016 uint64_t Offset = Reg.Addr - this->Obj.base();
4017 OS << "\n'" << Name.str().c_str() << "' relocation section at offset 0x"
4018 << utohexstr(X: Offset, /*LowerCase=*/true);
4019 if (Type != ELF::SHT_CREL)
4020 OS << " contains " << Reg.Size << " bytes";
4021 OS << ":\n";
4022 printRelocHeaderFields<ELFT>(OS, Type, this->Obj.getHeader());
4023}
4024
4025template <class ELFT>
4026static bool isRelocationSec(const typename ELFT::Shdr &Sec,
4027 const typename ELFT::Ehdr &EHeader) {
4028 return Sec.sh_type == ELF::SHT_REL || Sec.sh_type == ELF::SHT_RELA ||
4029 Sec.sh_type == ELF::SHT_RELR || Sec.sh_type == ELF::SHT_CREL ||
4030 Sec.sh_type == ELF::SHT_ANDROID_REL ||
4031 Sec.sh_type == ELF::SHT_ANDROID_RELA ||
4032 Sec.sh_type == ELF::SHT_ANDROID_RELR ||
4033 (EHeader.e_machine == EM_AARCH64 &&
4034 Sec.sh_type == ELF::SHT_AARCH64_AUTH_RELR);
4035}
4036
4037template <class ELFT> void GNUELFDumper<ELFT>::printRelocations() {
4038 auto PrintAsRelr = [&](const Elf_Shdr &Sec) {
4039 return Sec.sh_type == ELF::SHT_RELR ||
4040 Sec.sh_type == ELF::SHT_ANDROID_RELR ||
4041 (this->Obj.getHeader().e_machine == EM_AARCH64 &&
4042 Sec.sh_type == ELF::SHT_AARCH64_AUTH_RELR);
4043 };
4044 auto GetEntriesNum = [&](const Elf_Shdr &Sec) -> Expected<size_t> {
4045 // Android's packed relocation section needs to be unpacked first
4046 // to get the actual number of entries.
4047 if (Sec.sh_type == ELF::SHT_ANDROID_REL ||
4048 Sec.sh_type == ELF::SHT_ANDROID_RELA) {
4049 Expected<std::vector<typename ELFT::Rela>> RelasOrErr =
4050 this->Obj.android_relas(Sec);
4051 if (!RelasOrErr)
4052 return RelasOrErr.takeError();
4053 return RelasOrErr->size();
4054 }
4055
4056 if (Sec.sh_type == ELF::SHT_CREL) {
4057 Expected<ArrayRef<uint8_t>> ContentsOrErr =
4058 this->Obj.getSectionContents(Sec);
4059 if (!ContentsOrErr)
4060 return ContentsOrErr.takeError();
4061 auto NumOrErr = this->Obj.getCrelHeader(*ContentsOrErr);
4062 if (!NumOrErr)
4063 return NumOrErr.takeError();
4064 return *NumOrErr / 8;
4065 }
4066
4067 if (PrintAsRelr(Sec)) {
4068 Expected<Elf_Relr_Range> RelrsOrErr = this->Obj.relrs(Sec);
4069 if (!RelrsOrErr)
4070 return RelrsOrErr.takeError();
4071 return this->Obj.decode_relrs(*RelrsOrErr).size();
4072 }
4073
4074 return Sec.getEntityCount();
4075 };
4076
4077 bool HasRelocSections = false;
4078 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4079 if (!isRelocationSec<ELFT>(Sec, this->Obj.getHeader()))
4080 continue;
4081 HasRelocSections = true;
4082
4083 std::string EntriesNum = "<?>";
4084 if (Expected<size_t> NumOrErr = GetEntriesNum(Sec))
4085 EntriesNum = std::to_string(val: *NumOrErr);
4086 else
4087 this->reportUniqueWarning("unable to get the number of relocations in " +
4088 this->describe(Sec) + ": " +
4089 toString(E: NumOrErr.takeError()));
4090
4091 uintX_t Offset = Sec.sh_offset;
4092 StringRef Name = this->getPrintableSectionName(Sec);
4093 OS << "\nRelocation section '" << Name << "' at offset 0x"
4094 << utohexstr(Offset, /*LowerCase=*/true) << " contains " << EntriesNum
4095 << " entries:\n";
4096
4097 if (PrintAsRelr(Sec)) {
4098 printRelr(Sec);
4099 } else {
4100 uint64_t CrelHdr = 0;
4101 // For CREL, read the header and call printRelocationsHelper only if
4102 // GetEntriesNum(Sec) succeeded.
4103 if (Sec.sh_type == ELF::SHT_CREL && EntriesNum != "<?>") {
4104 CrelHdr = cantFail(this->Obj.getCrelHeader(
4105 cantFail(this->Obj.getSectionContents(Sec))));
4106 }
4107 printRelocHeaderFields<ELFT>(OS, Sec.sh_type, this->Obj.getHeader(),
4108 CrelHdr);
4109 if (Sec.sh_type != ELF::SHT_CREL || EntriesNum != "<?>")
4110 this->printRelocationsHelper(Sec);
4111 }
4112 }
4113 if (!HasRelocSections)
4114 OS << "\nThere are no relocations in this file.\n";
4115}
4116
4117template <class ELFT> void GNUELFDumper<ELFT>::printRelr(const Elf_Shdr &Sec) {
4118 Expected<Elf_Relr_Range> RangeOrErr = this->Obj.relrs(Sec);
4119 if (!RangeOrErr) {
4120 this->reportUniqueWarning("unable to read relocations from " +
4121 this->describe(Sec) + ": " +
4122 toString(RangeOrErr.takeError()));
4123 return;
4124 }
4125 if (ELFT::Is64Bits)
4126 OS << "Index: Entry Address Symbolic Address\n";
4127 else
4128 OS << "Index: Entry Address Symbolic Address\n";
4129
4130 // If .symtab is available, collect its defined symbols and sort them by
4131 // st_value.
4132 SmallVector<std::pair<uint64_t, std::string>, 0> Syms;
4133 if (this->DotSymtabSec) {
4134 Elf_Sym_Range Symtab;
4135 std::optional<StringRef> Strtab;
4136 std::tie(Symtab, Strtab) = this->getSymtabAndStrtab();
4137 if (Symtab.size() && Strtab) {
4138 for (auto [I, Sym] : enumerate(Symtab)) {
4139 if (!Sym.st_shndx)
4140 continue;
4141 Syms.emplace_back(Sym.st_value,
4142 this->getFullSymbolName(Sym, I, ArrayRef<Elf_Word>(),
4143 *Strtab, false));
4144 }
4145 }
4146 }
4147 llvm::stable_sort(Range&: Syms);
4148
4149 typename ELFT::uint Base = 0;
4150 size_t I = 0;
4151 auto Print = [&](uint64_t Where) {
4152 OS << format_hex_no_prefix(Where, ELFT::Is64Bits ? 16 : 8);
4153 for (; I < Syms.size() && Syms[I].first <= Where; ++I)
4154 ;
4155 // Try symbolizing the address. Find the nearest symbol before or at the
4156 // address and print the symbol and the address difference.
4157 if (I) {
4158 OS << " " << Syms[I - 1].second;
4159 if (Syms[I - 1].first < Where)
4160 OS << " + 0x" << Twine::utohexstr(Val: Where - Syms[I - 1].first);
4161 }
4162 OS << '\n';
4163 };
4164 for (auto [Index, R] : enumerate(*RangeOrErr)) {
4165 typename ELFT::uint Entry = R;
4166 OS << formatv("{0:4}: ", Index)
4167 << format_hex_no_prefix(Entry, ELFT::Is64Bits ? 16 : 8) << ' ';
4168 if ((Entry & 1) == 0) {
4169 Print(Entry);
4170 Base = Entry + sizeof(typename ELFT::uint);
4171 } else {
4172 bool First = true;
4173 for (auto Where = Base; Entry >>= 1;
4174 Where += sizeof(typename ELFT::uint)) {
4175 if (Entry & 1) {
4176 if (First)
4177 First = false;
4178 else
4179 OS.indent(NumSpaces: ELFT::Is64Bits ? 24 : 16);
4180 Print(Where);
4181 }
4182 }
4183 Base += (CHAR_BIT * sizeof(Entry) - 1) * sizeof(typename ELFT::uint);
4184 }
4185 }
4186}
4187
4188// Print the offset of a particular section from anyone of the ranges:
4189// [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER].
4190// If 'Type' does not fall within any of those ranges, then a string is
4191// returned as '<unknown>' followed by the type value.
4192static std::string getSectionTypeOffsetString(unsigned Type) {
4193 if (Type >= SHT_LOOS && Type <= SHT_HIOS)
4194 return "LOOS+0x" + utohexstr(X: Type - SHT_LOOS, /*LowerCase=*/true);
4195 else if (Type >= SHT_LOPROC && Type <= SHT_HIPROC)
4196 return "LOPROC+0x" + utohexstr(X: Type - SHT_LOPROC, /*LowerCase=*/true);
4197 else if (Type >= SHT_LOUSER && Type <= SHT_HIUSER)
4198 return "LOUSER+0x" + utohexstr(X: Type - SHT_LOUSER, /*LowerCase=*/true);
4199 return "0x" + utohexstr(X: Type, /*LowerCase=*/true) + ": <unknown>";
4200}
4201
4202static std::string getSectionTypeString(unsigned Machine, unsigned Type) {
4203 StringRef Name = getELFSectionTypeName(Machine, Type);
4204
4205 // Handle SHT_GNU_* type names.
4206 if (Name.consume_front(Prefix: "SHT_GNU_")) {
4207 if (Name == "HASH")
4208 return "GNU_HASH";
4209 // E.g. SHT_GNU_verneed -> VERNEED.
4210 return Name.upper();
4211 }
4212
4213 if (Name == "SHT_SYMTAB_SHNDX")
4214 return "SYMTAB SECTION INDICES";
4215
4216 if (Name.consume_front(Prefix: "SHT_"))
4217 return Name.str();
4218 return getSectionTypeOffsetString(Type);
4219}
4220
4221static void printSectionDescription(formatted_raw_ostream &OS,
4222 unsigned EMachine) {
4223 OS << "Key to Flags:\n";
4224 OS << " W (write), A (alloc), X (execute), M (merge), S (strings), I "
4225 "(info),\n";
4226 OS << " L (link order), O (extra OS processing required), G (group), T "
4227 "(TLS),\n";
4228 OS << " C (compressed), x (unknown), o (OS specific), E (exclude),\n";
4229 OS << " R (retain)";
4230
4231 if (EMachine == EM_X86_64)
4232 OS << ", l (large)";
4233 else if (EMachine == EM_ARM || EMachine == EM_AARCH64)
4234 OS << ", y (purecode)";
4235
4236 OS << ", p (processor specific)\n";
4237}
4238
4239template <class ELFT> void GNUELFDumper<ELFT>::printSectionHeaders() {
4240 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
4241 if (Sections.empty()) {
4242 OS << "\nThere are no sections in this file.\n";
4243 Expected<StringRef> SecStrTableOrErr =
4244 this->Obj.getSectionStringTable(Sections, this->WarningHandler);
4245 if (!SecStrTableOrErr)
4246 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4247 return;
4248 }
4249 unsigned Bias = ELFT::Is64Bits ? 0 : 8;
4250 OS << "There are " << to_string(Sections.size())
4251 << " section headers, starting at offset "
4252 << "0x" << utohexstr(this->Obj.getHeader().e_shoff, /*LowerCase=*/true) << ":\n\n";
4253 OS << "Section Headers:\n";
4254 Field Fields[11] = {
4255 {"[Nr]", 2}, {"Name", 7}, {"Type", 25},
4256 {"Address", 41}, {"Off", 58 - Bias}, {"Size", 65 - Bias},
4257 {"ES", 72 - Bias}, {"Flg", 75 - Bias}, {"Lk", 79 - Bias},
4258 {"Inf", 82 - Bias}, {"Al", 86 - Bias}};
4259 for (const Field &F : Fields)
4260 printField(F);
4261 OS << "\n";
4262
4263 StringRef SecStrTable;
4264 if (Expected<StringRef> SecStrTableOrErr =
4265 this->Obj.getSectionStringTable(Sections, this->WarningHandler))
4266 SecStrTable = *SecStrTableOrErr;
4267 else
4268 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4269
4270 size_t SectionIndex = 0;
4271 for (const Elf_Shdr &Sec : Sections) {
4272 Fields[0].Str = to_string(Value: SectionIndex);
4273 if (SecStrTable.empty())
4274 Fields[1].Str = "<no-strings>";
4275 else
4276 Fields[1].Str = std::string(unwrapOrError<StringRef>(
4277 this->FileName, this->Obj.getSectionName(Sec, SecStrTable)));
4278 Fields[2].Str =
4279 getSectionTypeString(this->Obj.getHeader().e_machine, Sec.sh_type);
4280 Fields[3].Str =
4281 to_string(format_hex_no_prefix(Sec.sh_addr, ELFT::Is64Bits ? 16 : 8));
4282 Fields[4].Str = to_string(format_hex_no_prefix(Sec.sh_offset, 6));
4283 Fields[5].Str = to_string(format_hex_no_prefix(Sec.sh_size, 6));
4284 Fields[6].Str = to_string(format_hex_no_prefix(Sec.sh_entsize, 2));
4285 Fields[7].Str = getGNUFlags(this->Obj.getHeader().e_ident[ELF::EI_OSABI],
4286 this->Obj.getHeader().e_machine, Sec.sh_flags);
4287 Fields[8].Str = to_string(Sec.sh_link);
4288 Fields[9].Str = to_string(Sec.sh_info);
4289 Fields[10].Str = to_string(Sec.sh_addralign);
4290
4291 OS.PadToColumn(NewCol: Fields[0].Column);
4292 OS << "[" << right_justify(Fields[0].Str, 2) << "]";
4293 for (int i = 1; i < 7; i++)
4294 printField(F: Fields[i]);
4295 OS.PadToColumn(NewCol: Fields[7].Column);
4296 OS << right_justify(Fields[7].Str, 3);
4297 OS.PadToColumn(NewCol: Fields[8].Column);
4298 OS << right_justify(Fields[8].Str, 2);
4299 OS.PadToColumn(NewCol: Fields[9].Column);
4300 OS << right_justify(Fields[9].Str, 3);
4301 OS.PadToColumn(NewCol: Fields[10].Column);
4302 OS << right_justify(Fields[10].Str, 2);
4303 OS << "\n";
4304 ++SectionIndex;
4305 }
4306 printSectionDescription(OS, this->Obj.getHeader().e_machine);
4307}
4308
4309template <class ELFT>
4310void GNUELFDumper<ELFT>::printSymtabMessage(const Elf_Shdr *Symtab,
4311 size_t Entries,
4312 bool NonVisibilityBitsUsed,
4313 bool ExtraSymInfo) const {
4314 StringRef Name;
4315 if (Symtab)
4316 Name = this->getPrintableSectionName(*Symtab);
4317 if (!Name.empty())
4318 OS << "\nSymbol table '" << Name << "'";
4319 else
4320 OS << "\nSymbol table for image";
4321 OS << " contains " << Entries << " entries:\n";
4322
4323 if (ELFT::Is64Bits) {
4324 OS << " Num: Value Size Type Bind Vis";
4325 if (ExtraSymInfo)
4326 OS << "+Other";
4327 } else {
4328 OS << " Num: Value Size Type Bind Vis";
4329 if (ExtraSymInfo)
4330 OS << "+Other";
4331 }
4332
4333 OS.PadToColumn(NewCol: (ELFT::Is64Bits ? 56 : 48) + (NonVisibilityBitsUsed ? 13 : 0));
4334 if (ExtraSymInfo)
4335 OS << "Ndx(SecName) Name [+ Version Info]\n";
4336 else
4337 OS << "Ndx Name\n";
4338}
4339
4340template <class ELFT>
4341std::string GNUELFDumper<ELFT>::getSymbolSectionNdx(
4342 const Elf_Sym &Symbol, unsigned SymIndex, DataRegion<Elf_Word> ShndxTable,
4343 bool ExtraSymInfo) const {
4344 unsigned SectionIndex = Symbol.st_shndx;
4345 switch (SectionIndex) {
4346 case ELF::SHN_UNDEF:
4347 return "UND";
4348 case ELF::SHN_ABS:
4349 return "ABS";
4350 case ELF::SHN_COMMON:
4351 return "COM";
4352 case ELF::SHN_XINDEX: {
4353 Expected<uint32_t> IndexOrErr =
4354 object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, ShndxTable);
4355 if (!IndexOrErr) {
4356 assert(Symbol.st_shndx == SHN_XINDEX &&
4357 "getExtendedSymbolTableIndex should only fail due to an invalid "
4358 "SHT_SYMTAB_SHNDX table/reference");
4359 this->reportUniqueWarning(IndexOrErr.takeError());
4360 return "RSV[0xffff]";
4361 }
4362 SectionIndex = *IndexOrErr;
4363 break;
4364 }
4365 default:
4366 // Find if:
4367 // Processor specific
4368 if (SectionIndex >= ELF::SHN_LOPROC && SectionIndex <= ELF::SHN_HIPROC)
4369 return std::string("PRC[0x") +
4370 to_string(Value: format_hex_no_prefix(N: SectionIndex, Width: 4)) + "]";
4371 // OS specific
4372 if (SectionIndex >= ELF::SHN_LOOS && SectionIndex <= ELF::SHN_HIOS)
4373 return std::string("OS[0x") +
4374 to_string(Value: format_hex_no_prefix(N: SectionIndex, Width: 4)) + "]";
4375 // Architecture reserved:
4376 if (SectionIndex >= ELF::SHN_LORESERVE &&
4377 SectionIndex <= ELF::SHN_HIRESERVE)
4378 return std::string("RSV[0x") +
4379 to_string(Value: format_hex_no_prefix(N: SectionIndex, Width: 4)) + "]";
4380 break;
4381 }
4382
4383 std::string Extra;
4384 if (ExtraSymInfo) {
4385 auto Sec = this->Obj.getSection(SectionIndex);
4386 if (!Sec) {
4387 this->reportUniqueWarning(Sec.takeError());
4388 } else {
4389 auto SecName = this->Obj.getSectionName(**Sec);
4390 if (!SecName)
4391 this->reportUniqueWarning(SecName.takeError());
4392 else
4393 Extra = Twine(" (" + *SecName + ")").str();
4394 }
4395 }
4396 return to_string(Value: format_decimal(N: SectionIndex, Width: 3)) + Extra;
4397}
4398
4399template <class ELFT>
4400void GNUELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
4401 DataRegion<Elf_Word> ShndxTable,
4402 std::optional<StringRef> StrTable,
4403 bool IsDynamic, bool NonVisibilityBitsUsed,
4404 bool ExtraSymInfo) const {
4405 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4406 Field Fields[8] = {0, 8, 17 + Bias, 23 + Bias,
4407 31 + Bias, 38 + Bias, 48 + Bias, 51 + Bias};
4408 Fields[0].Str = to_string(Value: format_decimal(N: SymIndex, Width: 6)) + ":";
4409 Fields[1].Str =
4410 to_string(format_hex_no_prefix(Symbol.st_value, ELFT::Is64Bits ? 16 : 8));
4411 Fields[2].Str = to_string(format_decimal(Symbol.st_size, 5));
4412
4413 unsigned char SymbolType = Symbol.getType();
4414 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
4415 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
4416 Fields[3].Str = EnumStrings(AMDGPUSymbolTypes).toStringOrHex(Value: SymbolType, StrIdx: 1);
4417 else
4418 Fields[3].Str = getElfSymbolTypes().toStringOrHex(Value: SymbolType, StrIdx: 1);
4419
4420 Fields[4].Str =
4421 EnumStrings(ElfSymbolBindings).toStringOrHex(Symbol.getBinding(), 1);
4422 Fields[5].Str = EnumStrings(ElfSymbolVisibilities)
4423 .toStringOrHex(Symbol.getVisibility(), 1);
4424
4425 if (Symbol.st_other & ~0x3) {
4426 if (this->Obj.getHeader().e_machine == ELF::EM_AARCH64) {
4427 uint8_t Other = Symbol.st_other & ~0x3;
4428 if (Other & STO_AARCH64_VARIANT_PCS) {
4429 Other &= ~STO_AARCH64_VARIANT_PCS;
4430 Fields[5].Str += " [VARIANT_PCS";
4431 if (Other != 0)
4432 Fields[5].Str.append(" | " + utohexstr(X: Other, /*LowerCase=*/true));
4433 Fields[5].Str.append("]");
4434 }
4435 } else if (this->Obj.getHeader().e_machine == ELF::EM_RISCV) {
4436 uint8_t Other = Symbol.st_other & ~0x3;
4437 if (Other & STO_RISCV_VARIANT_CC) {
4438 Other &= ~STO_RISCV_VARIANT_CC;
4439 Fields[5].Str += " [VARIANT_CC";
4440 if (Other != 0)
4441 Fields[5].Str.append(" | " + utohexstr(X: Other, /*LowerCase=*/true));
4442 Fields[5].Str.append("]");
4443 }
4444 } else {
4445 Fields[5].Str +=
4446 " [<other: " + to_string(format_hex(Symbol.st_other, 2)) + ">]";
4447 }
4448 }
4449
4450 Fields[6].Column += NonVisibilityBitsUsed ? 13 : 0;
4451 Fields[6].Str =
4452 getSymbolSectionNdx(Symbol, SymIndex, ShndxTable, ExtraSymInfo);
4453
4454 Fields[7].Column += ExtraSymInfo ? 10 : 0;
4455 Fields[7].Str = this->getFullSymbolName(Symbol, SymIndex, ShndxTable,
4456 StrTable, IsDynamic);
4457 for (const Field &Entry : Fields)
4458 printField(F: Entry);
4459 OS << "\n";
4460}
4461
4462template <class ELFT>
4463void GNUELFDumper<ELFT>::printHashedSymbol(const Elf_Sym *Symbol,
4464 unsigned SymIndex,
4465 DataRegion<Elf_Word> ShndxTable,
4466 StringRef StrTable,
4467 uint32_t Bucket) {
4468 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4469 Field Fields[9] = {0, 6, 11, 20 + Bias, 25 + Bias,
4470 34 + Bias, 41 + Bias, 49 + Bias, 53 + Bias};
4471 Fields[0].Str = to_string(Value: format_decimal(N: SymIndex, Width: 5));
4472 Fields[1].Str = to_string(Value: format_decimal(N: Bucket, Width: 3)) + ":";
4473
4474 Fields[2].Str = to_string(
4475 format_hex_no_prefix(Symbol->st_value, ELFT::Is64Bits ? 16 : 8));
4476 Fields[3].Str = to_string(format_decimal(Symbol->st_size, 5));
4477
4478 unsigned char SymbolType = Symbol->getType();
4479 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
4480 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
4481 Fields[4].Str = EnumStrings(AMDGPUSymbolTypes).toString(Value: SymbolType, StrIdx: 1);
4482 else
4483 Fields[4].Str = getElfSymbolTypes().toStringOrHex(Value: SymbolType, StrIdx: 1);
4484
4485 Fields[5].Str =
4486 EnumStrings(ElfSymbolBindings).toString(Symbol->getBinding(), 1);
4487 Fields[6].Str =
4488 EnumStrings(ElfSymbolVisibilities).toString(Symbol->getVisibility(), 1);
4489 Fields[7].Str = getSymbolSectionNdx(Symbol: *Symbol, SymIndex, ShndxTable);
4490 Fields[8].Str =
4491 this->getFullSymbolName(*Symbol, SymIndex, ShndxTable, StrTable, true);
4492
4493 for (const Field &Entry : Fields)
4494 printField(F: Entry);
4495 OS << "\n";
4496}
4497
4498template <class ELFT>
4499void GNUELFDumper<ELFT>::printSymbols(bool PrintSymbols,
4500 bool PrintDynamicSymbols,
4501 bool ExtraSymInfo) {
4502 if (!PrintSymbols && !PrintDynamicSymbols)
4503 return;
4504 // GNU readelf prints both the .dynsym and .symtab with --symbols.
4505 this->printSymbolsHelper(true, ExtraSymInfo);
4506 if (PrintSymbols)
4507 this->printSymbolsHelper(false, ExtraSymInfo);
4508}
4509
4510template <class ELFT>
4511void GNUELFDumper<ELFT>::printHashTableSymbols(const Elf_Hash &SysVHash) {
4512 if (this->DynamicStringTable.empty())
4513 return;
4514
4515 if (ELFT::Is64Bits)
4516 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4517 else
4518 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4519 OS << "\n";
4520
4521 Elf_Sym_Range DynSyms = this->dynamic_symbols();
4522 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
4523 if (!FirstSym) {
4524 this->reportUniqueWarning(
4525 Twine("unable to print symbols for the .hash table: the "
4526 "dynamic symbol table ") +
4527 (this->DynSymRegion ? "is empty" : "was not found"));
4528 return;
4529 }
4530
4531 DataRegion<Elf_Word> ShndxTable(
4532 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
4533 auto Buckets = SysVHash.buckets();
4534 auto Chains = SysVHash.chains();
4535 for (uint32_t Buc = 0; Buc < SysVHash.nbucket; Buc++) {
4536 if (Buckets[Buc] == ELF::STN_UNDEF)
4537 continue;
4538 BitVector Visited(SysVHash.nchain);
4539 for (uint32_t Ch = Buckets[Buc]; Ch < SysVHash.nchain; Ch = Chains[Ch]) {
4540 if (Ch == ELF::STN_UNDEF)
4541 break;
4542
4543 if (Visited[Ch]) {
4544 this->reportUniqueWarning(".hash section is invalid: bucket " +
4545 Twine(Ch) +
4546 ": a cycle was detected in the linked chain");
4547 break;
4548 }
4549
4550 printHashedSymbol(Symbol: FirstSym + Ch, SymIndex: Ch, ShndxTable, StrTable: this->DynamicStringTable,
4551 Bucket: Buc);
4552 Visited[Ch] = true;
4553 }
4554 }
4555}
4556
4557template <class ELFT>
4558void GNUELFDumper<ELFT>::printGnuHashTableSymbols(const Elf_GnuHash &GnuHash) {
4559 if (this->DynamicStringTable.empty())
4560 return;
4561
4562 Elf_Sym_Range DynSyms = this->dynamic_symbols();
4563 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
4564 if (!FirstSym) {
4565 this->reportUniqueWarning(
4566 Twine("unable to print symbols for the .gnu.hash table: the "
4567 "dynamic symbol table ") +
4568 (this->DynSymRegion ? "is empty" : "was not found"));
4569 return;
4570 }
4571
4572 auto GetSymbol = [&](uint64_t SymIndex,
4573 uint64_t SymsTotal) -> const Elf_Sym * {
4574 if (SymIndex >= SymsTotal) {
4575 this->reportUniqueWarning(
4576 "unable to print hashed symbol with index " + Twine(SymIndex) +
4577 ", which is greater than or equal to the number of dynamic symbols "
4578 "(" +
4579 Twine::utohexstr(Val: SymsTotal) + ")");
4580 return nullptr;
4581 }
4582 return FirstSym + SymIndex;
4583 };
4584
4585 Expected<ArrayRef<Elf_Word>> ValuesOrErr =
4586 getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHash);
4587 ArrayRef<Elf_Word> Values;
4588 if (!ValuesOrErr)
4589 this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH "
4590 "section: " +
4591 toString(ValuesOrErr.takeError()));
4592 else
4593 Values = *ValuesOrErr;
4594
4595 DataRegion<Elf_Word> ShndxTable(
4596 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
4597 ArrayRef<Elf_Word> Buckets = GnuHash.buckets();
4598 for (uint32_t Buc = 0; Buc < GnuHash.nbuckets; Buc++) {
4599 if (Buckets[Buc] == ELF::STN_UNDEF)
4600 continue;
4601 uint32_t Index = Buckets[Buc];
4602 // Print whole chain.
4603 while (true) {
4604 uint32_t SymIndex = Index++;
4605 if (const Elf_Sym *Sym = GetSymbol(SymIndex, DynSyms.size()))
4606 printHashedSymbol(Symbol: Sym, SymIndex, ShndxTable, StrTable: this->DynamicStringTable,
4607 Bucket: Buc);
4608 else
4609 break;
4610
4611 if (SymIndex < GnuHash.symndx) {
4612 this->reportUniqueWarning(
4613 "unable to read the hash value for symbol with index " +
4614 Twine(SymIndex) +
4615 ", which is less than the index of the first hashed symbol (" +
4616 Twine(GnuHash.symndx) + ")");
4617 break;
4618 }
4619
4620 // Chain ends at symbol with stopper bit.
4621 if ((Values[SymIndex - GnuHash.symndx] & 1) == 1)
4622 break;
4623 }
4624 }
4625}
4626
4627template <class ELFT> void GNUELFDumper<ELFT>::printHashSymbols() {
4628 if (this->HashTable) {
4629 OS << "\n Symbol table of .hash for image:\n";
4630 if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
4631 this->reportUniqueWarning(std::move(E));
4632 else
4633 printHashTableSymbols(SysVHash: *this->HashTable);
4634 }
4635
4636 // Try printing the .gnu.hash table.
4637 if (this->GnuHashTable) {
4638 OS << "\n Symbol table of .gnu.hash for image:\n";
4639 if (ELFT::Is64Bits)
4640 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4641 else
4642 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4643 OS << "\n";
4644
4645 if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
4646 this->reportUniqueWarning(std::move(E));
4647 else
4648 printGnuHashTableSymbols(GnuHash: *this->GnuHashTable);
4649 }
4650}
4651
4652template <class ELFT> void GNUELFDumper<ELFT>::printSectionDetails() {
4653 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
4654 if (Sections.empty()) {
4655 OS << "\nThere are no sections in this file.\n";
4656 Expected<StringRef> SecStrTableOrErr =
4657 this->Obj.getSectionStringTable(Sections, this->WarningHandler);
4658 if (!SecStrTableOrErr)
4659 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4660 return;
4661 }
4662 OS << "There are " << to_string(Sections.size())
4663 << " section headers, starting at offset "
4664 << "0x" << utohexstr(this->Obj.getHeader().e_shoff, /*LowerCase=*/true) << ":\n\n";
4665
4666 OS << "Section Headers:\n";
4667
4668 auto PrintFields = [&](ArrayRef<Field> V) {
4669 for (const Field &F : V)
4670 printField(F);
4671 OS << "\n";
4672 };
4673
4674 PrintFields({{"[Nr]", 2}, {"Name", 7}});
4675
4676 constexpr bool Is64 = ELFT::Is64Bits;
4677 PrintFields({{"Type", 7},
4678 {Is64 ? "Address" : "Addr", 23},
4679 {{"Off"}, Is64 ? 40 : 32},
4680 {{"Size"}, Is64 ? 47 : 39},
4681 {{"ES"}, Is64 ? 54 : 46},
4682 {{"Lk"}, Is64 ? 59 : 51},
4683 {{"Inf"}, Is64 ? 62 : 54},
4684 {{"Al"}, Is64 ? 66 : 57}});
4685 PrintFields({{"Flags", 7}});
4686
4687 StringRef SecStrTable;
4688 if (Expected<StringRef> SecStrTableOrErr =
4689 this->Obj.getSectionStringTable(Sections, this->WarningHandler))
4690 SecStrTable = *SecStrTableOrErr;
4691 else
4692 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4693
4694 size_t SectionIndex = 0;
4695 const unsigned AddrSize = Is64 ? 16 : 8;
4696 for (const Elf_Shdr &S : Sections) {
4697 StringRef Name = "<?>";
4698 if (Expected<StringRef> NameOrErr =
4699 this->Obj.getSectionName(S, SecStrTable))
4700 Name = *NameOrErr;
4701 else
4702 this->reportUniqueWarning(NameOrErr.takeError());
4703
4704 OS.PadToColumn(NewCol: 2);
4705 OS << "[" << right_justify(Str: to_string(Value: SectionIndex), Width: 2) << "]";
4706 PrintFields({{Name, 7}});
4707 PrintFields(
4708 {{getSectionTypeString(this->Obj.getHeader().e_machine, S.sh_type), 7},
4709 {to_string(format_hex_no_prefix(S.sh_addr, AddrSize)), 23},
4710 {to_string(format_hex_no_prefix(S.sh_offset, 6)), Is64 ? 39 : 32},
4711 {to_string(format_hex_no_prefix(S.sh_size, 6)), Is64 ? 47 : 39},
4712 {to_string(format_hex_no_prefix(S.sh_entsize, 2)), Is64 ? 54 : 46},
4713 {to_string(S.sh_link), Is64 ? 59 : 51},
4714 {to_string(S.sh_info), Is64 ? 63 : 55},
4715 {to_string(S.sh_addralign), Is64 ? 66 : 58}});
4716
4717 OS.PadToColumn(NewCol: 7);
4718 OS << "[" << to_string(format_hex_no_prefix(S.sh_flags, AddrSize)) << "]: ";
4719
4720 DenseMap<unsigned, StringRef> FlagToName = {
4721 {SHF_WRITE, "WRITE"}, {SHF_ALLOC, "ALLOC"},
4722 {SHF_EXECINSTR, "EXEC"}, {SHF_MERGE, "MERGE"},
4723 {SHF_STRINGS, "STRINGS"}, {SHF_INFO_LINK, "INFO LINK"},
4724 {SHF_LINK_ORDER, "LINK ORDER"}, {SHF_OS_NONCONFORMING, "OS NONCONF"},
4725 {SHF_GROUP, "GROUP"}, {SHF_TLS, "TLS"},
4726 {SHF_COMPRESSED, "COMPRESSED"}, {SHF_EXCLUDE, "EXCLUDE"}};
4727
4728 uint64_t Flags = S.sh_flags;
4729 uint64_t UnknownFlags = 0;
4730 ListSeparator LS;
4731 while (Flags) {
4732 // Take the least significant bit as a flag.
4733 uint64_t Flag = Flags & -Flags;
4734 Flags -= Flag;
4735
4736 auto It = FlagToName.find(Val: Flag);
4737 if (It != FlagToName.end())
4738 OS << LS << It->second;
4739 else
4740 UnknownFlags |= Flag;
4741 }
4742
4743 auto PrintUnknownFlags = [&](uint64_t Mask, StringRef Name) {
4744 uint64_t FlagsToPrint = UnknownFlags & Mask;
4745 if (!FlagsToPrint)
4746 return;
4747
4748 OS << LS << Name << " ("
4749 << to_string(Value: format_hex_no_prefix(N: FlagsToPrint, Width: AddrSize)) << ")";
4750 UnknownFlags &= ~Mask;
4751 };
4752
4753 PrintUnknownFlags(SHF_MASKOS, "OS");
4754 PrintUnknownFlags(SHF_MASKPROC, "PROC");
4755 PrintUnknownFlags(uint64_t(-1), "UNKNOWN");
4756
4757 OS << "\n";
4758 ++SectionIndex;
4759
4760 if (!(S.sh_flags & SHF_COMPRESSED))
4761 continue;
4762 Expected<ArrayRef<uint8_t>> Data = this->Obj.getSectionContents(S);
4763 if (!Data || Data->size() < sizeof(Elf_Chdr)) {
4764 consumeError(Err: Data.takeError());
4765 reportWarning(createError(Err: "SHF_COMPRESSED section '" + Name +
4766 "' does not have an Elf_Chdr header"),
4767 this->FileName);
4768 OS.indent(NumSpaces: 7);
4769 OS << "[<corrupt>]";
4770 } else {
4771 OS.indent(NumSpaces: 7);
4772 auto *Chdr = reinterpret_cast<const Elf_Chdr *>(Data->data());
4773 if (Chdr->ch_type == ELFCOMPRESS_ZLIB)
4774 OS << "ZLIB";
4775 else if (Chdr->ch_type == ELFCOMPRESS_ZSTD)
4776 OS << "ZSTD";
4777 else
4778 OS << format(Fmt: "[<unknown>: 0x%x]", Vals: unsigned(Chdr->ch_type));
4779 OS << ", " << format_hex_no_prefix(Chdr->ch_size, ELFT::Is64Bits ? 16 : 8)
4780 << ", " << Chdr->ch_addralign;
4781 }
4782 OS << '\n';
4783 }
4784}
4785
4786static inline std::string printPhdrFlags(unsigned Flag) {
4787 std::string Str;
4788 Str = (Flag & PF_R) ? "R" : " ";
4789 Str += (Flag & PF_W) ? "W" : " ";
4790 Str += (Flag & PF_X) ? "E" : " ";
4791 return Str;
4792}
4793
4794template <class ELFT>
4795static bool checkTLSSections(const typename ELFT::Phdr &Phdr,
4796 const typename ELFT::Shdr &Sec) {
4797 if (Sec.sh_flags & ELF::SHF_TLS) {
4798 // .tbss must only be shown in the PT_TLS segment.
4799 if (Sec.sh_type == ELF::SHT_NOBITS)
4800 return Phdr.p_type == ELF::PT_TLS;
4801
4802 // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO
4803 // segments.
4804 return (Phdr.p_type == ELF::PT_TLS) || (Phdr.p_type == ELF::PT_LOAD) ||
4805 (Phdr.p_type == ELF::PT_GNU_RELRO);
4806 }
4807
4808 // PT_TLS must only have SHF_TLS sections.
4809 return Phdr.p_type != ELF::PT_TLS;
4810}
4811
4812template <class ELFT>
4813static bool checkPTDynamic(const typename ELFT::Phdr &Phdr,
4814 const typename ELFT::Shdr &Sec) {
4815 if (Phdr.p_type != ELF::PT_DYNAMIC || Phdr.p_memsz == 0 || Sec.sh_size != 0)
4816 return true;
4817
4818 // We get here when we have an empty section. Only non-empty sections can be
4819 // at the start or at the end of PT_DYNAMIC.
4820 // Is section within the phdr both based on offset and VMA?
4821 bool CheckOffset = (Sec.sh_type == ELF::SHT_NOBITS) ||
4822 (Sec.sh_offset > Phdr.p_offset &&
4823 Sec.sh_offset < Phdr.p_offset + Phdr.p_filesz);
4824 bool CheckVA = !(Sec.sh_flags & ELF::SHF_ALLOC) ||
4825 (Sec.sh_addr > Phdr.p_vaddr && Sec.sh_addr < Phdr.p_memsz);
4826 return CheckOffset && CheckVA;
4827}
4828
4829template <class ELFT>
4830void GNUELFDumper<ELFT>::printProgramHeaders(
4831 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
4832 bool ShouldPrintSectionMapping =
4833 (PrintSectionMapping != cl::boolOrDefault::BOU_FALSE);
4834 // Exit early if no program header or section mapping details were requested.
4835 if (!PrintProgramHeaders && !ShouldPrintSectionMapping)
4836 return;
4837
4838 if (PrintProgramHeaders) {
4839 Expected<uint32_t> PhNumOrErr = this->Obj.getPhNum();
4840 if (!PhNumOrErr) {
4841 this->reportUniqueWarning(PhNumOrErr.takeError());
4842 ShouldPrintSectionMapping = false;
4843 } else if (*PhNumOrErr == 0) {
4844 OS << "\nThere are no program headers in this file.\n";
4845 } else {
4846 printProgramHeaders();
4847 }
4848 }
4849
4850 if (ShouldPrintSectionMapping)
4851 printSectionMapping();
4852}
4853
4854template <class ELFT> void GNUELFDumper<ELFT>::printProgramHeaders() {
4855 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4856 const Elf_Ehdr &Header = this->Obj.getHeader();
4857 Field Fields[8] = {2, 17, 26, 37 + Bias,
4858 48 + Bias, 56 + Bias, 64 + Bias, 68 + Bias};
4859 uint32_t PhNum = 0;
4860 Expected<uint32_t> PhNumOrErr = this->Obj.getPhNum();
4861
4862 // The caller already performs this check, so failure is impossible.
4863 if (PhNumOrErr)
4864 PhNum = *PhNumOrErr;
4865 else
4866 cantFail(Err: PhNumOrErr.takeError());
4867
4868 OS << "\nElf file type is "
4869 << EnumStrings(ElfObjectFileType).toStringOrHex(Header.e_type, 1) << "\n"
4870 << "Entry point " << format_hex(Header.e_entry, 3) << "\n"
4871 << "There are " << PhNum << " program headers,"
4872 << " starting at offset " << Header.e_phoff << "\n\n"
4873 << "Program Headers:\n";
4874 if (ELFT::Is64Bits)
4875 OS << " Type Offset VirtAddr PhysAddr "
4876 << " FileSiz MemSiz Flg Align\n";
4877 else
4878 OS << " Type Offset VirtAddr PhysAddr FileSiz "
4879 << "MemSiz Flg Align\n";
4880
4881 unsigned Width = ELFT::Is64Bits ? 18 : 10;
4882 unsigned SizeWidth = ELFT::Is64Bits ? 8 : 7;
4883
4884 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4885 if (!PhdrsOrErr) {
4886 this->reportUniqueWarning("unable to dump program headers: " +
4887 toString(PhdrsOrErr.takeError()));
4888 return;
4889 }
4890
4891 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4892 Fields[0].Str = getGNUPtType(Header.e_machine, Phdr.p_type);
4893 Fields[1].Str = to_string(format_hex(Phdr.p_offset, 8));
4894 Fields[2].Str = to_string(format_hex(Phdr.p_vaddr, Width));
4895 Fields[3].Str = to_string(format_hex(Phdr.p_paddr, Width));
4896 Fields[4].Str = to_string(format_hex(Phdr.p_filesz, SizeWidth));
4897 Fields[5].Str = to_string(format_hex(Phdr.p_memsz, SizeWidth));
4898 Fields[6].Str = printPhdrFlags(Phdr.p_flags);
4899 Fields[7].Str = to_string(format_hex(Phdr.p_align, 1));
4900 for (const Field &F : Fields)
4901 printField(F);
4902 if (Phdr.p_type == ELF::PT_INTERP) {
4903 OS << "\n";
4904 auto ReportBadInterp = [&](const Twine &Msg) {
4905 this->reportUniqueWarning(
4906 "unable to read program interpreter name at offset 0x" +
4907 Twine::utohexstr(Val: Phdr.p_offset) + ": " + Msg);
4908 };
4909
4910 if (Phdr.p_offset >= this->Obj.getBufSize()) {
4911 ReportBadInterp("it goes past the end of the file (0x" +
4912 Twine::utohexstr(Val: this->Obj.getBufSize()) + ")");
4913 continue;
4914 }
4915
4916 const char *Data =
4917 reinterpret_cast<const char *>(this->Obj.base()) + Phdr.p_offset;
4918 size_t MaxSize = this->Obj.getBufSize() - Phdr.p_offset;
4919 size_t Len = strnlen(string: Data, maxlen: MaxSize);
4920 if (Len == MaxSize) {
4921 ReportBadInterp("it is not null-terminated");
4922 continue;
4923 }
4924
4925 OS << " [Requesting program interpreter: ";
4926 OS << StringRef(Data, Len) << "]";
4927 }
4928 OS << "\n";
4929 }
4930}
4931
4932template <class ELFT> void GNUELFDumper<ELFT>::printSectionMapping() {
4933 OS << "\n Section to Segment mapping:\n Segment Sections...\n";
4934 DenseSet<const Elf_Shdr *> BelongsToSegment;
4935 int Phnum = 0;
4936
4937 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4938 if (!PhdrsOrErr) {
4939 this->reportUniqueWarning(
4940 "can't read program headers to build section to segment mapping: " +
4941 toString(PhdrsOrErr.takeError()));
4942 return;
4943 }
4944
4945 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4946 std::string Sections;
4947 OS << format(Fmt: " %2.2d ", Vals: Phnum++);
4948 // Check if each section is in a segment and then print mapping.
4949 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4950 if (Sec.sh_type == ELF::SHT_NULL)
4951 continue;
4952
4953 // readelf additionally makes sure it does not print zero sized sections
4954 // at end of segments and for PT_DYNAMIC both start and end of section
4955 // .tbss must only be shown in PT_TLS section.
4956 if (isSectionInSegment<ELFT>(Phdr, Sec) &&
4957 checkTLSSections<ELFT>(Phdr, Sec) &&
4958 checkPTDynamic<ELFT>(Phdr, Sec)) {
4959 Sections +=
4960 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4961 " ";
4962 BelongsToSegment.insert(&Sec);
4963 }
4964 }
4965 OS << Sections << "\n";
4966 OS.flush();
4967 }
4968
4969 // Display sections that do not belong to a segment.
4970 std::string Sections;
4971 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4972 if (BelongsToSegment.find(&Sec) == BelongsToSegment.end())
4973 Sections +=
4974 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4975 ' ';
4976 }
4977 if (!Sections.empty()) {
4978 OS << " None " << Sections << '\n';
4979 OS.flush();
4980 }
4981}
4982
4983namespace {
4984
4985template <class ELFT>
4986RelSymbol<ELFT> getSymbolForReloc(const ELFDumper<ELFT> &Dumper,
4987 const Relocation<ELFT> &Reloc) {
4988 using Elf_Sym = typename ELFT::Sym;
4989 auto WarnAndReturn = [&](const Elf_Sym *Sym,
4990 const Twine &Reason) -> RelSymbol<ELFT> {
4991 Dumper.reportUniqueWarning(
4992 "unable to get name of the dynamic symbol with index " +
4993 Twine(Reloc.Symbol) + ": " + Reason);
4994 return {Sym, "<corrupt>"};
4995 };
4996
4997 ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols();
4998 const Elf_Sym *FirstSym = Symbols.begin();
4999 if (!FirstSym)
5000 return WarnAndReturn(nullptr, "no dynamic symbol table found");
5001
5002 // We might have an object without a section header. In this case the size of
5003 // Symbols is zero, because there is no way to know the size of the dynamic
5004 // table. We should allow this case and not print a warning.
5005 if (!Symbols.empty() && Reloc.Symbol >= Symbols.size())
5006 return WarnAndReturn(
5007 nullptr,
5008 "index is greater than or equal to the number of dynamic symbols (" +
5009 Twine(Symbols.size()) + ")");
5010
5011 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
5012 const uint64_t FileSize = Obj.getBufSize();
5013 const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) +
5014 (uint64_t)Reloc.Symbol * sizeof(Elf_Sym);
5015 if (SymOffset + sizeof(Elf_Sym) > FileSize)
5016 return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(Val: SymOffset) +
5017 " goes past the end of the file (0x" +
5018 Twine::utohexstr(Val: FileSize) + ")");
5019
5020 const Elf_Sym *Sym = FirstSym + Reloc.Symbol;
5021 Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable());
5022 if (!ErrOrName)
5023 return WarnAndReturn(Sym, toString(E: ErrOrName.takeError()));
5024
5025 return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(Name: *ErrOrName)};
5026}
5027} // namespace
5028
5029template <class ELFT>
5030static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj,
5031 typename ELFT::DynRange Tags) {
5032 size_t Max = 0;
5033 for (const typename ELFT::Dyn &Dyn : Tags)
5034 Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size());
5035 return Max;
5036}
5037
5038template <class ELFT> void GNUELFDumper<ELFT>::printDynamicTable() {
5039 Elf_Dyn_Range Table = this->dynamic_table();
5040 if (Table.empty())
5041 return;
5042
5043 OS << "Dynamic section at offset "
5044 << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable.Addr) -
5045 this->Obj.base(),
5046 1)
5047 << " contains " << Table.size() << " entries:\n";
5048
5049 // The type name is surrounded with round brackets, hence add 2.
5050 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2;
5051 // The "Name/Value" column should be indented from the "Type" column by N
5052 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
5053 // space (1) = 3.
5054 OS << " Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type"
5055 << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
5056
5057 std::string ValueFmt = " %-" + std::to_string(val: MaxTagSize) + "s ";
5058 for (auto Entry : Table) {
5059 uintX_t Tag = Entry.getTag();
5060 std::string Type =
5061 std::string("(") + this->Obj.getDynamicTagAsString(Tag) + ")";
5062 std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
5063 OS << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10)
5064 << format(Fmt: ValueFmt.c_str(), Vals: Type.c_str()) << Value << "\n";
5065 }
5066}
5067
5068template <class ELFT> void GNUELFDumper<ELFT>::printDynamicRelocations() {
5069 this->printDynamicRelocationsHelper();
5070}
5071
5072template <class ELFT>
5073void ELFDumper<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) {
5074 printRelRelaReloc(R, RelSym: getSymbolForReloc(*this, R));
5075}
5076
5077template <class ELFT>
5078void ELFDumper<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) {
5079 this->forEachRelocationDo(
5080 Sec, RelRelaFn: [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
5081 const Elf_Shdr *SymTab) { printReloc(R, RelIndex: Ndx, Sec, SymTab); });
5082}
5083
5084template <class ELFT> void ELFDumper<ELFT>::printDynamicRelocationsHelper() {
5085 const bool IsMips64EL = this->Obj.isMips64EL();
5086 auto DumpCrelRegion = [&](DynRegionInfo &Region) {
5087 // While the size is unknown, a valid CREL has at least one byte. We can
5088 // check whether Addr is in bounds, and then decode CREL until the file
5089 // end.
5090 Region.Size = Region.EntSize = 1;
5091 if (!Region.template getAsArrayRef<uint8_t>().empty()) {
5092 const uint64_t Offset =
5093 Region.Addr - reinterpret_cast<const uint8_t *>(
5094 ObjF.getMemoryBufferRef().getBufferStart());
5095 const uint64_t ObjSize = ObjF.getMemoryBufferRef().getBufferSize();
5096 auto RelsOrRelas =
5097 Obj.decodeCrel(ArrayRef<uint8_t>(Region.Addr, ObjSize - Offset));
5098 if (!RelsOrRelas) {
5099 reportUniqueWarning(toString(RelsOrRelas.takeError()));
5100 } else {
5101 for (const Elf_Rel &R : RelsOrRelas->first)
5102 printDynamicReloc(R: Relocation<ELFT>(R, false));
5103 for (const Elf_Rela &R : RelsOrRelas->second)
5104 printDynamicReloc(R: Relocation<ELFT>(R, false));
5105 }
5106 }
5107 };
5108
5109 if (this->DynCrelRegion.Addr) {
5110 printDynamicRelocHeader(Type: ELF::SHT_CREL, Name: "CREL", Reg: this->DynCrelRegion);
5111 DumpCrelRegion(this->DynCrelRegion);
5112 }
5113
5114 if (this->DynRelaRegion.Size > 0) {
5115 printDynamicRelocHeader(Type: ELF::SHT_RELA, Name: "RELA", Reg: this->DynRelaRegion);
5116 for (const Elf_Rela &Rela :
5117 this->DynRelaRegion.template getAsArrayRef<Elf_Rela>())
5118 printDynamicReloc(R: Relocation<ELFT>(Rela, IsMips64EL));
5119 }
5120
5121 if (this->DynRelRegion.Size > 0) {
5122 printDynamicRelocHeader(Type: ELF::SHT_REL, Name: "REL", Reg: this->DynRelRegion);
5123 for (const Elf_Rel &Rel :
5124 this->DynRelRegion.template getAsArrayRef<Elf_Rel>())
5125 printDynamicReloc(R: Relocation<ELFT>(Rel, IsMips64EL));
5126 }
5127
5128 if (this->DynRelrRegion.Size > 0) {
5129 printDynamicRelocHeader(Type: ELF::SHT_REL, Name: "RELR", Reg: this->DynRelrRegion);
5130 Elf_Relr_Range Relrs =
5131 this->DynRelrRegion.template getAsArrayRef<Elf_Relr>();
5132 for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs))
5133 printDynamicReloc(R: Relocation<ELFT>(Rel, IsMips64EL));
5134 }
5135
5136 if (this->DynPLTRelRegion.Size) {
5137 if (this->DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) {
5138 printDynamicRelocHeader(Type: ELF::SHT_RELA, Name: "PLT", Reg: this->DynPLTRelRegion);
5139 for (const Elf_Rela &Rela :
5140 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rela>())
5141 printDynamicReloc(R: Relocation<ELFT>(Rela, IsMips64EL));
5142 } else if (this->DynPLTRelRegion.EntSize == 1) {
5143 DumpCrelRegion(this->DynPLTRelRegion);
5144 } else {
5145 printDynamicRelocHeader(Type: ELF::SHT_REL, Name: "PLT", Reg: this->DynPLTRelRegion);
5146 for (const Elf_Rel &Rel :
5147 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rel>())
5148 printDynamicReloc(R: Relocation<ELFT>(Rel, IsMips64EL));
5149 }
5150 }
5151}
5152
5153template <class ELFT>
5154void GNUELFDumper<ELFT>::printGNUVersionSectionProlog(
5155 const typename ELFT::Shdr &Sec, const Twine &Label, unsigned EntriesNum) {
5156 // Don't inline the SecName, because it might report a warning to stderr and
5157 // corrupt the output.
5158 StringRef SecName = this->getPrintableSectionName(Sec);
5159 OS << Label << " section '" << SecName << "' "
5160 << "contains " << EntriesNum << " entries:\n";
5161
5162 StringRef LinkedSecName = "<corrupt>";
5163 if (Expected<const typename ELFT::Shdr *> LinkedSecOrErr =
5164 this->Obj.getSection(Sec.sh_link))
5165 LinkedSecName = this->getPrintableSectionName(**LinkedSecOrErr);
5166 else
5167 this->reportUniqueWarning("invalid section linked to " +
5168 this->describe(Sec) + ": " +
5169 toString(LinkedSecOrErr.takeError()));
5170
5171 OS << " Addr: " << format_hex_no_prefix(Sec.sh_addr, 16)
5172 << " Offset: " << format_hex(Sec.sh_offset, 8)
5173 << " Link: " << Sec.sh_link << " (" << LinkedSecName << ")\n";
5174}
5175
5176template <class ELFT>
5177void GNUELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
5178 if (!Sec)
5179 return;
5180
5181 printGNUVersionSectionProlog(Sec: *Sec, Label: "Version symbols",
5182 EntriesNum: Sec->sh_size / sizeof(Elf_Versym));
5183 Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
5184 this->getVersionTable(*Sec, /*SymTab=*/nullptr,
5185 /*StrTab=*/nullptr, /*SymTabSec=*/nullptr);
5186 if (!VerTableOrErr) {
5187 this->reportUniqueWarning(VerTableOrErr.takeError());
5188 return;
5189 }
5190
5191 SmallVector<std::optional<VersionEntry>, 0> *VersionMap = nullptr;
5192 if (Expected<SmallVector<std::optional<VersionEntry>, 0> *> MapOrErr =
5193 this->getVersionMap())
5194 VersionMap = *MapOrErr;
5195 else
5196 this->reportUniqueWarning(MapOrErr.takeError());
5197
5198 ArrayRef<Elf_Versym> VerTable = *VerTableOrErr;
5199 std::vector<StringRef> Versions;
5200 for (size_t I = 0, E = VerTable.size(); I < E; ++I) {
5201 unsigned Ndx = VerTable[I].vs_index;
5202 if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) {
5203 Versions.emplace_back(args: Ndx == VER_NDX_LOCAL ? "*local*" : "*global*");
5204 continue;
5205 }
5206
5207 if (!VersionMap) {
5208 Versions.emplace_back(args: "<corrupt>");
5209 continue;
5210 }
5211
5212 bool IsDefault;
5213 Expected<StringRef> NameOrErr = this->Obj.getSymbolVersionByIndex(
5214 Ndx, IsDefault, *VersionMap, /*IsSymHidden=*/std::nullopt);
5215 if (!NameOrErr) {
5216 this->reportUniqueWarning("unable to get a version for entry " +
5217 Twine(I) + " of " + this->describe(*Sec) +
5218 ": " + toString(E: NameOrErr.takeError()));
5219 Versions.emplace_back(args: "<corrupt>");
5220 continue;
5221 }
5222 Versions.emplace_back(args&: *NameOrErr);
5223 }
5224
5225 // readelf prints 4 entries per line.
5226 uint64_t Entries = VerTable.size();
5227 for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) {
5228 OS << " " << format_hex_no_prefix(N: VersymRow, Width: 3) << ":";
5229 for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) {
5230 unsigned Ndx = VerTable[VersymRow + I].vs_index;
5231 OS << format(Fmt: "%4x%c", Vals: Ndx & VERSYM_VERSION,
5232 Vals: Ndx & VERSYM_HIDDEN ? 'h' : ' ');
5233 OS << left_justify(Str: "(" + std::string(Versions[VersymRow + I]) + ")", Width: 13);
5234 }
5235 OS << '\n';
5236 }
5237 OS << '\n';
5238}
5239
5240static std::string versionFlagToString(unsigned Flags) {
5241 if (Flags == 0)
5242 return "none";
5243
5244 std::string Ret;
5245 auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) {
5246 if (!(Flags & Flag))
5247 return;
5248 if (!Ret.empty())
5249 Ret += " | ";
5250 Ret += Name;
5251 Flags &= ~Flag;
5252 };
5253
5254 AddFlag(VER_FLG_BASE, "BASE");
5255 AddFlag(VER_FLG_WEAK, "WEAK");
5256 AddFlag(VER_FLG_INFO, "INFO");
5257 AddFlag(~0, "<unknown>");
5258 return Ret;
5259}
5260
5261template <class ELFT>
5262void GNUELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
5263 if (!Sec)
5264 return;
5265
5266 printGNUVersionSectionProlog(Sec: *Sec, Label: "Version definition", EntriesNum: Sec->sh_info);
5267
5268 Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
5269 if (!V) {
5270 this->reportUniqueWarning(V.takeError());
5271 return;
5272 }
5273
5274 for (const VerDef &Def : *V) {
5275 OS << format(Fmt: " 0x%04x: Rev: %u Flags: %s Index: %u Cnt: %u Name: %s\n",
5276 Vals: Def.Offset, Vals: Def.Version,
5277 Vals: versionFlagToString(Flags: Def.Flags).c_str(), Vals: Def.Ndx, Vals: Def.Cnt,
5278 Vals: Def.Name.data());
5279 unsigned I = 0;
5280 for (const VerdAux &Aux : Def.AuxV)
5281 OS << format(Fmt: " 0x%04x: Parent %u: %s\n", Vals: Aux.Offset, Vals: ++I,
5282 Vals: Aux.Name.data());
5283 }
5284
5285 OS << '\n';
5286}
5287
5288template <class ELFT>
5289void GNUELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
5290 if (!Sec)
5291 return;
5292
5293 unsigned VerneedNum = Sec->sh_info;
5294 printGNUVersionSectionProlog(Sec: *Sec, Label: "Version needs", EntriesNum: VerneedNum);
5295
5296 Expected<std::vector<VerNeed>> V =
5297 this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
5298 if (!V) {
5299 this->reportUniqueWarning(V.takeError());
5300 return;
5301 }
5302
5303 for (const VerNeed &VN : *V) {
5304 OS << format(Fmt: " 0x%04x: Version: %u File: %s Cnt: %u\n", Vals: VN.Offset,
5305 Vals: VN.Version, Vals: VN.File.data(), Vals: VN.Cnt);
5306 for (const VernAux &Aux : VN.AuxV)
5307 OS << format(Fmt: " 0x%04x: Name: %s Flags: %s Version: %u\n", Vals: Aux.Offset,
5308 Vals: Aux.Name.data(), Vals: versionFlagToString(Flags: Aux.Flags).c_str(),
5309 Vals: Aux.Other);
5310 }
5311 OS << '\n';
5312}
5313
5314template <class ELFT>
5315void GNUELFDumper<ELFT>::printHashHistogramStats(size_t NBucket,
5316 size_t MaxChain,
5317 size_t TotalSyms,
5318 ArrayRef<size_t> Count,
5319 bool IsGnu) const {
5320 size_t CumulativeNonZero = 0;
5321 OS << "Histogram for" << (IsGnu ? " `.gnu.hash'" : "")
5322 << " bucket list length (total of " << NBucket << " buckets)\n"
5323 << " Length Number % of total Coverage\n";
5324 for (size_t I = 0; I < MaxChain; ++I) {
5325 CumulativeNonZero += Count[I] * I;
5326 OS << format(Fmt: "%7lu %-10lu (%5.1f%%) %5.1f%%\n", Vals: I, Vals: Count[I],
5327 Vals: (Count[I] * 100.0) / NBucket,
5328 Vals: (CumulativeNonZero * 100.0) / TotalSyms);
5329 }
5330}
5331
5332template <class ELFT> void GNUELFDumper<ELFT>::printCGProfile() {
5333 OS << "GNUStyle::printCGProfile not implemented\n";
5334}
5335
5336template <class ELFT>
5337SmallVector<FunctionCallgraphInfo, 16>
5338ELFDumper<ELFT>::processCallGraphSection(const Elf_Shdr *CGSection) {
5339 SmallVector<FunctionCallgraphInfo, 16> FuncCGInfos;
5340 ArrayRef<uint8_t> Contents = cantFail(Obj.getSectionContents(*CGSection));
5341 DataExtractor Data(Contents, Obj.isLE());
5342 DataExtractor::Cursor C(0);
5343 uint64_t UnknownCount = 0;
5344 while (C && C.tell() < CGSection->sh_size) {
5345 uint8_t FormatVersionNumber = Data.getU8(C);
5346 assert(C && "always expect the one byte read to succeed when C.tell() < "
5347 "CGSection->sh_size is true.");
5348 if (FormatVersionNumber != 0) {
5349 reportWarning(Err: createError(Err: "unknown format version value [" +
5350 std::to_string(val: FormatVersionNumber) +
5351 "] in SHT_LLVM_CALL_GRAPH type section"),
5352 Input: FileName);
5353 return {};
5354 }
5355
5356 uint8_t FlagsVal = Data.getU8(C);
5357 if (!C) {
5358 reportWarning(
5359 Err: createError(Err: "failed while reading call graph info's Flags: " +
5360 toString(E: C.takeError())),
5361 Input: FileName);
5362 return {};
5363 }
5364 callgraph::Flags CGFlags = static_cast<callgraph::Flags>(FlagsVal);
5365 constexpr callgraph::Flags ValidFlags = callgraph::IsIndirectTarget |
5366 callgraph::HasDirectCallees |
5367 callgraph::HasIndirectCallees;
5368 constexpr uint8_t ValidMask = static_cast<uint8_t>(ValidFlags);
5369 if ((FlagsVal & ~ValidMask) != 0) {
5370 reportWarning(Err: createError(Err: "unsupported Flags value [" +
5371 std::to_string(val: FlagsVal) + "] "),
5372 Input: FileName);
5373 return {};
5374 }
5375
5376 uint64_t FuncAddrOffset = C.tell();
5377 uint64_t FuncAddr =
5378 static_cast<uint64_t>(Data.getUnsigned(C, Size: sizeof(typename ELFT::uint)));
5379 if (!C) {
5380 reportWarning(
5381 Err: createError(
5382 Err: "failed while reading call graph info function entry PC: " +
5383 toString(E: C.takeError())),
5384 Input: FileName);
5385 return {};
5386 }
5387
5388 bool IsETREL = this->Obj.getHeader().e_type == ELF::ET_REL;
5389 // Create a new entry for this function.
5390 FunctionCallgraphInfo CGInfo;
5391 CGInfo.FunctionAddress = IsETREL ? FuncAddrOffset : FuncAddr;
5392 CGInfo.FormatVersionNumber = FormatVersionNumber;
5393 bool IsIndirectTarget =
5394 (CGFlags & callgraph::IsIndirectTarget) != callgraph::None;
5395 CGInfo.IsIndirectTarget = IsIndirectTarget;
5396 uint64_t TypeID = Data.getU64(C);
5397 if (!C) {
5398 reportWarning(Err: createError(Err: "failed while reading function type ID: " +
5399 toString(E: C.takeError())),
5400 Input: FileName);
5401 return {};
5402 }
5403 CGInfo.FunctionTypeID = TypeID;
5404 if (IsIndirectTarget && TypeID == 0)
5405 ++UnknownCount;
5406
5407 if (CGFlags & callgraph::HasDirectCallees) {
5408 // Read number of direct call sites for this function.
5409 uint64_t NumDirectCallees = Data.getULEB128(C);
5410 if (!C) {
5411 reportWarning(
5412 Err: createError(Err: "failed while reading number of direct callees: " +
5413 toString(E: C.takeError())),
5414 Input: FileName);
5415 return {};
5416 }
5417 // Read unique direct callees and populate FuncCGInfos.
5418 for (uint64_t I = 0; I < NumDirectCallees; ++I) {
5419 uint64_t CalleeOffset = C.tell();
5420 uint64_t Callee = static_cast<uint64_t>(
5421 Data.getUnsigned(C, Size: sizeof(typename ELFT::uint)));
5422 if (!C) {
5423 reportWarning(Err: createError(Err: "failed while reading direct callee: " +
5424 toString(E: C.takeError())),
5425 Input: FileName);
5426 return {};
5427 }
5428 CGInfo.DirectCallees.insert(V: (IsETREL ? CalleeOffset : Callee));
5429 }
5430 }
5431
5432 if (CGFlags & callgraph::HasIndirectCallees) {
5433 uint64_t NumIndirectTargetTypeIDs = Data.getULEB128(C);
5434 if (!C) {
5435 reportWarning(
5436 Err: createError(
5437 Err: "failed while reading number of indirect target type IDs: " +
5438 toString(E: C.takeError())),
5439 Input: FileName);
5440 return {};
5441 }
5442 // Read unique indirect target type IDs and populate FuncCGInfos.
5443 for (uint64_t I = 0; I < NumIndirectTargetTypeIDs; ++I) {
5444 uint64_t TargetType = Data.getU64(C);
5445 if (!C) {
5446 reportWarning(
5447 Err: createError(Err: "failed while reading indirect target type ID: " +
5448 toString(E: C.takeError())),
5449 Input: FileName);
5450 return {};
5451 }
5452 CGInfo.IndirectTypeIDs.insert(V: TargetType);
5453 }
5454 }
5455 FuncCGInfos.push_back(Elt: CGInfo);
5456 }
5457
5458 if (UnknownCount)
5459 reportUniqueWarning(
5460 "SHT_LLVM_CALL_GRAPH type section has unknown type ID for " +
5461 Twine(UnknownCount) + " indirect targets");
5462 return FuncCGInfos;
5463}
5464
5465template <class ELFT>
5466void GNUELFDumper<ELFT>::printBBAddrMaps(bool /*PrettyPGOAnalysis*/) {
5467 OS << "GNUStyle::printBBAddrMaps not implemented\n";
5468}
5469
5470static Expected<std::vector<uint64_t>> toULEB128Array(ArrayRef<uint8_t> Data) {
5471 std::vector<uint64_t> Ret;
5472 const uint8_t *Cur = Data.begin();
5473 const uint8_t *End = Data.end();
5474 while (Cur != End) {
5475 unsigned Size;
5476 const char *Err = nullptr;
5477 Ret.push_back(x: decodeULEB128(p: Cur, n: &Size, end: End, error: &Err));
5478 if (Err)
5479 return createError(Err);
5480 Cur += Size;
5481 }
5482 return Ret;
5483}
5484
5485template <class ELFT>
5486static Expected<std::vector<uint64_t>>
5487decodeAddrsigSection(const ELFFile<ELFT> &Obj, const typename ELFT::Shdr &Sec) {
5488 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Sec);
5489 if (!ContentsOrErr)
5490 return ContentsOrErr.takeError();
5491
5492 if (Expected<std::vector<uint64_t>> SymsOrErr =
5493 toULEB128Array(Data: *ContentsOrErr))
5494 return *SymsOrErr;
5495 else
5496 return createError("unable to decode " + describe(Obj, Sec) + ": " +
5497 toString(E: SymsOrErr.takeError()));
5498}
5499
5500template <class ELFT> void GNUELFDumper<ELFT>::printAddrsig() {
5501 if (!this->DotAddrsigSec)
5502 return;
5503
5504 Expected<std::vector<uint64_t>> SymsOrErr =
5505 decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
5506 if (!SymsOrErr) {
5507 this->reportUniqueWarning(SymsOrErr.takeError());
5508 return;
5509 }
5510
5511 StringRef Name = this->getPrintableSectionName(*this->DotAddrsigSec);
5512 OS << "\nAddress-significant symbols section '" << Name << "'"
5513 << " contains " << SymsOrErr->size() << " entries:\n";
5514 OS << " Num: Name\n";
5515
5516 Field Fields[2] = {0, 8};
5517 size_t SymIndex = 0;
5518 for (uint64_t Sym : *SymsOrErr) {
5519 Fields[0].Str = to_string(Value: format_decimal(N: ++SymIndex, Width: 6)) + ":";
5520 Fields[1].Str = this->getStaticSymbolName(Sym);
5521 for (const Field &Entry : Fields)
5522 printField(F: Entry);
5523 OS << "\n";
5524 }
5525}
5526
5527template <class ELFT>
5528static bool printAArch64PAuthABICoreInfo(raw_ostream &OS, uint32_t DataSize,
5529 ArrayRef<uint8_t> Desc) {
5530 OS << " AArch64 PAuth ABI core info: ";
5531 // DataSize - size without padding, Desc.size() - size with padding
5532 if (DataSize != 16) {
5533 OS << format(Fmt: "<corrupted size: expected 16, got %d>", Vals: DataSize);
5534 return false;
5535 }
5536
5537 uint64_t Platform =
5538 support::endian::read64<ELFT::Endianness>(Desc.data() + 0);
5539 uint64_t Version = support::endian::read64<ELFT::Endianness>(Desc.data() + 8);
5540
5541 const char *PlatformDesc = [Platform]() {
5542 switch (Platform) {
5543 case AARCH64_PAUTH_PLATFORM_INVALID:
5544 return "invalid";
5545 case AARCH64_PAUTH_PLATFORM_BAREMETAL:
5546 return "baremetal";
5547 case AARCH64_PAUTH_PLATFORM_LLVM_LINUX:
5548 return "llvm_linux";
5549 default:
5550 return "unknown";
5551 }
5552 }();
5553
5554 std::string VersionDesc = [Platform, Version]() -> std::string {
5555 if (Platform != AARCH64_PAUTH_PLATFORM_LLVM_LINUX)
5556 return "";
5557 if (Version >= (1 << (AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST + 1)))
5558 return "unknown";
5559
5560 std::array<StringRef, AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST + 1>
5561 Flags;
5562 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS] = "Intrinsics";
5563 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS] = "Calls";
5564 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS] = "Returns";
5565 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS] = "AuthTraps";
5566 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR] =
5567 "VTPtrAddressDiscrimination";
5568 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR] =
5569 "VTPtrTypeDiscrimination";
5570 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI] = "InitFini";
5571 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC] =
5572 "InitFiniAddressDiscrimination";
5573 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT] = "ELFGOT";
5574 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS] = "IndirectGotos";
5575 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR] =
5576 "TypeInfoVTPtrDiscrimination";
5577 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR] =
5578 "FPtrTypeDiscrimination";
5579
5580 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
5581 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
5582 "Update when new enum items are defined");
5583
5584 std::string Desc;
5585 for (uint32_t I = 0, End = Flags.size(); I < End; ++I) {
5586 if (!(Version & (1ULL << I)))
5587 Desc += '!';
5588 Desc +=
5589 Twine("PointerAuth" + Flags[I] + (I == End - 1 ? "" : ", ")).str();
5590 }
5591 return Desc;
5592 }();
5593
5594 OS << format(Fmt: "platform 0x%" PRIx64 " (%s), version 0x%" PRIx64, Vals: Platform,
5595 Vals: PlatformDesc, Vals: Version);
5596 if (!VersionDesc.empty())
5597 OS << format(Fmt: " (%s)", Vals: VersionDesc.c_str());
5598
5599 return true;
5600}
5601
5602template <typename ELFT>
5603static std::string getGNUProperty(uint32_t Type, uint32_t DataSize,
5604 ArrayRef<uint8_t> Data,
5605 typename ELFT::Half EMachine) {
5606 std::string str;
5607 raw_string_ostream OS(str);
5608 uint32_t PrData;
5609 auto DumpBit = [&](uint32_t Flag, StringRef Name) {
5610 if (PrData & Flag) {
5611 PrData &= ~Flag;
5612 OS << Name;
5613 if (PrData)
5614 OS << ", ";
5615 }
5616 };
5617
5618 switch (Type) {
5619 default:
5620 OS << format(Fmt: "<application-specific type 0x%x>", Vals: Type);
5621 return str;
5622 case GNU_PROPERTY_STACK_SIZE: {
5623 OS << "stack size: ";
5624 if (DataSize == sizeof(typename ELFT::uint))
5625 OS << formatv(Fmt: "{0:x}",
5626 Vals: (uint64_t)(*(const typename ELFT::Addr *)Data.data()));
5627 else
5628 OS << format(Fmt: "<corrupt length: 0x%x>", Vals: DataSize);
5629 return str;
5630 }
5631 case GNU_PROPERTY_NO_COPY_ON_PROTECTED:
5632 OS << "no copy on protected";
5633 if (DataSize)
5634 OS << format(Fmt: " <corrupt length: 0x%x>", Vals: DataSize);
5635 return str;
5636 case GNU_PROPERTY_AARCH64_FEATURE_1_AND:
5637 case GNU_PROPERTY_X86_FEATURE_1_AND:
5638 static_assert(GNU_PROPERTY_AARCH64_FEATURE_1_AND ==
5639 GNU_PROPERTY_RISCV_FEATURE_1_AND,
5640 "GNU_PROPERTY_RISCV_FEATURE_1_AND should equal "
5641 "GNU_PROPERTY_AARCH64_FEATURE_1_AND, otherwise "
5642 "GNU_PROPERTY_RISCV_FEATURE_1_AND would be skipped!");
5643
5644 if (EMachine == EM_AARCH64 && Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) {
5645 OS << "aarch64 feature: ";
5646 } else if (EMachine == EM_RISCV &&
5647 Type == GNU_PROPERTY_RISCV_FEATURE_1_AND) {
5648 OS << "RISC-V feature: ";
5649 } else if ((EMachine == EM_386 || EMachine == EM_X86_64) &&
5650 Type == GNU_PROPERTY_X86_FEATURE_1_AND) {
5651 OS << "x86 feature: ";
5652 } else {
5653 OS << format(Fmt: "<application-specific type 0x%x>", Vals: Type);
5654 return str;
5655 }
5656
5657 if (DataSize != 4) {
5658 OS << format(Fmt: "<corrupt length: 0x%x>", Vals: DataSize);
5659 return str;
5660 }
5661 PrData = endian::read32<ELFT::Endianness>(Data.data());
5662 if (PrData == 0) {
5663 OS << "<None>";
5664 return str;
5665 }
5666
5667 if (EMachine == EM_AARCH64) {
5668 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI, "BTI");
5669 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC, "PAC");
5670 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_GCS, "GCS");
5671 } else if (EMachine == EM_RISCV) {
5672 DumpBit(GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_UNLABELED,
5673 "ZICFILP-unlabeled");
5674 DumpBit(GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS, "ZICFISS");
5675 DumpBit(GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_FUNC_SIG, "ZICFILP-func-sig");
5676 } else {
5677 DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT, "IBT");
5678 DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK, "SHSTK");
5679 }
5680 if (PrData)
5681 OS << format(Fmt: "<unknown flags: 0x%x>", Vals: PrData);
5682 return str;
5683 case GNU_PROPERTY_AARCH64_FEATURE_PAUTH:
5684 printAArch64PAuthABICoreInfo<ELFT>(OS, DataSize, Data);
5685 return str;
5686 case GNU_PROPERTY_X86_FEATURE_2_NEEDED:
5687 case GNU_PROPERTY_X86_FEATURE_2_USED:
5688 OS << "x86 feature "
5689 << (Type == GNU_PROPERTY_X86_FEATURE_2_NEEDED ? "needed: " : "used: ");
5690 if (DataSize != 4) {
5691 OS << format(Fmt: "<corrupt length: 0x%x>", Vals: DataSize);
5692 return str;
5693 }
5694 PrData = endian::read32<ELFT::Endianness>(Data.data());
5695 if (PrData == 0) {
5696 OS << "<None>";
5697 return str;
5698 }
5699 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86, "x86");
5700 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87, "x87");
5701 DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX, "MMX");
5702 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM, "XMM");
5703 DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM, "YMM");
5704 DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM, "ZMM");
5705 DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR, "FXSR");
5706 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE, "XSAVE");
5707 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT, "XSAVEOPT");
5708 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC, "XSAVEC");
5709 if (PrData)
5710 OS << format(Fmt: "<unknown flags: 0x%x>", Vals: PrData);
5711 return str;
5712 case GNU_PROPERTY_X86_ISA_1_NEEDED:
5713 case GNU_PROPERTY_X86_ISA_1_USED:
5714 OS << "x86 ISA "
5715 << (Type == GNU_PROPERTY_X86_ISA_1_NEEDED ? "needed: " : "used: ");
5716 if (DataSize != 4) {
5717 OS << format(Fmt: "<corrupt length: 0x%x>", Vals: DataSize);
5718 return str;
5719 }
5720 PrData = endian::read32<ELFT::Endianness>(Data.data());
5721 if (PrData == 0) {
5722 OS << "<None>";
5723 return str;
5724 }
5725 DumpBit(GNU_PROPERTY_X86_ISA_1_BASELINE, "x86-64-baseline");
5726 DumpBit(GNU_PROPERTY_X86_ISA_1_V2, "x86-64-v2");
5727 DumpBit(GNU_PROPERTY_X86_ISA_1_V3, "x86-64-v3");
5728 DumpBit(GNU_PROPERTY_X86_ISA_1_V4, "x86-64-v4");
5729 if (PrData)
5730 OS << format(Fmt: "<unknown flags: 0x%x>", Vals: PrData);
5731 return str;
5732 }
5733}
5734
5735template <typename ELFT>
5736static SmallVector<std::string, 4>
5737getGNUPropertyList(ArrayRef<uint8_t> Arr, typename ELFT::Half EMachine) {
5738 using Elf_Word = typename ELFT::Word;
5739
5740 SmallVector<std::string, 4> Properties;
5741 while (Arr.size() >= 8) {
5742 uint32_t Type = *reinterpret_cast<const Elf_Word *>(Arr.data());
5743 uint32_t DataSize = *reinterpret_cast<const Elf_Word *>(Arr.data() + 4);
5744 Arr = Arr.drop_front(N: 8);
5745
5746 // Take padding size into account if present.
5747 uint64_t PaddedSize = alignTo(Value: DataSize, Align: sizeof(typename ELFT::uint));
5748 std::string str;
5749 raw_string_ostream OS(str);
5750 if (Arr.size() < PaddedSize) {
5751 OS << format(Fmt: "<corrupt type (0x%x) datasz: 0x%x>", Vals: Type, Vals: DataSize);
5752 Properties.push_back(Elt: str);
5753 break;
5754 }
5755 Properties.push_back(getGNUProperty<ELFT>(
5756 Type, DataSize, Arr.take_front(N: PaddedSize), EMachine));
5757 Arr = Arr.drop_front(N: PaddedSize);
5758 }
5759
5760 if (!Arr.empty())
5761 Properties.push_back(Elt: "<corrupted GNU_PROPERTY_TYPE_0>");
5762
5763 return Properties;
5764}
5765
5766struct GNUAbiTag {
5767 std::string OSName;
5768 std::string ABI;
5769 bool IsValid;
5770};
5771
5772template <typename ELFT> static GNUAbiTag getGNUAbiTag(ArrayRef<uint8_t> Desc) {
5773 typedef typename ELFT::Word Elf_Word;
5774
5775 ArrayRef<Elf_Word> Words(reinterpret_cast<const Elf_Word *>(Desc.begin()),
5776 reinterpret_cast<const Elf_Word *>(Desc.end()));
5777
5778 if (Words.size() < 4)
5779 return {.OSName: "", .ABI: "", /*IsValid=*/false};
5780
5781 static const char *OSNames[] = {
5782 "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable",
5783 };
5784 StringRef OSName = "Unknown";
5785 if (Words[0] < std::size(OSNames))
5786 OSName = OSNames[Words[0]];
5787 uint32_t Major = Words[1], Minor = Words[2], Patch = Words[3];
5788 std::string str;
5789 raw_string_ostream ABI(str);
5790 ABI << Major << "." << Minor << "." << Patch;
5791 return {.OSName: std::string(OSName), .ABI: str, /*IsValid=*/true};
5792}
5793
5794static std::string getGNUBuildId(ArrayRef<uint8_t> Desc) {
5795 std::string str;
5796 raw_string_ostream OS(str);
5797 for (uint8_t B : Desc)
5798 OS << format_hex_no_prefix(N: B, Width: 2);
5799 return str;
5800}
5801
5802static StringRef getDescAsStringRef(ArrayRef<uint8_t> Desc) {
5803 return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
5804}
5805
5806template <typename ELFT>
5807static bool printGNUNote(raw_ostream &OS, uint32_t NoteType,
5808 ArrayRef<uint8_t> Desc, typename ELFT::Half EMachine) {
5809 // Return true if we were able to pretty-print the note, false otherwise.
5810 switch (NoteType) {
5811 default:
5812 return false;
5813 case ELF::NT_GNU_ABI_TAG: {
5814 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
5815 if (!AbiTag.IsValid)
5816 OS << " <corrupt GNU_ABI_TAG>";
5817 else
5818 OS << " OS: " << AbiTag.OSName << ", ABI: " << AbiTag.ABI;
5819 break;
5820 }
5821 case ELF::NT_GNU_BUILD_ID: {
5822 OS << " Build ID: " << getGNUBuildId(Desc);
5823 break;
5824 }
5825 case ELF::NT_GNU_GOLD_VERSION:
5826 OS << " Version: " << getDescAsStringRef(Desc);
5827 break;
5828 case ELF::NT_GNU_PROPERTY_TYPE_0:
5829 OS << " Properties:";
5830 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc, EMachine))
5831 OS << " " << Property << "\n";
5832 break;
5833 }
5834 OS << '\n';
5835 return true;
5836}
5837
5838using AndroidNoteProperties = std::vector<std::pair<StringRef, std::string>>;
5839static AndroidNoteProperties getAndroidNoteProperties(uint32_t NoteType,
5840 ArrayRef<uint8_t> Desc) {
5841 AndroidNoteProperties Props;
5842 switch (NoteType) {
5843 case ELF::NT_ANDROID_TYPE_MEMTAG:
5844 if (Desc.empty()) {
5845 Props.emplace_back(args: "Invalid .note.android.memtag", args: "");
5846 return Props;
5847 }
5848
5849 switch (Desc[0] & NT_MEMTAG_LEVEL_MASK) {
5850 case NT_MEMTAG_LEVEL_NONE:
5851 Props.emplace_back(args: "Tagging Mode", args: "NONE");
5852 break;
5853 case NT_MEMTAG_LEVEL_ASYNC:
5854 Props.emplace_back(args: "Tagging Mode", args: "ASYNC");
5855 break;
5856 case NT_MEMTAG_LEVEL_SYNC:
5857 Props.emplace_back(args: "Tagging Mode", args: "SYNC");
5858 break;
5859 default:
5860 Props.emplace_back(
5861 args: "Tagging Mode",
5862 args: ("Unknown (" + Twine::utohexstr(Val: Desc[0] & NT_MEMTAG_LEVEL_MASK) + ")")
5863 .str());
5864 break;
5865 }
5866 Props.emplace_back(args: "Heap",
5867 args: (Desc[0] & NT_MEMTAG_HEAP) ? "Enabled" : "Disabled");
5868 Props.emplace_back(args: "Stack",
5869 args: (Desc[0] & NT_MEMTAG_STACK) ? "Enabled" : "Disabled");
5870 break;
5871 default:
5872 return Props;
5873 }
5874 return Props;
5875}
5876
5877static bool printAndroidNote(raw_ostream &OS, uint32_t NoteType,
5878 ArrayRef<uint8_t> Desc) {
5879 // Return true if we were able to pretty-print the note, false otherwise.
5880 AndroidNoteProperties Props = getAndroidNoteProperties(NoteType, Desc);
5881 if (Props.empty())
5882 return false;
5883 for (const auto &KV : Props)
5884 OS << " " << KV.first << ": " << KV.second << '\n';
5885 return true;
5886}
5887
5888template <class ELFT>
5889void GNUELFDumper<ELFT>::printMemtag(
5890 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
5891 const ArrayRef<uint8_t> AndroidNoteDesc,
5892 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) {
5893 OS << "Memtag Dynamic Entries:\n";
5894 if (DynamicEntries.empty())
5895 OS << " < none found >\n";
5896 for (const auto &DynamicEntryKV : DynamicEntries)
5897 OS << " " << DynamicEntryKV.first << ": " << DynamicEntryKV.second
5898 << "\n";
5899
5900 if (!AndroidNoteDesc.empty()) {
5901 OS << "Memtag Android Note:\n";
5902 printAndroidNote(OS, NoteType: ELF::NT_ANDROID_TYPE_MEMTAG, Desc: AndroidNoteDesc);
5903 }
5904
5905 if (Descriptors.empty())
5906 return;
5907
5908 OS << "Memtag Global Descriptors:\n";
5909 for (const auto &[Addr, BytesToTag] : Descriptors) {
5910 OS << " 0x" << utohexstr(X: Addr, /*LowerCase=*/true) << ": 0x"
5911 << utohexstr(X: BytesToTag, /*LowerCase=*/true) << "\n";
5912 }
5913}
5914
5915template <typename ELFT>
5916static bool printLLVMOMPOFFLOADNote(raw_ostream &OS, uint32_t NoteType,
5917 ArrayRef<uint8_t> Desc) {
5918 switch (NoteType) {
5919 default:
5920 return false;
5921 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
5922 OS << " Version: " << getDescAsStringRef(Desc);
5923 break;
5924 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
5925 OS << " Producer: " << getDescAsStringRef(Desc);
5926 break;
5927 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
5928 OS << " Producer version: " << getDescAsStringRef(Desc);
5929 break;
5930 }
5931 OS << '\n';
5932 return true;
5933}
5934
5935constexpr EnumStringDef<unsigned> FreeBSDFeatureCtlFlagsDefs[] = {
5936 {.Names: {"ASLR_DISABLE"}, .Value: NT_FREEBSD_FCTL_ASLR_DISABLE},
5937 {.Names: {"PROTMAX_DISABLE"}, .Value: NT_FREEBSD_FCTL_PROTMAX_DISABLE},
5938 {.Names: {"STKGAP_DISABLE"}, .Value: NT_FREEBSD_FCTL_STKGAP_DISABLE},
5939 {.Names: {"WXNEEDED"}, .Value: NT_FREEBSD_FCTL_WXNEEDED},
5940 {.Names: {"LA48"}, .Value: NT_FREEBSD_FCTL_LA48},
5941 {.Names: {"ASG_DISABLE"}, .Value: NT_FREEBSD_FCTL_ASG_DISABLE},
5942};
5943constexpr auto FreeBSDFeatureCtlFlags =
5944 BUILD_ENUM_STRINGS(FreeBSDFeatureCtlFlagsDefs);
5945
5946struct FreeBSDNote {
5947 std::string Type;
5948 std::string Value;
5949};
5950
5951template <typename ELFT>
5952static std::optional<FreeBSDNote>
5953getFreeBSDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc, bool IsCore) {
5954 if (IsCore)
5955 return std::nullopt; // No pretty-printing yet.
5956 switch (NoteType) {
5957 case ELF::NT_FREEBSD_ABI_TAG:
5958 if (Desc.size() != 4)
5959 return std::nullopt;
5960 return FreeBSDNote{"ABI tag",
5961 utostr(endian::read32<ELFT::Endianness>(Desc.data()))};
5962 case ELF::NT_FREEBSD_ARCH_TAG:
5963 return FreeBSDNote{.Type: "Arch tag", .Value: toStringRef(Input: Desc).str()};
5964 case ELF::NT_FREEBSD_FEATURE_CTL: {
5965 if (Desc.size() != 4)
5966 return std::nullopt;
5967 unsigned Value = endian::read32<ELFT::Endianness>(Desc.data());
5968 std::string FlagsStr;
5969 raw_string_ostream OS(FlagsStr);
5970 printFlags(Value, Flags: EnumStrings(FreeBSDFeatureCtlFlags), OS);
5971 if (FlagsStr.empty())
5972 OS << "0x" << utohexstr(X: Value, /*LowerCase=*/true);
5973 else
5974 OS << "(0x" << utohexstr(X: Value, /*LowerCase=*/true) << ")";
5975 return FreeBSDNote{.Type: "Feature flags", .Value: FlagsStr};
5976 }
5977 default:
5978 return std::nullopt;
5979 }
5980}
5981
5982struct AMDNote {
5983 std::string Type;
5984 std::string Value;
5985};
5986
5987template <typename ELFT>
5988static AMDNote getAMDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
5989 switch (NoteType) {
5990 default:
5991 return {.Type: "", .Value: ""};
5992 case ELF::NT_AMD_HSA_CODE_OBJECT_VERSION: {
5993 struct CodeObjectVersion {
5994 support::aligned_ulittle32_t MajorVersion;
5995 support::aligned_ulittle32_t MinorVersion;
5996 };
5997 if (Desc.size() != sizeof(CodeObjectVersion))
5998 return {.Type: "AMD HSA Code Object Version",
5999 .Value: "Invalid AMD HSA Code Object Version"};
6000 std::string VersionString;
6001 raw_string_ostream StrOS(VersionString);
6002 auto Version = reinterpret_cast<const CodeObjectVersion *>(Desc.data());
6003 StrOS << "[Major: " << Version->MajorVersion
6004 << ", Minor: " << Version->MinorVersion << "]";
6005 return {.Type: "AMD HSA Code Object Version", .Value: VersionString};
6006 }
6007 case ELF::NT_AMD_HSA_HSAIL: {
6008 struct HSAILProperties {
6009 support::aligned_ulittle32_t HSAILMajorVersion;
6010 support::aligned_ulittle32_t HSAILMinorVersion;
6011 uint8_t Profile;
6012 uint8_t MachineModel;
6013 uint8_t DefaultFloatRound;
6014 };
6015 if (Desc.size() != sizeof(HSAILProperties))
6016 return {.Type: "AMD HSA HSAIL Properties", .Value: "Invalid AMD HSA HSAIL Properties"};
6017 auto Properties = reinterpret_cast<const HSAILProperties *>(Desc.data());
6018 std::string HSAILPropetiesString;
6019 raw_string_ostream StrOS(HSAILPropetiesString);
6020 StrOS << "[HSAIL Major: " << Properties->HSAILMajorVersion
6021 << ", HSAIL Minor: " << Properties->HSAILMinorVersion
6022 << ", Profile: " << uint32_t(Properties->Profile)
6023 << ", Machine Model: " << uint32_t(Properties->MachineModel)
6024 << ", Default Float Round: "
6025 << uint32_t(Properties->DefaultFloatRound) << "]";
6026 return {.Type: "AMD HSA HSAIL Properties", .Value: HSAILPropetiesString};
6027 }
6028 case ELF::NT_AMD_HSA_ISA_VERSION: {
6029 struct IsaVersion {
6030 support::aligned_ulittle16_t VendorNameSize;
6031 support::aligned_ulittle16_t ArchitectureNameSize;
6032 support::aligned_ulittle32_t Major;
6033 support::aligned_ulittle32_t Minor;
6034 support::aligned_ulittle32_t Stepping;
6035 };
6036 if (Desc.size() < sizeof(IsaVersion))
6037 return {.Type: "AMD HSA ISA Version", .Value: "Invalid AMD HSA ISA Version"};
6038 auto Isa = reinterpret_cast<const IsaVersion *>(Desc.data());
6039 if (Desc.size() < sizeof(IsaVersion) +
6040 Isa->VendorNameSize + Isa->ArchitectureNameSize ||
6041 Isa->VendorNameSize == 0 || Isa->ArchitectureNameSize == 0)
6042 return {.Type: "AMD HSA ISA Version", .Value: "Invalid AMD HSA ISA Version"};
6043 std::string IsaString;
6044 raw_string_ostream StrOS(IsaString);
6045 StrOS << "[Vendor: "
6046 << StringRef((const char*)Desc.data() + sizeof(IsaVersion), Isa->VendorNameSize - 1)
6047 << ", Architecture: "
6048 << StringRef((const char*)Desc.data() + sizeof(IsaVersion) + Isa->VendorNameSize,
6049 Isa->ArchitectureNameSize - 1)
6050 << ", Major: " << Isa->Major << ", Minor: " << Isa->Minor
6051 << ", Stepping: " << Isa->Stepping << "]";
6052 return {.Type: "AMD HSA ISA Version", .Value: IsaString};
6053 }
6054 case ELF::NT_AMD_HSA_METADATA: {
6055 if (Desc.size() == 0)
6056 return {.Type: "AMD HSA Metadata", .Value: ""};
6057 return {
6058 .Type: "AMD HSA Metadata",
6059 .Value: std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size() - 1)};
6060 }
6061 case ELF::NT_AMD_HSA_ISA_NAME: {
6062 if (Desc.size() == 0)
6063 return {.Type: "AMD HSA ISA Name", .Value: ""};
6064 return {
6065 .Type: "AMD HSA ISA Name",
6066 .Value: std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
6067 }
6068 case ELF::NT_AMD_PAL_METADATA: {
6069 struct PALMetadata {
6070 support::aligned_ulittle32_t Key;
6071 support::aligned_ulittle32_t Value;
6072 };
6073 if (Desc.size() % sizeof(PALMetadata) != 0)
6074 return {.Type: "AMD PAL Metadata", .Value: "Invalid AMD PAL Metadata"};
6075 auto Isa = reinterpret_cast<const PALMetadata *>(Desc.data());
6076 std::string MetadataString;
6077 raw_string_ostream StrOS(MetadataString);
6078 for (size_t I = 0, E = Desc.size() / sizeof(PALMetadata); I < E; ++I) {
6079 StrOS << "[" << Isa[I].Key << ": " << Isa[I].Value << "]";
6080 }
6081 return {.Type: "AMD PAL Metadata", .Value: MetadataString};
6082 }
6083 }
6084}
6085
6086struct AMDGPUNote {
6087 std::string Type;
6088 std::string Value;
6089};
6090
6091template <typename ELFT>
6092static AMDGPUNote getAMDGPUNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
6093 switch (NoteType) {
6094 default:
6095 return {.Type: "", .Value: ""};
6096 case ELF::NT_AMDGPU_METADATA: {
6097 StringRef MsgPackString =
6098 StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
6099 msgpack::Document MsgPackDoc;
6100 if (!MsgPackDoc.readFromBlob(Blob: MsgPackString, /*Multi=*/false))
6101 return {.Type: "", .Value: ""};
6102
6103 std::string MetadataString;
6104
6105 // FIXME: Metadata Verifier only works with AMDHSA.
6106 // This is an ugly workaround to avoid the verifier for other MD
6107 // formats (e.g. amdpal)
6108 if (MsgPackString.contains(Other: "amdhsa.")) {
6109 AMDGPU::HSAMD::V3::MetadataVerifier Verifier(true);
6110 if (!Verifier.verify(HSAMetadataRoot&: MsgPackDoc.getRoot()))
6111 MetadataString = "Invalid AMDGPU Metadata\n";
6112 }
6113
6114 raw_string_ostream StrOS(MetadataString);
6115 if (MsgPackDoc.getRoot().isScalar()) {
6116 // TODO: passing a scalar root to toYAML() asserts:
6117 // (PolymorphicTraits<T>::getKind(Val) != NodeKind::Scalar &&
6118 // "plain scalar documents are not supported")
6119 // To avoid this crash we print the raw data instead.
6120 return {.Type: "", .Value: ""};
6121 }
6122 MsgPackDoc.toYAML(OS&: StrOS);
6123 return {.Type: "AMDGPU Metadata", .Value: MetadataString};
6124 }
6125 }
6126}
6127
6128struct CoreFileMapping {
6129 uint64_t Start, End, Offset;
6130 StringRef Filename;
6131};
6132
6133struct CoreNote {
6134 uint64_t PageSize;
6135 std::vector<CoreFileMapping> Mappings;
6136};
6137
6138static Expected<CoreNote> readCoreNote(DataExtractor Desc,
6139 unsigned AddressSize) {
6140 // Expected format of the NT_FILE note description:
6141 // 1. # of file mappings (call it N)
6142 // 2. Page size
6143 // 3. N (start, end, offset) triples
6144 // 4. N packed filenames (null delimited)
6145 // Each field is an Elf_Addr, except for filenames which are char* strings.
6146
6147 CoreNote Ret;
6148
6149 if (!Desc.isValidOffsetForDataOfSize(offset: 2, length: AddressSize))
6150 return createError(Err: "the note of size 0x" + Twine::utohexstr(Val: Desc.size()) +
6151 " is too short, expected at least 0x" +
6152 Twine::utohexstr(Val: AddressSize * 2));
6153 if (Desc.getData().back() != 0)
6154 return createError(Err: "the note is not NUL terminated");
6155
6156 uint64_t DescOffset = 0;
6157 uint64_t FileCount = Desc.getUnsigned(offset_ptr: &DescOffset, byte_size: AddressSize);
6158 Ret.PageSize = Desc.getUnsigned(offset_ptr: &DescOffset, byte_size: AddressSize);
6159
6160 if (!Desc.isValidOffsetForDataOfSize(offset: 3 * FileCount * AddressSize,
6161 length: AddressSize))
6162 return createError(Err: "unable to read file mappings (found " +
6163 Twine(FileCount) + "): the note of size 0x" +
6164 Twine::utohexstr(Val: Desc.size()) + " is too short");
6165
6166 uint64_t FilenamesOffset = 0;
6167 DataExtractor Filenames(
6168 Desc.getData().drop_front(N: DescOffset + 3 * FileCount * AddressSize),
6169 Desc.isLittleEndian());
6170
6171 Ret.Mappings.resize(new_size: FileCount);
6172 size_t I = 0;
6173 for (CoreFileMapping &Mapping : Ret.Mappings) {
6174 ++I;
6175 if (!Filenames.isValidOffsetForDataOfSize(offset: FilenamesOffset, length: 1))
6176 return createError(
6177 Err: "unable to read the file name for the mapping with index " +
6178 Twine(I) + ": the note of size 0x" + Twine::utohexstr(Val: Desc.size()) +
6179 " is truncated");
6180 Mapping.Start = Desc.getUnsigned(offset_ptr: &DescOffset, byte_size: AddressSize);
6181 Mapping.End = Desc.getUnsigned(offset_ptr: &DescOffset, byte_size: AddressSize);
6182 Mapping.Offset = Desc.getUnsigned(offset_ptr: &DescOffset, byte_size: AddressSize);
6183 Mapping.Filename = Filenames.getCStrRef(OffsetPtr: &FilenamesOffset);
6184 }
6185
6186 return Ret;
6187}
6188
6189template <typename ELFT>
6190static void printCoreNote(raw_ostream &OS, const CoreNote &Note) {
6191 // Length of "0x<address>" string.
6192 const int FieldWidth = ELFT::Is64Bits ? 18 : 10;
6193
6194 OS << " Page size: " << format_decimal(N: Note.PageSize, Width: 0) << '\n';
6195 OS << " " << right_justify(Str: "Start", Width: FieldWidth) << " "
6196 << right_justify(Str: "End", Width: FieldWidth) << " "
6197 << right_justify(Str: "Page Offset", Width: FieldWidth) << '\n';
6198 for (const CoreFileMapping &Mapping : Note.Mappings) {
6199 OS << " " << format_hex(N: Mapping.Start, Width: FieldWidth) << " "
6200 << format_hex(N: Mapping.End, Width: FieldWidth) << " "
6201 << format_hex(N: Mapping.Offset, Width: FieldWidth) << "\n "
6202 << Mapping.Filename << '\n';
6203 }
6204}
6205
6206const NoteType GenericNoteTypes[] = {
6207 {.ID: ELF::NT_VERSION, .Name: "NT_VERSION (version)"},
6208 {.ID: ELF::NT_ARCH, .Name: "NT_ARCH (architecture)"},
6209 {.ID: ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN, .Name: "OPEN"},
6210 {.ID: ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC, .Name: "func"},
6211};
6212
6213const NoteType GNUNoteTypes[] = {
6214 {.ID: ELF::NT_GNU_ABI_TAG, .Name: "NT_GNU_ABI_TAG (ABI version tag)"},
6215 {.ID: ELF::NT_GNU_HWCAP, .Name: "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"},
6216 {.ID: ELF::NT_GNU_BUILD_ID, .Name: "NT_GNU_BUILD_ID (unique build ID bitstring)"},
6217 {.ID: ELF::NT_GNU_GOLD_VERSION, .Name: "NT_GNU_GOLD_VERSION (gold version)"},
6218 {.ID: ELF::NT_GNU_PROPERTY_TYPE_0, .Name: "NT_GNU_PROPERTY_TYPE_0 (property note)"},
6219};
6220
6221const NoteType FreeBSDCoreNoteTypes[] = {
6222 {.ID: ELF::NT_FREEBSD_THRMISC, .Name: "NT_THRMISC (thrmisc structure)"},
6223 {.ID: ELF::NT_FREEBSD_PROCSTAT_PROC, .Name: "NT_PROCSTAT_PROC (proc data)"},
6224 {.ID: ELF::NT_FREEBSD_PROCSTAT_FILES, .Name: "NT_PROCSTAT_FILES (files data)"},
6225 {.ID: ELF::NT_FREEBSD_PROCSTAT_VMMAP, .Name: "NT_PROCSTAT_VMMAP (vmmap data)"},
6226 {.ID: ELF::NT_FREEBSD_PROCSTAT_GROUPS, .Name: "NT_PROCSTAT_GROUPS (groups data)"},
6227 {.ID: ELF::NT_FREEBSD_PROCSTAT_UMASK, .Name: "NT_PROCSTAT_UMASK (umask data)"},
6228 {.ID: ELF::NT_FREEBSD_PROCSTAT_RLIMIT, .Name: "NT_PROCSTAT_RLIMIT (rlimit data)"},
6229 {.ID: ELF::NT_FREEBSD_PROCSTAT_OSREL, .Name: "NT_PROCSTAT_OSREL (osreldate data)"},
6230 {.ID: ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS,
6231 .Name: "NT_PROCSTAT_PSSTRINGS (ps_strings data)"},
6232 {.ID: ELF::NT_FREEBSD_PROCSTAT_AUXV, .Name: "NT_PROCSTAT_AUXV (auxv data)"},
6233};
6234
6235const NoteType FreeBSDNoteTypes[] = {
6236 {.ID: ELF::NT_FREEBSD_ABI_TAG, .Name: "NT_FREEBSD_ABI_TAG (ABI version tag)"},
6237 {.ID: ELF::NT_FREEBSD_NOINIT_TAG, .Name: "NT_FREEBSD_NOINIT_TAG (no .init tag)"},
6238 {.ID: ELF::NT_FREEBSD_ARCH_TAG, .Name: "NT_FREEBSD_ARCH_TAG (architecture tag)"},
6239 {.ID: ELF::NT_FREEBSD_FEATURE_CTL,
6240 .Name: "NT_FREEBSD_FEATURE_CTL (FreeBSD feature control)"},
6241};
6242
6243const NoteType NetBSDCoreNoteTypes[] = {
6244 {.ID: ELF::NT_NETBSDCORE_PROCINFO,
6245 .Name: "NT_NETBSDCORE_PROCINFO (procinfo structure)"},
6246 {.ID: ELF::NT_NETBSDCORE_AUXV, .Name: "NT_NETBSDCORE_AUXV (ELF auxiliary vector data)"},
6247 {.ID: ELF::NT_NETBSDCORE_LWPSTATUS, .Name: "PT_LWPSTATUS (ptrace_lwpstatus structure)"},
6248};
6249
6250const NoteType OpenBSDCoreNoteTypes[] = {
6251 {.ID: ELF::NT_OPENBSD_PROCINFO, .Name: "NT_OPENBSD_PROCINFO (procinfo structure)"},
6252 {.ID: ELF::NT_OPENBSD_AUXV, .Name: "NT_OPENBSD_AUXV (ELF auxiliary vector data)"},
6253 {.ID: ELF::NT_OPENBSD_REGS, .Name: "NT_OPENBSD_REGS (regular registers)"},
6254 {.ID: ELF::NT_OPENBSD_FPREGS, .Name: "NT_OPENBSD_FPREGS (floating point registers)"},
6255 {.ID: ELF::NT_OPENBSD_WCOOKIE, .Name: "NT_OPENBSD_WCOOKIE (window cookie)"},
6256};
6257
6258const NoteType AMDNoteTypes[] = {
6259 {.ID: ELF::NT_AMD_HSA_CODE_OBJECT_VERSION,
6260 .Name: "NT_AMD_HSA_CODE_OBJECT_VERSION (AMD HSA Code Object Version)"},
6261 {.ID: ELF::NT_AMD_HSA_HSAIL, .Name: "NT_AMD_HSA_HSAIL (AMD HSA HSAIL Properties)"},
6262 {.ID: ELF::NT_AMD_HSA_ISA_VERSION, .Name: "NT_AMD_HSA_ISA_VERSION (AMD HSA ISA Version)"},
6263 {.ID: ELF::NT_AMD_HSA_METADATA, .Name: "NT_AMD_HSA_METADATA (AMD HSA Metadata)"},
6264 {.ID: ELF::NT_AMD_HSA_ISA_NAME, .Name: "NT_AMD_HSA_ISA_NAME (AMD HSA ISA Name)"},
6265 {.ID: ELF::NT_AMD_PAL_METADATA, .Name: "NT_AMD_PAL_METADATA (AMD PAL Metadata)"},
6266};
6267
6268const NoteType AMDGPUNoteTypes[] = {
6269 {.ID: ELF::NT_AMDGPU_METADATA, .Name: "NT_AMDGPU_METADATA (AMDGPU Metadata)"},
6270};
6271
6272const NoteType LLVMOMPOFFLOADNoteTypes[] = {
6273 {.ID: ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION,
6274 .Name: "NT_LLVM_OPENMP_OFFLOAD_VERSION (image format version)"},
6275 {.ID: ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER,
6276 .Name: "NT_LLVM_OPENMP_OFFLOAD_PRODUCER (producing toolchain)"},
6277 {.ID: ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION,
6278 .Name: "NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION (producing toolchain version)"},
6279};
6280
6281const NoteType AndroidNoteTypes[] = {
6282 {.ID: ELF::NT_ANDROID_TYPE_IDENT, .Name: "NT_ANDROID_TYPE_IDENT"},
6283 {.ID: ELF::NT_ANDROID_TYPE_KUSER, .Name: "NT_ANDROID_TYPE_KUSER"},
6284 {.ID: ELF::NT_ANDROID_TYPE_MEMTAG,
6285 .Name: "NT_ANDROID_TYPE_MEMTAG (Android memory tagging information)"},
6286};
6287
6288const NoteType CoreNoteTypes[] = {
6289 {.ID: ELF::NT_PRSTATUS, .Name: "NT_PRSTATUS (prstatus structure)"},
6290 {.ID: ELF::NT_FPREGSET, .Name: "NT_FPREGSET (floating point registers)"},
6291 {.ID: ELF::NT_PRPSINFO, .Name: "NT_PRPSINFO (prpsinfo structure)"},
6292 {.ID: ELF::NT_TASKSTRUCT, .Name: "NT_TASKSTRUCT (task structure)"},
6293 {.ID: ELF::NT_AUXV, .Name: "NT_AUXV (auxiliary vector)"},
6294 {.ID: ELF::NT_PSTATUS, .Name: "NT_PSTATUS (pstatus structure)"},
6295 {.ID: ELF::NT_FPREGS, .Name: "NT_FPREGS (floating point registers)"},
6296 {.ID: ELF::NT_PSINFO, .Name: "NT_PSINFO (psinfo structure)"},
6297 {.ID: ELF::NT_LWPSTATUS, .Name: "NT_LWPSTATUS (lwpstatus_t structure)"},
6298 {.ID: ELF::NT_LWPSINFO, .Name: "NT_LWPSINFO (lwpsinfo_t structure)"},
6299 {.ID: ELF::NT_WIN32PSTATUS, .Name: "NT_WIN32PSTATUS (win32_pstatus structure)"},
6300
6301 {.ID: ELF::NT_PPC_VMX, .Name: "NT_PPC_VMX (ppc Altivec registers)"},
6302 {.ID: ELF::NT_PPC_VSX, .Name: "NT_PPC_VSX (ppc VSX registers)"},
6303 {.ID: ELF::NT_PPC_TAR, .Name: "NT_PPC_TAR (ppc TAR register)"},
6304 {.ID: ELF::NT_PPC_PPR, .Name: "NT_PPC_PPR (ppc PPR register)"},
6305 {.ID: ELF::NT_PPC_DSCR, .Name: "NT_PPC_DSCR (ppc DSCR register)"},
6306 {.ID: ELF::NT_PPC_EBB, .Name: "NT_PPC_EBB (ppc EBB registers)"},
6307 {.ID: ELF::NT_PPC_PMU, .Name: "NT_PPC_PMU (ppc PMU registers)"},
6308 {.ID: ELF::NT_PPC_TM_CGPR, .Name: "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"},
6309 {.ID: ELF::NT_PPC_TM_CFPR,
6310 .Name: "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"},
6311 {.ID: ELF::NT_PPC_TM_CVMX,
6312 .Name: "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"},
6313 {.ID: ELF::NT_PPC_TM_CVSX, .Name: "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"},
6314 {.ID: ELF::NT_PPC_TM_SPR, .Name: "NT_PPC_TM_SPR (ppc TM special purpose registers)"},
6315 {.ID: ELF::NT_PPC_TM_CTAR, .Name: "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"},
6316 {.ID: ELF::NT_PPC_TM_CPPR, .Name: "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"},
6317 {.ID: ELF::NT_PPC_TM_CDSCR, .Name: "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"},
6318
6319 {.ID: ELF::NT_386_TLS, .Name: "NT_386_TLS (x86 TLS information)"},
6320 {.ID: ELF::NT_386_IOPERM, .Name: "NT_386_IOPERM (x86 I/O permissions)"},
6321 {.ID: ELF::NT_X86_XSTATE, .Name: "NT_X86_XSTATE (x86 XSAVE extended state)"},
6322
6323 {.ID: ELF::NT_S390_HIGH_GPRS, .Name: "NT_S390_HIGH_GPRS (s390 upper register halves)"},
6324 {.ID: ELF::NT_S390_TIMER, .Name: "NT_S390_TIMER (s390 timer register)"},
6325 {.ID: ELF::NT_S390_TODCMP, .Name: "NT_S390_TODCMP (s390 TOD comparator register)"},
6326 {.ID: ELF::NT_S390_TODPREG, .Name: "NT_S390_TODPREG (s390 TOD programmable register)"},
6327 {.ID: ELF::NT_S390_CTRS, .Name: "NT_S390_CTRS (s390 control registers)"},
6328 {.ID: ELF::NT_S390_PREFIX, .Name: "NT_S390_PREFIX (s390 prefix register)"},
6329 {.ID: ELF::NT_S390_LAST_BREAK,
6330 .Name: "NT_S390_LAST_BREAK (s390 last breaking event address)"},
6331 {.ID: ELF::NT_S390_SYSTEM_CALL,
6332 .Name: "NT_S390_SYSTEM_CALL (s390 system call restart data)"},
6333 {.ID: ELF::NT_S390_TDB, .Name: "NT_S390_TDB (s390 transaction diagnostic block)"},
6334 {.ID: ELF::NT_S390_VXRS_LOW,
6335 .Name: "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"},
6336 {.ID: ELF::NT_S390_VXRS_HIGH, .Name: "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"},
6337 {.ID: ELF::NT_S390_GS_CB, .Name: "NT_S390_GS_CB (s390 guarded-storage registers)"},
6338 {.ID: ELF::NT_S390_GS_BC,
6339 .Name: "NT_S390_GS_BC (s390 guarded-storage broadcast control)"},
6340
6341 {.ID: ELF::NT_ARM_VFP, .Name: "NT_ARM_VFP (arm VFP registers)"},
6342 {.ID: ELF::NT_ARM_TLS, .Name: "NT_ARM_TLS (AArch TLS registers)"},
6343 {.ID: ELF::NT_ARM_HW_BREAK,
6344 .Name: "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"},
6345 {.ID: ELF::NT_ARM_HW_WATCH,
6346 .Name: "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"},
6347 {.ID: ELF::NT_ARM_SVE, .Name: "NT_ARM_SVE (AArch64 SVE registers)"},
6348 {.ID: ELF::NT_ARM_PAC_MASK,
6349 .Name: "NT_ARM_PAC_MASK (AArch64 Pointer Authentication code masks)"},
6350 {.ID: ELF::NT_ARM_TAGGED_ADDR_CTRL,
6351 .Name: "NT_ARM_TAGGED_ADDR_CTRL (AArch64 Tagged Address Control)"},
6352 {.ID: ELF::NT_ARM_SSVE, .Name: "NT_ARM_SSVE (AArch64 Streaming SVE registers)"},
6353 {.ID: ELF::NT_ARM_ZA, .Name: "NT_ARM_ZA (AArch64 SME ZA registers)"},
6354 {.ID: ELF::NT_ARM_ZT, .Name: "NT_ARM_ZT (AArch64 SME ZT registers)"},
6355 {.ID: ELF::NT_ARM_FPMR, .Name: "NT_ARM_FPMR (AArch64 Floating Point Mode Register)"},
6356 {.ID: ELF::NT_ARM_POE,
6357 .Name: "NT_ARM_POE (AArch64 Permission Overlay Extension Registers)"},
6358 {.ID: ELF::NT_ARM_GCS, .Name: "NT_ARM_GCS (AArch64 Guarded Control Stack state)"},
6359
6360 {.ID: ELF::NT_FILE, .Name: "NT_FILE (mapped files)"},
6361 {.ID: ELF::NT_PRXFPREG, .Name: "NT_PRXFPREG (user_xfpregs structure)"},
6362 {.ID: ELF::NT_SIGINFO, .Name: "NT_SIGINFO (siginfo_t data)"},
6363};
6364
6365template <class ELFT>
6366StringRef getNoteTypeName(const typename ELFT::Note &Note, unsigned ELFType) {
6367 uint32_t Type = Note.getType();
6368 auto FindNote = [&](ArrayRef<NoteType> V) -> StringRef {
6369 for (const NoteType &N : V)
6370 if (N.ID == Type)
6371 return N.Name;
6372 return "";
6373 };
6374
6375 StringRef Name = Note.getName();
6376 if (Name == "GNU")
6377 return FindNote(GNUNoteTypes);
6378 if (Name == "FreeBSD") {
6379 if (ELFType == ELF::ET_CORE) {
6380 // FreeBSD also places the generic core notes in the FreeBSD namespace.
6381 StringRef Result = FindNote(FreeBSDCoreNoteTypes);
6382 if (!Result.empty())
6383 return Result;
6384 return FindNote(CoreNoteTypes);
6385 } else {
6386 return FindNote(FreeBSDNoteTypes);
6387 }
6388 }
6389 if (ELFType == ELF::ET_CORE && Name.starts_with(Prefix: "NetBSD-CORE")) {
6390 StringRef Result = FindNote(NetBSDCoreNoteTypes);
6391 if (!Result.empty())
6392 return Result;
6393 return FindNote(CoreNoteTypes);
6394 }
6395 if (ELFType == ELF::ET_CORE && Name.starts_with(Prefix: "OpenBSD")) {
6396 // OpenBSD also places the generic core notes in the OpenBSD namespace.
6397 StringRef Result = FindNote(OpenBSDCoreNoteTypes);
6398 if (!Result.empty())
6399 return Result;
6400 return FindNote(CoreNoteTypes);
6401 }
6402 if (Name == "AMD")
6403 return FindNote(AMDNoteTypes);
6404 if (Name == "AMDGPU")
6405 return FindNote(AMDGPUNoteTypes);
6406 if (Name == "LLVMOMPOFFLOAD")
6407 return FindNote(LLVMOMPOFFLOADNoteTypes);
6408 if (Name == "Android")
6409 return FindNote(AndroidNoteTypes);
6410
6411 if (ELFType == ELF::ET_CORE)
6412 return FindNote(CoreNoteTypes);
6413 return FindNote(GenericNoteTypes);
6414}
6415
6416template <class ELFT>
6417static void processNotesHelper(
6418 const ELFDumper<ELFT> &Dumper,
6419 llvm::function_ref<void(std::optional<StringRef>, typename ELFT::Off,
6420 typename ELFT::Addr, size_t)>
6421 StartNotesFn,
6422 llvm::function_ref<Error(const typename ELFT::Note &, bool)> ProcessNoteFn,
6423 llvm::function_ref<void()> FinishNotesFn) {
6424 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
6425 bool IsCoreFile = Obj.getHeader().e_type == ELF::ET_CORE;
6426
6427 ArrayRef<typename ELFT::Shdr> Sections = cantFail(Obj.sections());
6428 if (!IsCoreFile && !Sections.empty()) {
6429 for (const typename ELFT::Shdr &S : Sections) {
6430 if (S.sh_type != SHT_NOTE)
6431 continue;
6432 StartNotesFn(expectedToOptional(Obj.getSectionName(S)), S.sh_offset,
6433 S.sh_size, S.sh_addralign);
6434 Error Err = Error::success();
6435 size_t I = 0;
6436 for (const typename ELFT::Note Note : Obj.notes(S, Err)) {
6437 if (Error E = ProcessNoteFn(Note, IsCoreFile))
6438 Dumper.reportUniqueWarning(
6439 "unable to read note with index " + Twine(I) + " from the " +
6440 describe(Obj, S) + ": " + toString(E: std::move(E)));
6441 ++I;
6442 }
6443 if (Err)
6444 Dumper.reportUniqueWarning("unable to read notes from the " +
6445 describe(Obj, S) + ": " +
6446 toString(E: std::move(Err)));
6447 FinishNotesFn();
6448 }
6449 return;
6450 }
6451
6452 Expected<ArrayRef<typename ELFT::Phdr>> PhdrsOrErr = Obj.program_headers();
6453 if (!PhdrsOrErr) {
6454 Dumper.reportUniqueWarning(
6455 "unable to read program headers to locate the PT_NOTE segment: " +
6456 toString(PhdrsOrErr.takeError()));
6457 return;
6458 }
6459
6460 for (size_t I = 0, E = (*PhdrsOrErr).size(); I != E; ++I) {
6461 const typename ELFT::Phdr &P = (*PhdrsOrErr)[I];
6462 if (P.p_type != PT_NOTE)
6463 continue;
6464 StartNotesFn(/*SecName=*/std::nullopt, P.p_offset, P.p_filesz, P.p_align);
6465 Error Err = Error::success();
6466 size_t Index = 0;
6467 for (const typename ELFT::Note Note : Obj.notes(P, Err)) {
6468 if (Error E = ProcessNoteFn(Note, IsCoreFile))
6469 Dumper.reportUniqueWarning("unable to read note with index " +
6470 Twine(Index) +
6471 " from the PT_NOTE segment with index " +
6472 Twine(I) + ": " + toString(E: std::move(E)));
6473 ++Index;
6474 }
6475 if (Err)
6476 Dumper.reportUniqueWarning(
6477 "unable to read notes from the PT_NOTE segment with index " +
6478 Twine(I) + ": " + toString(E: std::move(Err)));
6479 FinishNotesFn();
6480 }
6481}
6482
6483template <class ELFT> void GNUELFDumper<ELFT>::printNotes() {
6484 size_t Align = 0;
6485 bool IsFirstHeader = true;
6486 auto PrintHeader = [&](std::optional<StringRef> SecName,
6487 const typename ELFT::Off Offset,
6488 const typename ELFT::Addr Size, size_t Al) {
6489 Align = std::max<size_t>(a: Al, b: 4);
6490 // Print a newline between notes sections to match GNU readelf.
6491 if (!IsFirstHeader) {
6492 OS << '\n';
6493 } else {
6494 IsFirstHeader = false;
6495 }
6496
6497 OS << "Displaying notes found ";
6498
6499 if (SecName)
6500 OS << "in: " << *SecName << "\n";
6501 else
6502 OS << "at file offset " << format_hex(Offset, 10) << " with length "
6503 << format_hex(Size, 10) << ":\n";
6504
6505 OS << " Owner Data size \tDescription\n";
6506 };
6507
6508 auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
6509 StringRef Name = Note.getName();
6510 ArrayRef<uint8_t> Descriptor = Note.getDesc(Align);
6511 Elf_Word Type = Note.getType();
6512
6513 // Print the note owner/type.
6514 OS << " " << left_justify(Str: Name, Width: 20) << ' '
6515 << format_hex(N: Descriptor.size(), Width: 10) << '\t';
6516
6517 StringRef NoteType =
6518 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
6519 if (!NoteType.empty())
6520 OS << NoteType << '\n';
6521 else
6522 OS << "Unknown note type: (" << format_hex(Type, 10) << ")\n";
6523
6524 const typename ELFT::Half EMachine = this->Obj.getHeader().e_machine;
6525
6526 // Print the description, or fallback to printing raw bytes for unknown
6527 // owners/if we fail to pretty-print the contents.
6528 if (Name == "GNU") {
6529 if (printGNUNote<ELFT>(OS, Type, Descriptor, EMachine))
6530 return Error::success();
6531 } else if (Name == "FreeBSD") {
6532 if (std::optional<FreeBSDNote> N =
6533 getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
6534 OS << " " << N->Type << ": " << N->Value << '\n';
6535 return Error::success();
6536 }
6537 } else if (Name == "AMD") {
6538 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
6539 if (!N.Type.empty()) {
6540 OS << " " << N.Type << ":\n " << N.Value << '\n';
6541 return Error::success();
6542 }
6543 } else if (Name == "AMDGPU") {
6544 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
6545 if (!N.Type.empty()) {
6546 OS << " " << N.Type << ":\n " << N.Value << '\n';
6547 return Error::success();
6548 }
6549 } else if (Name == "LLVMOMPOFFLOAD") {
6550 if (printLLVMOMPOFFLOADNote<ELFT>(OS, Type, Descriptor))
6551 return Error::success();
6552 } else if (Name == "CORE") {
6553 if (Type == ELF::NT_FILE) {
6554 DataExtractor DescExtractor(Descriptor, ELFT::Endianness ==
6555 llvm::endianness::little);
6556 if (Expected<CoreNote> NoteOrErr =
6557 readCoreNote(Desc: DescExtractor, AddressSize: sizeof(Elf_Addr))) {
6558 printCoreNote<ELFT>(OS, *NoteOrErr);
6559 return Error::success();
6560 } else {
6561 return NoteOrErr.takeError();
6562 }
6563 }
6564 } else if (Name == "Android") {
6565 if (printAndroidNote(OS, Type, Descriptor))
6566 return Error::success();
6567 }
6568 if (!Descriptor.empty()) {
6569 OS << " description data:";
6570 for (uint8_t B : Descriptor)
6571 OS << " " << format(Fmt: "%02x", Vals: B);
6572 OS << '\n';
6573 }
6574 return Error::success();
6575 };
6576
6577 processNotesHelper(*this, /*StartNotesFn=*/PrintHeader,
6578 /*ProcessNoteFn=*/ProcessNote, /*FinishNotesFn=*/[]() {});
6579}
6580
6581template <class ELFT>
6582ArrayRef<uint8_t>
6583ELFDumper<ELFT>::getMemtagGlobalsSectionContents(uint64_t ExpectedAddr) {
6584 for (const typename ELFT::Shdr &Sec : cantFail(Obj.sections())) {
6585 if (Sec.sh_type != SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC)
6586 continue;
6587 if (Sec.sh_addr != ExpectedAddr) {
6588 reportUniqueWarning(
6589 "SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section was unexpectedly at 0x" +
6590 Twine::utohexstr(Val: Sec.sh_addr) +
6591 ", when DT_AARCH64_MEMTAG_GLOBALS says it should be at 0x" +
6592 Twine::utohexstr(Val: ExpectedAddr));
6593 return ArrayRef<uint8_t>();
6594 }
6595 Expected<ArrayRef<uint8_t>> Contents = Obj.getSectionContents(Sec);
6596 if (auto E = Contents.takeError()) {
6597 reportUniqueWarning(
6598 "couldn't get SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section contents: " +
6599 toString(E: std::move(E)));
6600 return ArrayRef<uint8_t>();
6601 }
6602 return Contents.get();
6603 }
6604 return ArrayRef<uint8_t>();
6605}
6606
6607// Reserve the lower three bits of the first byte of the step distance when
6608// encoding the memtag descriptors. Found to be the best overall size tradeoff
6609// when compiling Android T with full MTE globals enabled.
6610constexpr uint64_t MemtagStepVarintReservedBits = 3;
6611constexpr uint64_t MemtagGranuleSize = 16;
6612
6613template <typename ELFT> void ELFDumper<ELFT>::printMemtag() {
6614 if (Obj.getHeader().e_machine != EM_AARCH64) return;
6615 std::vector<std::pair<std::string, std::string>> DynamicEntries;
6616 uint64_t MemtagGlobalsSz = 0;
6617 uint64_t MemtagGlobals = 0;
6618 for (const typename ELFT::Dyn &Entry : dynamic_table()) {
6619 uintX_t Tag = Entry.getTag();
6620 switch (Tag) {
6621 case DT_AARCH64_MEMTAG_GLOBALSSZ:
6622 MemtagGlobalsSz = Entry.getVal();
6623 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6624 getDynamicEntry(Type: Tag, Value: Entry.getVal()));
6625 break;
6626 case DT_AARCH64_MEMTAG_GLOBALS:
6627 MemtagGlobals = Entry.getVal();
6628 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6629 getDynamicEntry(Type: Tag, Value: Entry.getVal()));
6630 break;
6631 case DT_AARCH64_MEMTAG_MODE:
6632 case DT_AARCH64_MEMTAG_HEAP:
6633 case DT_AARCH64_MEMTAG_STACK:
6634 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6635 getDynamicEntry(Type: Tag, Value: Entry.getVal()));
6636 break;
6637 }
6638 }
6639
6640 ArrayRef<uint8_t> AndroidNoteDesc;
6641 auto FindAndroidNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
6642 if (Note.getName() == "Android" &&
6643 Note.getType() == ELF::NT_ANDROID_TYPE_MEMTAG)
6644 AndroidNoteDesc = Note.getDesc(4);
6645 return Error::success();
6646 };
6647
6648 processNotesHelper(
6649 *this,
6650 /*StartNotesFn=*/
6651 [](std::optional<StringRef>, const typename ELFT::Off,
6652 const typename ELFT::Addr, size_t) {},
6653 /*ProcessNoteFn=*/FindAndroidNote, /*FinishNotesFn=*/[]() {});
6654
6655 ArrayRef<uint8_t> Contents = getMemtagGlobalsSectionContents(ExpectedAddr: MemtagGlobals);
6656 if (Contents.size() != MemtagGlobalsSz) {
6657 reportUniqueWarning(
6658 "mismatch between DT_AARCH64_MEMTAG_GLOBALSSZ (0x" +
6659 Twine::utohexstr(Val: MemtagGlobalsSz) +
6660 ") and SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section size (0x" +
6661 Twine::utohexstr(Val: Contents.size()) + ")");
6662 Contents = ArrayRef<uint8_t>();
6663 }
6664
6665 std::vector<std::pair<uint64_t, uint64_t>> GlobalDescriptors;
6666 uint64_t Address = 0;
6667 // See the AArch64 MemtagABI document for a description of encoding scheme:
6668 // https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#83encoding-of-sht_aarch64_memtag_globals_dynamic
6669 for (size_t I = 0; I < Contents.size();) {
6670 const char *Error = nullptr;
6671 unsigned DecodedBytes = 0;
6672 uint64_t Value = decodeULEB128(p: Contents.data() + I, n: &DecodedBytes,
6673 end: Contents.end(), error: &Error);
6674 I += DecodedBytes;
6675 if (Error) {
6676 reportUniqueWarning(
6677 "error decoding distance uleb, " + Twine(DecodedBytes) +
6678 " byte(s) into SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC: " + Twine(Error));
6679 GlobalDescriptors.clear();
6680 break;
6681 }
6682 uint64_t Distance = Value >> MemtagStepVarintReservedBits;
6683 uint64_t GranulesToTag = Value & ((1 << MemtagStepVarintReservedBits) - 1);
6684 if (GranulesToTag == 0) {
6685 GranulesToTag = decodeULEB128(p: Contents.data() + I, n: &DecodedBytes,
6686 end: Contents.end(), error: &Error) +
6687 1;
6688 I += DecodedBytes;
6689 if (Error) {
6690 reportUniqueWarning(
6691 "error decoding size-only uleb, " + Twine(DecodedBytes) +
6692 " byte(s) into SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC: " + Twine(Error));
6693 GlobalDescriptors.clear();
6694 break;
6695 }
6696 }
6697 Address += Distance * MemtagGranuleSize;
6698 GlobalDescriptors.emplace_back(args&: Address, args: GranulesToTag * MemtagGranuleSize);
6699 Address += GranulesToTag * MemtagGranuleSize;
6700 }
6701
6702 printMemtag(DynamicEntries, AndroidNoteDesc, GlobalDescriptors);
6703}
6704
6705template <typename ELFT>
6706void ELFDumper<ELFT>::printSFrameHeader(
6707 const SFrameParser<ELFT::Endianness> &Parser) {
6708 DictScope HeaderScope(W, "Header");
6709
6710 const sframe::Preamble<ELFT::Endianness> &Preamble = Parser.getPreamble();
6711 W.printHex("Magic", Preamble.Magic.value());
6712 W.printEnum("Version", Preamble.Version.value(), sframe::getVersions());
6713 W.printFlags("Flags", Preamble.Flags.value(), sframe::getFlags());
6714
6715 const sframe::Header<ELFT::Endianness> &Header = Parser.getHeader();
6716 W.printEnum("ABI", Header.ABIArch.value(), sframe::getABIs());
6717
6718 W.printNumber(("CFA fixed FP offset" +
6719 Twine(Parser.usesFixedFPOffset() ? "" : " (unused)"))
6720 .str(),
6721 Header.CFAFixedFPOffset.value());
6722
6723 W.printNumber(("CFA fixed RA offset" +
6724 Twine(Parser.usesFixedRAOffset() ? "" : " (unused)"))
6725 .str(),
6726 Header.CFAFixedRAOffset.value());
6727
6728 W.printNumber("Auxiliary header length", Header.AuxHdrLen.value());
6729 W.printNumber("Num FDEs", Header.NumFDEs.value());
6730 W.printNumber("Num FREs", Header.NumFREs.value());
6731 W.printNumber("FRE subsection length", Header.FRELen.value());
6732 W.printNumber("FDE subsection offset", Header.FDEOff.value());
6733 W.printNumber("FRE subsection offset", Header.FREOff.value());
6734
6735 if (Expected<ArrayRef<uint8_t>> Aux = Parser.getAuxHeader())
6736 W.printHexList("Auxiliary header", *Aux);
6737 else
6738 reportUniqueWarning(Aux.takeError());
6739}
6740
6741template <typename ELFT>
6742void ELFDumper<ELFT>::printSFrameFDEs(
6743 const SFrameParser<ELFT::Endianness> &Parser,
6744 ArrayRef<Relocation<ELFT>> Relocations, const Elf_Shdr *RelocSymTab) {
6745 typename SFrameParser<ELFT::Endianness>::FDERange FDEs;
6746 if (Error Err = Parser.fdes().moveInto(FDEs)) {
6747 reportUniqueWarning(std::move(Err));
6748 return;
6749 }
6750
6751 ListScope IndexScope(W, "Function Index");
6752 for (auto It = FDEs.begin(); It != FDEs.end(); ++It) {
6753 DictScope FDEScope(
6754 W,
6755 formatv("FuncDescEntry [{0}]", std::distance(FDEs.begin(), It)).str());
6756
6757 uint64_t FDEStartAddress =
6758 getAndPrintSFrameFDEStartAddress(Parser, FDE: It, Relocations, RelocSymTab);
6759 W.printHex("Size", It->Size);
6760 W.printHex("Start FRE Offset", It->StartFREOff);
6761 W.printNumber("Num FREs", It->NumFREs);
6762
6763 {
6764 DictScope InfoScope(W, "Info");
6765 W.printEnum("FRE Type", It->Info.getFREType(), sframe::getFRETypes());
6766 W.printEnum("FDE Type", It->Info.getFDEType(), sframe::getFDETypes());
6767 switch (Parser.getHeader().ABIArch) {
6768 case sframe::ABI::AArch64EndianBig:
6769 case sframe::ABI::AArch64EndianLittle:
6770 W.printEnum("PAuth Key",
6771 sframe::AArch64PAuthKey(It->Info.getPAuthKey()),
6772 sframe::getAArch64PAuthKeys());
6773 break;
6774 case sframe::ABI::AMD64EndianLittle:
6775 // unused
6776 break;
6777 }
6778
6779 W.printHex("Raw", It->Info.Info);
6780 }
6781
6782 W.printHex(
6783 ("Repetitive block size" +
6784 Twine(It->Info.getFDEType() == sframe::FDEType::PCMask ? ""
6785 : " (unused)"))
6786 .str(),
6787 It->RepSize);
6788
6789 W.printHex("Padding2", It->Padding2);
6790
6791 ListScope FREListScope(W, "FREs");
6792 Error Err = Error::success();
6793 for (const typename SFrameParser<ELFT::Endianness>::FrameRowEntry &FRE :
6794 Parser.fres(*It, Err)) {
6795 DictScope FREScope(W, "Frame Row Entry");
6796 W.printHex("Start Address",
6797 (It->Info.getFDEType() == sframe::FDEType::PCInc
6798 ? FDEStartAddress
6799 : 0) +
6800 FRE.StartAddress);
6801 W.printBoolean(Label: "Return Address Signed", Value: FRE.Info.isReturnAddressSigned());
6802 W.printEnum("Offset Size", FRE.Info.getOffsetSize(),
6803 sframe::getFREOffsets());
6804 W.printEnum("Base Register", FRE.Info.getBaseRegister(),
6805 sframe::getBaseRegisters());
6806 if (std::optional<int32_t> Off = Parser.getCFAOffset(FRE))
6807 W.printNumber("CFA Offset", *Off);
6808 if (std::optional<int32_t> Off = Parser.getRAOffset(FRE))
6809 W.printNumber("RA Offset", *Off);
6810 if (std::optional<int32_t> Off = Parser.getFPOffset(FRE))
6811 W.printNumber("FP Offset", *Off);
6812 if (ArrayRef<int32_t> Offs = Parser.getExtraOffsets(FRE); !Offs.empty())
6813 W.printList("Extra Offsets", Offs);
6814 }
6815 if (Err)
6816 reportUniqueWarning(std::move(Err));
6817 }
6818}
6819
6820template <typename ELFT>
6821uint64_t ELFDumper<ELFT>::getAndPrintSFrameFDEStartAddress(
6822 const SFrameParser<ELFT::Endianness> &Parser,
6823 const typename SFrameParser<ELFT::Endianness>::FDERange::iterator FDE,
6824 ArrayRef<Relocation<ELFT>> Relocations, const Elf_Shdr *RelocSymTab) {
6825 uint64_t Address = Parser.getAbsoluteStartAddress(FDE);
6826 uint64_t Offset = Parser.offsetOf(FDE);
6827
6828 auto Reloc = llvm::lower_bound(
6829 Relocations, Offset, [](auto R, uint64_t O) { return R.Offset < O; });
6830 if (Reloc == Relocations.end() || Reloc->Offset != Offset) {
6831 W.printHex("PC", Address);
6832 } else if (std::next(Reloc) != Relocations.end() &&
6833 std::next(Reloc)->Offset == Offset) {
6834 reportUniqueWarning(
6835 formatv(Fmt: "more than one relocation at offset {0:x+}", Vals&: Offset));
6836 W.printHex("PC", Address);
6837 } else if (Expected<RelSymbol<ELFT>> RelSym =
6838 getRelocationTarget(R: *Reloc, SymTab: RelocSymTab);
6839 !RelSym) {
6840 reportUniqueWarning(RelSym.takeError());
6841 W.printHex("PC", Address);
6842 } else {
6843 // Exactly one relocation at the given offset. Print it.
6844 DictScope PCScope(W, "PC");
6845 SmallString<32> RelocName;
6846 Obj.getRelocationTypeName(Reloc->Type, RelocName);
6847 W.printString("Relocation", RelocName);
6848 W.printString("Symbol Name", RelSym->Name);
6849 Address = FDE->StartAddress + Reloc->Addend.value_or(0);
6850 W.printHex("Start Address", Address);
6851 }
6852 return Address;
6853}
6854
6855template <typename ELFT>
6856void ELFDumper<ELFT>::printSectionsAsSFrame(ArrayRef<std::string> Sections) {
6857 constexpr endianness E = ELFT::Endianness;
6858
6859 for (object::SectionRef Section :
6860 getSectionRefsByNameOrIndex(Obj: ObjF, Sections)) {
6861 // Validity of sections names checked in getSectionRefsByNameOrIndex.
6862 StringRef SectionName = cantFail(ValOrErr: Section.getName());
6863
6864 DictScope SectionScope(W,
6865 formatv(Fmt: "SFrame section '{0}'", Vals&: SectionName).str());
6866
6867 StringRef SectionContent;
6868 if (Error Err = Section.getContents().moveInto(Value&: SectionContent)) {
6869 reportUniqueWarning(std::move(Err));
6870 continue;
6871 }
6872
6873 Expected<object::SFrameParser<E>> Parser = object::SFrameParser<E>::create(
6874 arrayRefFromStringRef(Input: SectionContent), Section.getAddress());
6875 if (!Parser) {
6876 reportUniqueWarning("invalid sframe section: " +
6877 toString(Parser.takeError()));
6878 continue;
6879 }
6880
6881 const Elf_Shdr *ELFSection = ObjF.getSection(Section.getRawDataRefImpl());
6882 MapVector<const Elf_Shdr *, const Elf_Shdr *> RelocationMap;
6883 if (Error Err = Obj.getSectionAndRelocations(
6884 [&](const Elf_Shdr &S) { return &S == ELFSection; })
6885 .moveInto(RelocationMap)) {
6886 reportUniqueWarning(std::move(Err));
6887 }
6888
6889 std::vector<Relocation<ELFT>> Relocations;
6890 const Elf_Shdr *RelocSymTab = nullptr;
6891 if (const Elf_Shdr *RelocSection = RelocationMap.lookup(ELFSection)) {
6892 forEachRelocationDo(Sec: *RelocSection,
6893 RelRelaFn: [&](const Relocation<ELFT> &R, unsigned Ndx,
6894 const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
6895 RelocSymTab = SymTab;
6896 Relocations.push_back(R);
6897 });
6898 llvm::stable_sort(Relocations, [](const auto &LHS, const auto &RHS) {
6899 return LHS.Offset < RHS.Offset;
6900 });
6901 }
6902
6903 printSFrameHeader(Parser: *Parser);
6904 printSFrameFDEs(Parser: *Parser, Relocations, RelocSymTab);
6905 }
6906}
6907
6908template <class ELFT> void GNUELFDumper<ELFT>::printELFLinkerOptions() {
6909 OS << "printELFLinkerOptions not implemented!\n";
6910}
6911
6912template <class ELFT>
6913void ELFDumper<ELFT>::printDependentLibsHelper(
6914 function_ref<void(const Elf_Shdr &)> OnSectionStart,
6915 function_ref<void(StringRef, uint64_t)> OnLibEntry) {
6916 auto Warn = [this](unsigned SecNdx, StringRef Msg) {
6917 this->reportUniqueWarning("SHT_LLVM_DEPENDENT_LIBRARIES section at index " +
6918 Twine(SecNdx) + " is broken: " + Msg);
6919 };
6920
6921 unsigned I = -1;
6922 for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
6923 ++I;
6924 if (Shdr.sh_type != ELF::SHT_LLVM_DEPENDENT_LIBRARIES)
6925 continue;
6926
6927 OnSectionStart(Shdr);
6928
6929 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Shdr);
6930 if (!ContentsOrErr) {
6931 Warn(I, toString(E: ContentsOrErr.takeError()));
6932 continue;
6933 }
6934
6935 ArrayRef<uint8_t> Contents = *ContentsOrErr;
6936 if (!Contents.empty() && Contents.back() != 0) {
6937 Warn(I, "the content is not null-terminated");
6938 continue;
6939 }
6940
6941 for (const uint8_t *I = Contents.begin(), *E = Contents.end(); I < E;) {
6942 StringRef Lib((const char *)I);
6943 OnLibEntry(Lib, I - Contents.begin());
6944 I += Lib.size() + 1;
6945 }
6946 }
6947}
6948
6949template <class ELFT>
6950void ELFDumper<ELFT>::forEachRelocationDo(
6951 const Elf_Shdr &Sec,
6952 llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
6953 const Elf_Shdr &, const Elf_Shdr *)>
6954 RelRelaFn) {
6955 auto Warn = [&](Error &&E,
6956 const Twine &Prefix = "unable to read relocations from") {
6957 this->reportUniqueWarning(Prefix + " " + describe(Sec) + ": " +
6958 toString(E: std::move(E)));
6959 };
6960
6961 // SHT_RELR/SHT_ANDROID_RELR/SHT_AARCH64_AUTH_RELR sections do not have an
6962 // associated symbol table. For them we should not treat the value of the
6963 // sh_link field as an index of a symbol table.
6964 const Elf_Shdr *SymTab;
6965 if (Sec.sh_type != ELF::SHT_RELR && Sec.sh_type != ELF::SHT_ANDROID_RELR &&
6966 !(Obj.getHeader().e_machine == EM_AARCH64 &&
6967 Sec.sh_type == ELF::SHT_AARCH64_AUTH_RELR)) {
6968 Expected<const Elf_Shdr *> SymTabOrErr = Obj.getSection(Sec.sh_link);
6969 if (!SymTabOrErr) {
6970 Warn(SymTabOrErr.takeError(), "unable to locate a symbol table for");
6971 return;
6972 }
6973 SymTab = *SymTabOrErr;
6974 }
6975
6976 unsigned RelNdx = 0;
6977 const bool IsMips64EL = this->Obj.isMips64EL();
6978 switch (Sec.sh_type) {
6979 case ELF::SHT_REL:
6980 if (Expected<Elf_Rel_Range> RangeOrErr = Obj.rels(Sec)) {
6981 for (const Elf_Rel &R : *RangeOrErr)
6982 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
6983 } else {
6984 Warn(RangeOrErr.takeError());
6985 }
6986 break;
6987 case ELF::SHT_RELA:
6988 if (Expected<Elf_Rela_Range> RangeOrErr = Obj.relas(Sec)) {
6989 for (const Elf_Rela &R : *RangeOrErr)
6990 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
6991 } else {
6992 Warn(RangeOrErr.takeError());
6993 }
6994 break;
6995 case ELF::SHT_AARCH64_AUTH_RELR:
6996 if (Obj.getHeader().e_machine != EM_AARCH64)
6997 break;
6998 [[fallthrough]];
6999 case ELF::SHT_RELR:
7000 case ELF::SHT_ANDROID_RELR: {
7001 Expected<Elf_Relr_Range> RangeOrErr = Obj.relrs(Sec);
7002 if (!RangeOrErr) {
7003 Warn(RangeOrErr.takeError());
7004 break;
7005 }
7006
7007 for (const Elf_Rel &R : Obj.decode_relrs(*RangeOrErr))
7008 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec,
7009 /*SymTab=*/nullptr);
7010 break;
7011 }
7012 case ELF::SHT_CREL: {
7013 if (auto RelsOrRelas = Obj.crels(Sec)) {
7014 for (const Elf_Rel &R : RelsOrRelas->first)
7015 RelRelaFn(Relocation<ELFT>(R, false), RelNdx++, Sec, SymTab);
7016 for (const Elf_Rela &R : RelsOrRelas->second)
7017 RelRelaFn(Relocation<ELFT>(R, false), RelNdx++, Sec, SymTab);
7018 } else {
7019 Warn(RelsOrRelas.takeError());
7020 }
7021 break;
7022 }
7023 case ELF::SHT_ANDROID_REL:
7024 case ELF::SHT_ANDROID_RELA:
7025 if (Expected<std::vector<Elf_Rela>> RelasOrErr = Obj.android_relas(Sec)) {
7026 for (const Elf_Rela &R : *RelasOrErr)
7027 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
7028 } else {
7029 Warn(RelasOrErr.takeError());
7030 }
7031 break;
7032 }
7033}
7034
7035template <class ELFT>
7036StringRef ELFDumper<ELFT>::getPrintableSectionName(const Elf_Shdr &Sec) const {
7037 StringRef Name = "<?>";
7038 if (Expected<StringRef> SecNameOrErr =
7039 Obj.getSectionName(Sec, this->WarningHandler))
7040 Name = *SecNameOrErr;
7041 else
7042 this->reportUniqueWarning("unable to get the name of " + describe(Sec) +
7043 ": " + toString(E: SecNameOrErr.takeError()));
7044 return Name;
7045}
7046
7047template <class ELFT> void GNUELFDumper<ELFT>::printDependentLibs() {
7048 bool SectionStarted = false;
7049 struct NameOffset {
7050 StringRef Name;
7051 uint64_t Offset;
7052 };
7053 std::vector<NameOffset> SecEntries;
7054 NameOffset Current;
7055 auto PrintSection = [&]() {
7056 OS << "Dependent libraries section " << Current.Name << " at offset "
7057 << format_hex(Current.Offset, 1) << " contains " << SecEntries.size()
7058 << " entries:\n";
7059 for (NameOffset Entry : SecEntries)
7060 OS << " [" << format("%6" PRIx64, Entry.Offset) << "] " << Entry.Name
7061 << "\n";
7062 OS << "\n";
7063 SecEntries.clear();
7064 };
7065
7066 auto OnSectionStart = [&](const Elf_Shdr &Shdr) {
7067 if (SectionStarted)
7068 PrintSection();
7069 SectionStarted = true;
7070 Current.Offset = Shdr.sh_offset;
7071 Current.Name = this->getPrintableSectionName(Shdr);
7072 };
7073 auto OnLibEntry = [&](StringRef Lib, uint64_t Offset) {
7074 SecEntries.push_back(NameOffset{Lib, Offset});
7075 };
7076
7077 this->printDependentLibsHelper(OnSectionStart, OnLibEntry);
7078 if (SectionStarted)
7079 PrintSection();
7080}
7081
7082template <class ELFT>
7083SmallVector<uint32_t> ELFDumper<ELFT>::getSymbolIndexesForFunctionAddress(
7084 uint64_t SymValue, std::optional<const Elf_Shdr *> FunctionSec) {
7085 SmallVector<uint32_t> SymbolIndexes;
7086 if (!this->AddressToIndexMap) {
7087 // Populate the address to index map upon the first invocation of this
7088 // function.
7089 this->AddressToIndexMap.emplace();
7090 if (this->DotSymtabSec) {
7091 if (Expected<Elf_Sym_Range> SymsOrError =
7092 Obj.symbols(this->DotSymtabSec)) {
7093 uint32_t Index = (uint32_t)-1;
7094 for (const Elf_Sym &Sym : *SymsOrError) {
7095 ++Index;
7096
7097 if (Sym.st_shndx == ELF::SHN_UNDEF || Sym.getType() != ELF::STT_FUNC)
7098 continue;
7099
7100 Expected<uint64_t> SymAddrOrErr =
7101 ObjF.toSymbolRef(this->DotSymtabSec, Index).getAddress();
7102 if (!SymAddrOrErr) {
7103 std::string Name = this->getStaticSymbolName(Index);
7104 reportUniqueWarning("unable to get address of symbol '" + Name +
7105 "': " + toString(E: SymAddrOrErr.takeError()));
7106 return SymbolIndexes;
7107 }
7108
7109 (*this->AddressToIndexMap)[*SymAddrOrErr].push_back(x: Index);
7110 }
7111 } else {
7112 reportUniqueWarning("unable to read the symbol table: " +
7113 toString(SymsOrError.takeError()));
7114 }
7115 }
7116 }
7117
7118 auto Symbols = this->AddressToIndexMap->find(Val: SymValue);
7119 if (Symbols == this->AddressToIndexMap->end())
7120 return SymbolIndexes;
7121
7122 for (uint32_t Index : Symbols->second) {
7123 // Check if the symbol is in the right section. FunctionSec == None
7124 // means "any section".
7125 if (FunctionSec) {
7126 const Elf_Sym &Sym = *cantFail(Obj.getSymbol(this->DotSymtabSec, Index));
7127 if (Expected<const Elf_Shdr *> SecOrErr =
7128 Obj.getSection(Sym, this->DotSymtabSec,
7129 this->getShndxTable(Symtab: this->DotSymtabSec))) {
7130 if (*FunctionSec != *SecOrErr)
7131 continue;
7132 } else {
7133 std::string Name = this->getStaticSymbolName(Index);
7134 // Note: it is impossible to trigger this error currently, it is
7135 // untested.
7136 reportUniqueWarning("unable to get section of symbol '" + Name +
7137 "': " + toString(SecOrErr.takeError()));
7138 return SymbolIndexes;
7139 }
7140 }
7141
7142 SymbolIndexes.push_back(Elt: Index);
7143 }
7144
7145 return SymbolIndexes;
7146}
7147
7148template <class ELFT>
7149bool ELFDumper<ELFT>::printFunctionStackSize(
7150 uint64_t SymValue, std::optional<const Elf_Shdr *> FunctionSec,
7151 const Elf_Shdr &StackSizeSec, DataExtractor Data, uint64_t *Offset) {
7152 SmallVector<uint32_t> FuncSymIndexes =
7153 this->getSymbolIndexesForFunctionAddress(SymValue, FunctionSec);
7154 if (FuncSymIndexes.empty())
7155 reportUniqueWarning(
7156 "could not identify function symbol for stack size entry in " +
7157 describe(Sec: StackSizeSec));
7158
7159 // Extract the size. The expectation is that Offset is pointing to the right
7160 // place, i.e. past the function address.
7161 Error Err = Error::success();
7162 uint64_t StackSize = Data.getULEB128(offset_ptr: Offset, Err: &Err);
7163 if (Err) {
7164 reportUniqueWarning("could not extract a valid stack size from " +
7165 describe(Sec: StackSizeSec) + ": " +
7166 toString(E: std::move(Err)));
7167 return false;
7168 }
7169
7170 if (FuncSymIndexes.empty()) {
7171 printStackSizeEntry(Size: StackSize, FuncNames: {"?"});
7172 } else {
7173 SmallVector<std::string> FuncSymNames;
7174 for (uint32_t Index : FuncSymIndexes)
7175 FuncSymNames.push_back(this->getStaticSymbolName(Index));
7176 printStackSizeEntry(Size: StackSize, FuncNames: FuncSymNames);
7177 }
7178
7179 return true;
7180}
7181
7182template <class ELFT>
7183void GNUELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
7184 ArrayRef<std::string> FuncNames) {
7185 OS.PadToColumn(NewCol: 2);
7186 OS << format_decimal(N: Size, Width: 11);
7187 OS.PadToColumn(NewCol: 18);
7188
7189 OS << join(Begin: FuncNames.begin(), End: FuncNames.end(), Separator: ", ") << "\n";
7190}
7191
7192template <class ELFT>
7193void ELFDumper<ELFT>::printStackSize(const Relocation<ELFT> &R,
7194 const Elf_Shdr &RelocSec, unsigned Ndx,
7195 const Elf_Shdr *SymTab,
7196 const Elf_Shdr *FunctionSec,
7197 const Elf_Shdr &StackSizeSec,
7198 const RelocationResolver &Resolver,
7199 DataExtractor Data) {
7200 // This function ignores potentially erroneous input, unless it is directly
7201 // related to stack size reporting.
7202 const Elf_Sym *Sym = nullptr;
7203 Expected<RelSymbol<ELFT>> TargetOrErr = this->getRelocationTarget(R, SymTab);
7204 if (!TargetOrErr)
7205 reportUniqueWarning("unable to get the target of relocation with index " +
7206 Twine(Ndx) + " in " + describe(Sec: RelocSec) + ": " +
7207 toString(TargetOrErr.takeError()));
7208 else
7209 Sym = TargetOrErr->Sym;
7210
7211 uint64_t RelocSymValue = 0;
7212 if (Sym) {
7213 Expected<const Elf_Shdr *> SectionOrErr =
7214 this->Obj.getSection(*Sym, SymTab, this->getShndxTable(Symtab: SymTab));
7215 if (!SectionOrErr) {
7216 reportUniqueWarning(
7217 "cannot identify the section for relocation symbol '" +
7218 (*TargetOrErr).Name + "': " + toString(SectionOrErr.takeError()));
7219 } else if (*SectionOrErr != FunctionSec) {
7220 reportUniqueWarning("relocation symbol '" + (*TargetOrErr).Name +
7221 "' is not in the expected section");
7222 // Pretend that the symbol is in the correct section and report its
7223 // stack size anyway.
7224 FunctionSec = *SectionOrErr;
7225 }
7226
7227 RelocSymValue = Sym->st_value;
7228 }
7229
7230 uint64_t Offset = R.Offset;
7231 if (!Data.isValidOffsetForDataOfSize(offset: Offset, length: sizeof(Elf_Addr) + 1)) {
7232 reportUniqueWarning("found invalid relocation offset (0x" +
7233 Twine::utohexstr(Val: Offset) + ") into " +
7234 describe(Sec: StackSizeSec) +
7235 " while trying to extract a stack size entry");
7236 return;
7237 }
7238
7239 uint64_t SymValue = Resolver(R.Type, Offset, RelocSymValue,
7240 Data.getUnsigned(offset_ptr: &Offset, byte_size: sizeof(Elf_Addr)),
7241 R.Addend.value_or(0));
7242 this->printFunctionStackSize(SymValue, FunctionSec, StackSizeSec, Data,
7243 Offset: &Offset);
7244}
7245
7246template <class ELFT>
7247void ELFDumper<ELFT>::printNonRelocatableStackSizes(
7248 std::function<void()> PrintHeader) {
7249 // This function ignores potentially erroneous input, unless it is directly
7250 // related to stack size reporting.
7251 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
7252 if (this->getPrintableSectionName(Sec) != ".stack_sizes")
7253 continue;
7254 PrintHeader();
7255 ArrayRef<uint8_t> Contents =
7256 unwrapOrError(this->FileName, Obj.getSectionContents(Sec));
7257 DataExtractor Data(Contents, Obj.isLE());
7258 uint64_t Offset = 0;
7259 while (Offset < Contents.size()) {
7260 // The function address is followed by a ULEB representing the stack
7261 // size. Check for an extra byte before we try to process the entry.
7262 if (!Data.isValidOffsetForDataOfSize(offset: Offset, length: sizeof(Elf_Addr) + 1)) {
7263 reportUniqueWarning(
7264 describe(Sec) +
7265 " ended while trying to extract a stack size entry");
7266 break;
7267 }
7268 uint64_t SymValue = Data.getUnsigned(offset_ptr: &Offset, byte_size: sizeof(Elf_Addr));
7269 if (!printFunctionStackSize(SymValue, /*FunctionSec=*/std::nullopt, StackSizeSec: Sec,
7270 Data, Offset: &Offset))
7271 break;
7272 }
7273 }
7274}
7275
7276template <class ELFT>
7277void ELFDumper<ELFT>::printRelocatableStackSizes(
7278 std::function<void()> PrintHeader) {
7279 // Build a map between stack size sections and their corresponding relocation
7280 // sections.
7281 auto IsMatch = [&](const Elf_Shdr &Sec) -> bool {
7282 StringRef SectionName;
7283 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec))
7284 SectionName = *NameOrErr;
7285 else
7286 consumeError(Err: NameOrErr.takeError());
7287
7288 return SectionName == ".stack_sizes";
7289 };
7290
7291 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>>
7292 StackSizeRelocMapOrErr = Obj.getSectionAndRelocations(IsMatch);
7293 if (!StackSizeRelocMapOrErr) {
7294 reportUniqueWarning("unable to get stack size map section(s): " +
7295 toString(StackSizeRelocMapOrErr.takeError()));
7296 return;
7297 }
7298
7299 for (const auto &StackSizeMapEntry : *StackSizeRelocMapOrErr) {
7300 PrintHeader();
7301 const Elf_Shdr *StackSizesELFSec = StackSizeMapEntry.first;
7302 const Elf_Shdr *RelocSec = StackSizeMapEntry.second;
7303
7304 // Warn about stack size sections without a relocation section.
7305 if (!RelocSec) {
7306 reportWarning(createError(".stack_sizes (" + describe(Sec: *StackSizesELFSec) +
7307 ") does not have a corresponding "
7308 "relocation section"),
7309 FileName);
7310 continue;
7311 }
7312
7313 // We might end up with relocations in CREL here. If we do, report a
7314 // warning since we do not currently support them.
7315 if (RelocSec->sh_type == ELF::SHT_CREL) {
7316 reportWarning(createError(".stack_sizes (" + describe(Sec: *StackSizesELFSec) +
7317 ") has a corresponding CREL relocation "
7318 "section, which is not currently supported"),
7319 FileName);
7320 continue;
7321 }
7322
7323 // A .stack_sizes section header's sh_link field is supposed to point
7324 // to the section that contains the functions whose stack sizes are
7325 // described in it.
7326 const Elf_Shdr *FunctionSec = unwrapOrError(
7327 this->FileName, Obj.getSection(StackSizesELFSec->sh_link));
7328
7329 SupportsRelocation IsSupportedFn;
7330 RelocationResolver Resolver;
7331 std::tie(args&: IsSupportedFn, args&: Resolver) = getRelocationResolver(this->ObjF);
7332 ArrayRef<uint8_t> Contents =
7333 unwrapOrError(this->FileName, Obj.getSectionContents(*StackSizesELFSec));
7334 DataExtractor Data(Contents, Obj.isLE());
7335
7336 forEachRelocationDo(
7337 Sec: *RelocSec, RelRelaFn: [&](const Relocation<ELFT> &R, unsigned Ndx,
7338 const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
7339 if (!IsSupportedFn || !IsSupportedFn(R.Type)) {
7340 reportUniqueWarning(
7341 describe(Sec: *RelocSec) +
7342 " contains an unsupported relocation with index " + Twine(Ndx) +
7343 ": " + Obj.getRelocationTypeName(R.Type));
7344 return;
7345 }
7346
7347 this->printStackSize(R, RelocSec: *RelocSec, Ndx, SymTab, FunctionSec,
7348 StackSizeSec: *StackSizesELFSec, Resolver, Data);
7349 });
7350 }
7351}
7352
7353template <class ELFT>
7354void GNUELFDumper<ELFT>::printStackSizes() {
7355 bool HeaderHasBeenPrinted = false;
7356 auto PrintHeader = [&]() {
7357 if (HeaderHasBeenPrinted)
7358 return;
7359 OS << "\nStack Sizes:\n";
7360 OS.PadToColumn(NewCol: 9);
7361 OS << "Size";
7362 OS.PadToColumn(NewCol: 18);
7363 OS << "Functions\n";
7364 HeaderHasBeenPrinted = true;
7365 };
7366
7367 // For non-relocatable objects, look directly for sections whose name starts
7368 // with .stack_sizes and process the contents.
7369 if (this->Obj.getHeader().e_type == ELF::ET_REL)
7370 this->printRelocatableStackSizes(PrintHeader);
7371 else
7372 this->printNonRelocatableStackSizes(PrintHeader);
7373}
7374
7375template <class ELFT>
7376void GNUELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
7377 size_t Bias = ELFT::Is64Bits ? 8 : 0;
7378 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
7379 OS.PadToColumn(NewCol: 2);
7380 OS << format_hex_no_prefix(Parser.getGotAddress(E), 8 + Bias);
7381 OS.PadToColumn(NewCol: 11 + Bias);
7382 OS << format_decimal(Parser.getGotOffset(E), 6) << "(gp)";
7383 OS.PadToColumn(NewCol: 22 + Bias);
7384 OS << format_hex_no_prefix(*E, 8 + Bias);
7385 OS.PadToColumn(NewCol: 31 + 2 * Bias);
7386 OS << Purpose << "\n";
7387 };
7388
7389 OS << (Parser.IsStatic ? "Static GOT:\n" : "Primary GOT:\n");
7390 OS << " Canonical gp value: "
7391 << format_hex_no_prefix(Parser.getGp(), 8 + Bias) << "\n\n";
7392
7393 OS << " Reserved entries:\n";
7394 if (ELFT::Is64Bits)
7395 OS << " Address Access Initial Purpose\n";
7396 else
7397 OS << " Address Access Initial Purpose\n";
7398 PrintEntry(Parser.getGotLazyResolver(), "Lazy resolver");
7399 if (Parser.getGotModulePointer())
7400 PrintEntry(Parser.getGotModulePointer(), "Module pointer (GNU extension)");
7401
7402 if (!Parser.getLocalEntries().empty()) {
7403 OS << "\n";
7404 OS << " Local entries:\n";
7405 if (ELFT::Is64Bits)
7406 OS << " Address Access Initial\n";
7407 else
7408 OS << " Address Access Initial\n";
7409 for (auto &E : Parser.getLocalEntries())
7410 PrintEntry(&E, "");
7411 }
7412
7413 if (Parser.IsStatic)
7414 return;
7415
7416 if (!Parser.getGlobalEntries().empty()) {
7417 OS << "\n";
7418 OS << " Global entries:\n";
7419 if (ELFT::Is64Bits)
7420 OS << " Address Access Initial Sym.Val."
7421 << " Type Ndx Name\n";
7422 else
7423 OS << " Address Access Initial Sym.Val. Type Ndx Name\n";
7424
7425 DataRegion<Elf_Word> ShndxTable(
7426 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
7427 for (auto &E : Parser.getGlobalEntries()) {
7428 const Elf_Sym &Sym = *Parser.getGotSym(&E);
7429 const Elf_Sym &FirstSym = this->dynamic_symbols()[0];
7430 std::string SymName = this->getFullSymbolName(
7431 Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
7432
7433 OS.PadToColumn(NewCol: 2);
7434 OS << to_string(format_hex_no_prefix(Parser.getGotAddress(&E), 8 + Bias));
7435 OS.PadToColumn(NewCol: 11 + Bias);
7436 OS << to_string(format_decimal(Parser.getGotOffset(&E), 6)) + "(gp)";
7437 OS.PadToColumn(NewCol: 22 + Bias);
7438 OS << to_string(format_hex_no_prefix(E, 8 + Bias));
7439 OS.PadToColumn(NewCol: 31 + 2 * Bias);
7440 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
7441 OS.PadToColumn(NewCol: 40 + 3 * Bias);
7442 OS << getElfSymbolTypes().toStringOrHex(Sym.getType(), 1);
7443 OS.PadToColumn(NewCol: 48 + 3 * Bias);
7444 OS << getSymbolSectionNdx(Symbol: Sym, SymIndex: &Sym - this->dynamic_symbols().begin(),
7445 ShndxTable);
7446 OS.PadToColumn(NewCol: 52 + 3 * Bias);
7447 OS << SymName << "\n";
7448 }
7449 }
7450
7451 if (!Parser.getOtherEntries().empty())
7452 OS << "\n Number of TLS and multi-GOT entries "
7453 << Parser.getOtherEntries().size() << "\n";
7454}
7455
7456template <class ELFT>
7457void GNUELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
7458 size_t Bias = ELFT::Is64Bits ? 8 : 0;
7459 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
7460 OS.PadToColumn(NewCol: 2);
7461 OS << format_hex_no_prefix(Parser.getPltAddress(E), 8 + Bias);
7462 OS.PadToColumn(NewCol: 11 + Bias);
7463 OS << format_hex_no_prefix(*E, 8 + Bias);
7464 OS.PadToColumn(NewCol: 20 + 2 * Bias);
7465 OS << Purpose << "\n";
7466 };
7467
7468 OS << "PLT GOT:\n\n";
7469
7470 OS << " Reserved entries:\n";
7471 OS << " Address Initial Purpose\n";
7472 PrintEntry(Parser.getPltLazyResolver(), "PLT lazy resolver");
7473 if (Parser.getPltModulePointer())
7474 PrintEntry(Parser.getPltModulePointer(), "Module pointer");
7475
7476 if (!Parser.getPltEntries().empty()) {
7477 OS << "\n";
7478 OS << " Entries:\n";
7479 OS << " Address Initial Sym.Val. Type Ndx Name\n";
7480 DataRegion<Elf_Word> ShndxTable(
7481 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
7482 for (auto &E : Parser.getPltEntries()) {
7483 const Elf_Sym &Sym = *Parser.getPltSym(&E);
7484 const Elf_Sym &FirstSym = *cantFail(
7485 this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
7486 std::string SymName = this->getFullSymbolName(
7487 Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
7488
7489 OS.PadToColumn(NewCol: 2);
7490 OS << to_string(format_hex_no_prefix(Parser.getPltAddress(&E), 8 + Bias));
7491 OS.PadToColumn(NewCol: 11 + Bias);
7492 OS << to_string(format_hex_no_prefix(E, 8 + Bias));
7493 OS.PadToColumn(NewCol: 20 + 2 * Bias);
7494 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
7495 OS.PadToColumn(NewCol: 29 + 3 * Bias);
7496 OS << getElfSymbolTypes().toStringOrHex(Sym.getType(), 1);
7497 OS.PadToColumn(NewCol: 37 + 3 * Bias);
7498 OS << getSymbolSectionNdx(Symbol: Sym, SymIndex: &Sym - this->dynamic_symbols().begin(),
7499 ShndxTable);
7500 OS.PadToColumn(NewCol: 41 + 3 * Bias);
7501 OS << SymName << "\n";
7502 }
7503 }
7504}
7505
7506template <class ELFT>
7507Expected<const Elf_Mips_ABIFlags<ELFT> *>
7508getMipsAbiFlagsSection(const ELFDumper<ELFT> &Dumper) {
7509 const typename ELFT::Shdr *Sec = Dumper.findSectionByName(".MIPS.abiflags");
7510 if (Sec == nullptr)
7511 return nullptr;
7512
7513 constexpr StringRef ErrPrefix = "unable to read the .MIPS.abiflags section: ";
7514 Expected<ArrayRef<uint8_t>> DataOrErr =
7515 Dumper.getElfObject().getELFFile().getSectionContents(*Sec);
7516 if (!DataOrErr)
7517 return createError(Err: ErrPrefix + toString(E: DataOrErr.takeError()));
7518
7519 if (DataOrErr->size() != sizeof(Elf_Mips_ABIFlags<ELFT>))
7520 return createError(Err: ErrPrefix + "it has a wrong size (" +
7521 Twine(DataOrErr->size()) + ")");
7522 return reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(DataOrErr->data());
7523}
7524
7525template <class ELFT> void GNUELFDumper<ELFT>::printMipsABIFlags() {
7526 const Elf_Mips_ABIFlags<ELFT> *Flags = nullptr;
7527 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
7528 getMipsAbiFlagsSection(*this))
7529 Flags = *SecOrErr;
7530 else
7531 this->reportUniqueWarning(SecOrErr.takeError());
7532 if (!Flags)
7533 return;
7534
7535 OS << "MIPS ABI Flags Version: " << Flags->version << "\n\n";
7536 OS << "ISA: MIPS" << int(Flags->isa_level);
7537 if (Flags->isa_rev > 1)
7538 OS << "r" << int(Flags->isa_rev);
7539 OS << "\n";
7540 OS << "GPR size: " << getMipsRegisterSize(Flags->gpr_size) << "\n";
7541 OS << "CPR1 size: " << getMipsRegisterSize(Flags->cpr1_size) << "\n";
7542 OS << "CPR2 size: " << getMipsRegisterSize(Flags->cpr2_size) << "\n";
7543 OS << "FP ABI: " << EnumStrings(ElfMipsFpABIType).toStringOrHex(Flags->fp_abi)
7544 << "\n";
7545 OS << "ISA Extension: "
7546 << EnumStrings(ElfMipsISAExtType).toStringOrHex(Flags->isa_ext) << "\n";
7547 if (Flags->ases == 0)
7548 OS << "ASEs: None\n";
7549 else
7550 // FIXME: Print each flag on a separate line.
7551 OS << "ASEs: " << printFlags(Flags->ases, EnumStrings(ElfMipsASEFlags))
7552 << "\n";
7553 OS << "FLAGS 1: " << format_hex_no_prefix(Flags->flags1, 8, false) << "\n";
7554 OS << "FLAGS 2: " << format_hex_no_prefix(Flags->flags2, 8, false) << "\n";
7555 OS << "\n";
7556}
7557
7558template <class ELFT> void LLVMELFDumper<ELFT>::printFileHeaders() {
7559 const Elf_Ehdr &E = this->Obj.getHeader();
7560 {
7561 DictScope D(W, "ElfHeader");
7562 {
7563 DictScope D(W, "Ident");
7564 W.printBinary(Label: "Magic",
7565 Value: ArrayRef<unsigned char>(E.e_ident).slice(N: ELF::EI_MAG0, M: 4));
7566 W.printEnum("Class", E.e_ident[ELF::EI_CLASS], EnumStrings(ElfClass));
7567 W.printEnum("DataEncoding", E.e_ident[ELF::EI_DATA],
7568 EnumStrings(ElfDataEncoding));
7569 W.printNumber("FileVersion", E.e_ident[ELF::EI_VERSION]);
7570
7571 auto OSABI = EnumStrings(ElfOSABI);
7572 if (E.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH &&
7573 E.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) {
7574 switch (E.e_machine) {
7575 case ELF::EM_AMDGPU:
7576 OSABI = EnumStrings(AMDGPUElfOSABI);
7577 break;
7578 case ELF::EM_ARM:
7579 OSABI = EnumStrings(ARMElfOSABI);
7580 break;
7581 case ELF::EM_TI_C6000:
7582 OSABI = EnumStrings(C6000ElfOSABI);
7583 break;
7584 }
7585 }
7586 W.printEnum("OS/ABI", E.e_ident[ELF::EI_OSABI], OSABI);
7587 W.printNumber("ABIVersion", E.e_ident[ELF::EI_ABIVERSION]);
7588 W.printBinary(Label: "Unused",
7589 Value: ArrayRef<unsigned char>(E.e_ident).slice(N: ELF::EI_PAD));
7590 }
7591
7592 std::string TypeStr;
7593 if (StringRef Name = EnumStrings(ElfObjectFileType).toString(E.e_type);
7594 !Name.empty()) {
7595 TypeStr = Name.str();
7596 } else {
7597 if (E.e_type >= ET_LOPROC)
7598 TypeStr = "Processor Specific";
7599 else if (E.e_type >= ET_LOOS)
7600 TypeStr = "OS Specific";
7601 else
7602 TypeStr = "Unknown";
7603 }
7604 W.printString("Type", TypeStr + " (0x" +
7605 utohexstr(E.e_type, /*LowerCase=*/true) + ")");
7606
7607 W.printEnum("Machine", E.e_machine, EnumStrings(ElfMachineType));
7608 W.printNumber("Version", E.e_version);
7609 W.printHex("Entry", E.e_entry);
7610 W.printHex("ProgramHeaderOffset", E.e_phoff);
7611 W.printHex("SectionHeaderOffset", E.e_shoff);
7612 if (E.e_machine == EM_MIPS)
7613 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderMipsFlags),
7614 unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
7615 unsigned(ELF::EF_MIPS_MACH));
7616 else if (E.e_machine == EM_AMDGPU) {
7617 switch (E.e_ident[ELF::EI_ABIVERSION]) {
7618 default:
7619 W.printHex("Flags", E.e_flags);
7620 break;
7621 case 0:
7622 // ELFOSABI_AMDGPU_PAL, ELFOSABI_AMDGPU_MESA3D support *_V3 flags.
7623 [[fallthrough]];
7624 case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
7625 W.printFlags("Flags", E.e_flags,
7626 EnumStrings(ElfHeaderAMDGPUFlagsABIVersion3),
7627 unsigned(ELF::EF_AMDGPU_MACH));
7628 break;
7629 case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
7630 case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
7631 W.printFlags("Flags", E.e_flags,
7632 EnumStrings(ElfHeaderAMDGPUFlagsABIVersion4),
7633 unsigned(ELF::EF_AMDGPU_MACH),
7634 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
7635 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
7636 break;
7637 case ELF::ELFABIVERSION_AMDGPU_HSA_V6: {
7638 std::optional<FlagEntry> VerFlagEntry;
7639 // The string needs to remain alive from the moment we create a
7640 // FlagEntry until printFlags is done.
7641 std::string FlagStr;
7642 if (auto VersionFlag = E.e_flags & ELF::EF_AMDGPU_GENERIC_VERSION) {
7643 unsigned Version =
7644 VersionFlag >> ELF::EF_AMDGPU_GENERIC_VERSION_OFFSET;
7645 FlagStr = "EF_AMDGPU_GENERIC_VERSION_V" + std::to_string(val: Version);
7646 VerFlagEntry = FlagEntry(FlagStr, VersionFlag);
7647 }
7648 W.printFlags(
7649 "Flags", E.e_flags, EnumStrings(ElfHeaderAMDGPUFlagsABIVersion4),
7650 unsigned(ELF::EF_AMDGPU_MACH),
7651 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
7652 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4),
7653 VerFlagEntry ? ArrayRef(*VerFlagEntry) : ArrayRef<FlagEntry>());
7654 break;
7655 }
7656 }
7657 } else if (E.e_machine == EM_RISCV)
7658 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderRISCVFlags));
7659 else if (E.e_machine == EM_SPARC32PLUS || E.e_machine == EM_SPARCV9)
7660 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderSPARCFlags),
7661 unsigned(ELF::EF_SPARCV9_MM));
7662 else if (E.e_machine == EM_AVR)
7663 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderAVRFlags),
7664 unsigned(ELF::EF_AVR_ARCH_MASK));
7665 else if (E.e_machine == EM_LOONGARCH)
7666 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderLoongArchFlags),
7667 unsigned(ELF::EF_LOONGARCH_ABI_MODIFIER_MASK),
7668 unsigned(ELF::EF_LOONGARCH_OBJABI_MASK));
7669 else if (E.e_machine == EM_XTENSA)
7670 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderXtensaFlags),
7671 unsigned(ELF::EF_XTENSA_MACH));
7672 else if (E.e_machine == EM_CUDA)
7673 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderNVPTXFlags),
7674 unsigned(ELF::EF_CUDA_SM));
7675 else
7676 W.printFlags("Flags", E.e_flags);
7677 W.printNumber("HeaderSize", E.e_ehsize);
7678 W.printNumber("ProgramHeaderEntrySize", E.e_phentsize);
7679 W.printString("ProgramHeaderCount", this->getProgramHeadersNumString());
7680 W.printNumber("SectionHeaderEntrySize", E.e_shentsize);
7681 W.printString("SectionHeaderCount",
7682 getSectionHeadersNumString(this->Obj, this->FileName));
7683 W.printString("StringTableSectionIndex",
7684 getSectionHeaderTableIndexString(this->Obj, this->FileName));
7685 }
7686}
7687
7688template <class ELFT> void LLVMELFDumper<ELFT>::printGroupSections() {
7689 DictScope Lists(W, "Groups");
7690 std::vector<GroupSection> V = this->getGroups();
7691 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(Groups: V);
7692 for (const GroupSection &G : V) {
7693 DictScope D(W, "Group");
7694 W.printNumber(Label: "Name", Str: G.Name, Value: G.ShName);
7695 W.printNumber(Label: "Index", Value: G.Index);
7696 W.printNumber(Label: "Link", Value: G.Link);
7697 W.printNumber(Label: "Info", Value: G.Info);
7698 W.printHex(Label: "Type", Str: getGroupType(Flag: G.Type), Value: G.Type);
7699 W.printString(Label: "Signature", Value: G.Signature);
7700
7701 ListScope L(W, getGroupSectionHeaderName());
7702 for (const GroupMember &GM : G.Members) {
7703 const GroupSection *MainGroup = Map[GM.Index];
7704 if (MainGroup != &G)
7705 this->reportUniqueWarning(
7706 "section with index " + Twine(GM.Index) +
7707 ", included in the group section with index " +
7708 Twine(MainGroup->Index) +
7709 ", was also found in the group section with index " +
7710 Twine(G.Index));
7711 printSectionGroupMembers(Name: GM.Name, Idx: GM.Index);
7712 }
7713 }
7714
7715 if (V.empty())
7716 printEmptyGroupMessage();
7717}
7718
7719template <class ELFT>
7720std::string LLVMELFDumper<ELFT>::getGroupSectionHeaderName() const {
7721 return "Section(s) in group";
7722}
7723
7724template <class ELFT>
7725void LLVMELFDumper<ELFT>::printSectionGroupMembers(StringRef Name,
7726 uint64_t Idx) const {
7727 W.startLine() << Name << " (" << Idx << ")\n";
7728}
7729
7730template <class ELFT> void LLVMELFDumper<ELFT>::printRelocations() {
7731 ListScope D(W, "Relocations");
7732
7733 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
7734 if (!isRelocationSec<ELFT>(Sec, this->Obj.getHeader()))
7735 continue;
7736
7737 StringRef Name = this->getPrintableSectionName(Sec);
7738 unsigned SecNdx = &Sec - &cantFail(this->Obj.sections()).front();
7739 printRelocationSectionInfo(Sec, Name, SecNdx);
7740 }
7741}
7742
7743template <class ELFT>
7744void LLVMELFDumper<ELFT>::printExpandedRelRelaReloc(const Relocation<ELFT> &R,
7745 StringRef SymbolName,
7746 StringRef RelocName) {
7747 DictScope Group(W, "Relocation");
7748 W.printHex("Offset", R.Offset);
7749 W.printNumber("Type", RelocName, R.Type);
7750 W.printNumber("Symbol", !SymbolName.empty() ? SymbolName : "-", R.Symbol);
7751 if (R.Addend)
7752 W.printHex("Addend", (uintX_t)*R.Addend);
7753}
7754
7755template <class ELFT>
7756void LLVMELFDumper<ELFT>::printDefaultRelRelaReloc(const Relocation<ELFT> &R,
7757 StringRef SymbolName,
7758 StringRef RelocName) {
7759 raw_ostream &OS = W.startLine();
7760 OS << W.hex(R.Offset) << " " << RelocName << " "
7761 << (!SymbolName.empty() ? SymbolName : "-");
7762 if (R.Addend)
7763 OS << " " << W.hex((uintX_t)*R.Addend);
7764 OS << "\n";
7765}
7766
7767template <class ELFT>
7768void LLVMELFDumper<ELFT>::printRelocationSectionInfo(const Elf_Shdr &Sec,
7769 StringRef Name,
7770 const unsigned SecNdx) {
7771 DictScope D(W, (Twine("Section (") + Twine(SecNdx) + ") " + Name).str());
7772 this->printRelocationsHelper(Sec);
7773}
7774
7775template <class ELFT> void LLVMELFDumper<ELFT>::printEmptyGroupMessage() const {
7776 W.startLine() << "There are no group sections in the file.\n";
7777}
7778
7779template <class ELFT>
7780void LLVMELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
7781 const RelSymbol<ELFT> &RelSym) {
7782 StringRef SymbolName = RelSym.Name;
7783 if (RelSym.Sym && RelSym.Name.empty())
7784 SymbolName = "<null>";
7785 SmallString<32> RelocName;
7786 StringRef RelocTypeName = this->getRelocTypeName(R.Type, RelocName);
7787
7788 if (opts::ExpandRelocs) {
7789 printExpandedRelRelaReloc(R, SymbolName, RelocName: RelocTypeName);
7790 } else {
7791 printDefaultRelRelaReloc(R, SymbolName, RelocName: RelocTypeName);
7792 }
7793}
7794
7795template <class ELFT> void LLVMELFDumper<ELFT>::printSectionHeaders() {
7796 ListScope SectionsD(W, "Sections");
7797
7798 int SectionIndex = -1;
7799 auto FlagsList =
7800 getSectionFlagsForTarget(this->Obj.getHeader().e_ident[ELF::EI_OSABI],
7801 this->Obj.getHeader().e_machine);
7802 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
7803 DictScope SectionD(W, "Section");
7804 W.printNumber(Label: "Index", Value: ++SectionIndex);
7805 W.printNumber("Name", this->getPrintableSectionName(Sec), Sec.sh_name);
7806 W.printHex("Type",
7807 object::getELFSectionTypeName(Machine: this->Obj.getHeader().e_machine,
7808 Type: Sec.sh_type),
7809 Sec.sh_type);
7810 SmallVector<FlagEntry> SetFlags;
7811 for (const auto *Flag : FlagsList)
7812 if ((Sec.sh_flags & Flag->value()) == Flag->value())
7813 SetFlags.emplace_back(Flag->name(), Flag->value());
7814 W.printFlags("Flags", Sec.sh_flags, SetFlags);
7815 W.printHex("Address", Sec.sh_addr);
7816 W.printHex("Offset", Sec.sh_offset);
7817 W.printNumber("Size", Sec.sh_size);
7818 W.printNumber("Link", Sec.sh_link);
7819 W.printNumber("Info", Sec.sh_info);
7820 W.printNumber("AddressAlignment", Sec.sh_addralign);
7821 W.printNumber("EntrySize", Sec.sh_entsize);
7822
7823 if (opts::SectionRelocations) {
7824 ListScope D(W, "Relocations");
7825 this->printRelocationsHelper(Sec);
7826 }
7827
7828 if (opts::SectionSymbols) {
7829 ListScope D(W, "Symbols");
7830 if (this->DotSymtabSec) {
7831 StringRef StrTable = unwrapOrError(
7832 this->FileName,
7833 this->Obj.getStringTableForSymtab(*this->DotSymtabSec));
7834 ArrayRef<Elf_Word> ShndxTable = this->getShndxTable(this->DotSymtabSec);
7835
7836 typename ELFT::SymRange Symbols = unwrapOrError(
7837 this->FileName, this->Obj.symbols(this->DotSymtabSec));
7838 for (const Elf_Sym &Sym : Symbols) {
7839 const Elf_Shdr *SymSec = unwrapOrError(
7840 this->FileName,
7841 this->Obj.getSection(Sym, this->DotSymtabSec, ShndxTable));
7842 if (SymSec == &Sec)
7843 printSymbol(Symbol: Sym, SymIndex: &Sym - &Symbols[0], ShndxTable, StrTable, IsDynamic: false,
7844 /*NonVisibilityBitsUsed=*/false,
7845 /*ExtraSymInfo=*/false);
7846 }
7847 }
7848 }
7849
7850 if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) {
7851 ArrayRef<uint8_t> Data =
7852 unwrapOrError(this->FileName, this->Obj.getSectionContents(Sec));
7853 W.printBinaryBlock(
7854 Label: "SectionData",
7855 Value: StringRef(reinterpret_cast<const char *>(Data.data()), Data.size()));
7856 }
7857 }
7858}
7859
7860template <class ELFT>
7861void LLVMELFDumper<ELFT>::printSymbolSection(
7862 const Elf_Sym &Symbol, unsigned SymIndex,
7863 DataRegion<Elf_Word> ShndxTable) const {
7864 auto GetSectionSpecialType = [&]() -> std::optional<StringRef> {
7865 if (Symbol.isUndefined())
7866 return StringRef("Undefined");
7867 if (Symbol.isProcessorSpecific())
7868 return StringRef("Processor Specific");
7869 if (Symbol.isOSSpecific())
7870 return StringRef("Operating System Specific");
7871 if (Symbol.isAbsolute())
7872 return StringRef("Absolute");
7873 if (Symbol.isCommon())
7874 return StringRef("Common");
7875 if (Symbol.isReserved() && Symbol.st_shndx != SHN_XINDEX)
7876 return StringRef("Reserved");
7877 return std::nullopt;
7878 };
7879
7880 if (std::optional<StringRef> Type = GetSectionSpecialType()) {
7881 W.printHex("Section", *Type, Symbol.st_shndx);
7882 return;
7883 }
7884
7885 Expected<unsigned> SectionIndex =
7886 this->getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
7887 if (!SectionIndex) {
7888 assert(Symbol.st_shndx == SHN_XINDEX &&
7889 "getSymbolSectionIndex should only fail due to an invalid "
7890 "SHT_SYMTAB_SHNDX table/reference");
7891 this->reportUniqueWarning(SectionIndex.takeError());
7892 W.printHex(Label: "Section", Str: "Reserved", Value: SHN_XINDEX);
7893 return;
7894 }
7895
7896 Expected<StringRef> SectionName =
7897 this->getSymbolSectionName(Symbol, *SectionIndex);
7898 if (!SectionName) {
7899 // Don't report an invalid section name if the section headers are missing.
7900 // In such situations, all sections will be "invalid".
7901 if (!this->ObjF.sections().empty())
7902 this->reportUniqueWarning(SectionName.takeError());
7903 else
7904 consumeError(Err: SectionName.takeError());
7905 W.printHex(Label: "Section", Str: "<?>", Value: *SectionIndex);
7906 } else {
7907 W.printHex(Label: "Section", Str: *SectionName, Value: *SectionIndex);
7908 }
7909}
7910
7911template <class ELFT>
7912void LLVMELFDumper<ELFT>::printSymbolOtherField(const Elf_Sym &Symbol) const {
7913 auto SymOtherFlags =
7914 this->getOtherFlagsFromSymbol(this->Obj.getHeader(), Symbol);
7915 SmallVector<FlagEntry> SetFlags;
7916 unsigned EnumMask = 0x3u;
7917 for (const auto *Flag : SymOtherFlags) {
7918 if (Flag->value() & EnumMask) {
7919 if ((Symbol.st_other & EnumMask) == Flag->value())
7920 SetFlags.emplace_back(Flag->name(), Flag->value());
7921 } else if (Flag->value()) {
7922 if ((Symbol.st_other & Flag->value()) == Flag->value())
7923 SetFlags.emplace_back(Flag->name(), Flag->value());
7924 }
7925 }
7926 W.printFlags("Other", Symbol.st_other, SetFlags);
7927}
7928
7929template <class ELFT>
7930void LLVMELFDumper<ELFT>::printZeroSymbolOtherField(
7931 const Elf_Sym &Symbol) const {
7932 assert(Symbol.st_other == 0 && "non-zero Other Field");
7933 // Usually st_other flag is zero. Do not pollute the output
7934 // by flags enumeration in that case.
7935 W.printNumber(Label: "Other", Value: 0);
7936}
7937
7938template <class ELFT>
7939void LLVMELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
7940 DataRegion<Elf_Word> ShndxTable,
7941 std::optional<StringRef> StrTable,
7942 bool IsDynamic,
7943 bool /*NonVisibilityBitsUsed*/,
7944 bool /*ExtraSymInfo*/) const {
7945 std::string FullSymbolName = this->getFullSymbolName(
7946 Symbol, SymIndex, ShndxTable, StrTable, IsDynamic);
7947 unsigned char SymbolType = Symbol.getType();
7948
7949 DictScope D(W, "Symbol");
7950 W.printNumber("Name", FullSymbolName, Symbol.st_name);
7951 W.printHex("Value", Symbol.st_value);
7952 W.printNumber("Size", Symbol.st_size);
7953 W.printEnum("Binding", Symbol.getBinding(), EnumStrings(ElfSymbolBindings));
7954 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
7955 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
7956 W.printEnum(Label: "Type", Value: SymbolType, EnumValues: EnumStrings(AMDGPUSymbolTypes));
7957 else
7958 W.printEnum(Label: "Type", Value: SymbolType, EnumValues: getElfSymbolTypes());
7959 if (Symbol.st_other == 0)
7960 printZeroSymbolOtherField(Symbol);
7961 else
7962 printSymbolOtherField(Symbol);
7963 printSymbolSection(Symbol, SymIndex, ShndxTable);
7964}
7965
7966template <class ELFT>
7967void LLVMELFDumper<ELFT>::printSymbols(bool PrintSymbols,
7968 bool PrintDynamicSymbols,
7969 bool ExtraSymInfo) {
7970 if (PrintSymbols) {
7971 ListScope Group(W, "Symbols");
7972 this->printSymbolsHelper(false, ExtraSymInfo);
7973 }
7974 if (PrintDynamicSymbols) {
7975 ListScope Group(W, "DynamicSymbols");
7976 this->printSymbolsHelper(true, ExtraSymInfo);
7977 }
7978}
7979
7980template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicTable() {
7981 Elf_Dyn_Range Table = this->dynamic_table();
7982 if (Table.empty())
7983 return;
7984
7985 W.startLine() << "DynamicSection [ (" << Table.size() << " entries)\n";
7986
7987 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table);
7988 // The "Name/Value" column should be indented from the "Type" column by N
7989 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
7990 // space (1) = -3.
7991 W.startLine() << " Tag" << std::string(ELFT::Is64Bits ? 16 : 8, ' ')
7992 << "Type" << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
7993
7994 std::string ValueFmt = "%-" + std::to_string(val: MaxTagSize) + "s ";
7995 for (auto Entry : Table) {
7996 uintX_t Tag = Entry.getTag();
7997 std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
7998 W.startLine() << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10, true)
7999 << " "
8000 << format(ValueFmt.c_str(),
8001 this->Obj.getDynamicTagAsString(Tag).c_str())
8002 << Value << "\n";
8003 }
8004 W.startLine() << "]\n";
8005}
8006
8007template <class ELFT>
8008void JSONELFDumper<ELFT>::printAuxillaryDynamicTableEntryInfo(
8009 const Elf_Dyn &Entry) {
8010 auto FormatFlags = [this, Value = Entry.getVal()](auto Flags) {
8011 ListScope L(this->W, "Flags");
8012 for (const auto &Flag : Flags) {
8013 if (Flag.value() != 0 && (Value & Flag.value()) == Flag.value())
8014 this->W.printString(Flag.name());
8015 }
8016 };
8017 switch (Entry.getTag()) {
8018 case DT_SONAME:
8019 this->W.printString("Name", this->getDynamicString(Entry.getVal()));
8020 break;
8021 case DT_AUXILIARY:
8022 case DT_FILTER:
8023 case DT_NEEDED:
8024 this->W.printString("Library", this->getDynamicString(Entry.getVal()));
8025 break;
8026 case DT_USED:
8027 this->W.printString("Object", this->getDynamicString(Entry.getVal()));
8028 break;
8029 case DT_RPATH:
8030 case DT_RUNPATH: {
8031 StringRef Value = this->getDynamicString(Entry.getVal());
8032 ListScope L(this->W, "Path");
8033 while (!Value.empty()) {
8034 auto [Front, Back] = Value.split(Separator: ':');
8035 this->W.printString(Front);
8036 Value = Back;
8037 }
8038 break;
8039 }
8040 case DT_FLAGS:
8041 FormatFlags(EnumStrings(ElfDynamicDTFlags));
8042 break;
8043 case DT_FLAGS_1:
8044 FormatFlags(EnumStrings(ElfDynamicDTFlags1));
8045 break;
8046 default:
8047 return;
8048 }
8049}
8050
8051template <class ELFT> void JSONELFDumper<ELFT>::printDynamicTable() {
8052 Elf_Dyn_Range Table = this->dynamic_table();
8053 ListScope L(this->W, "DynamicSection");
8054 for (const auto &Entry : Table) {
8055 DictScope D(this->W);
8056 uintX_t Tag = Entry.getTag();
8057 this->W.printHex("Tag", Tag);
8058 this->W.printString("Type", this->Obj.getDynamicTagAsString(Tag));
8059 this->W.printHex("Value", Entry.getVal());
8060 this->printAuxillaryDynamicTableEntryInfo(Entry);
8061 }
8062}
8063
8064template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicRelocations() {
8065 W.startLine() << "Dynamic Relocations {\n";
8066 W.indent();
8067 this->printDynamicRelocationsHelper();
8068 W.unindent();
8069 W.startLine() << "}\n";
8070}
8071
8072template <class ELFT>
8073void LLVMELFDumper<ELFT>::printProgramHeaders(
8074 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
8075 if (PrintProgramHeaders)
8076 printProgramHeaders();
8077 if (PrintSectionMapping == cl::boolOrDefault::BOU_TRUE)
8078 printSectionMapping();
8079}
8080
8081template <class ELFT> void LLVMELFDumper<ELFT>::printProgramHeaders() {
8082 ListScope L(W, "ProgramHeaders");
8083
8084 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
8085 if (!PhdrsOrErr) {
8086 this->reportUniqueWarning("unable to dump program headers: " +
8087 toString(PhdrsOrErr.takeError()));
8088 return;
8089 }
8090
8091 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
8092 DictScope P(W, "ProgramHeader");
8093 StringRef Type =
8094 segmentTypeToString(this->Obj.getHeader().e_machine, Phdr.p_type);
8095
8096 W.printHex("Type", Type.empty() ? "Unknown" : Type, Phdr.p_type);
8097 W.printHex("Offset", Phdr.p_offset);
8098 W.printHex("VirtualAddress", Phdr.p_vaddr);
8099 W.printHex("PhysicalAddress", Phdr.p_paddr);
8100 W.printNumber("FileSize", Phdr.p_filesz);
8101 W.printNumber("MemSize", Phdr.p_memsz);
8102 W.printFlags("Flags", Phdr.p_flags, EnumStrings(ElfSegmentFlags));
8103 W.printNumber("Alignment", Phdr.p_align);
8104 }
8105}
8106
8107template <class ELFT>
8108void LLVMELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
8109 ListScope SS(W, "VersionSymbols");
8110 if (!Sec)
8111 return;
8112
8113 StringRef StrTable;
8114 ArrayRef<Elf_Sym> Syms;
8115 const Elf_Shdr *SymTabSec;
8116 Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
8117 this->getVersionTable(*Sec, &Syms, &StrTable, &SymTabSec);
8118 if (!VerTableOrErr) {
8119 this->reportUniqueWarning(VerTableOrErr.takeError());
8120 return;
8121 }
8122
8123 if (StrTable.empty() || Syms.empty() || Syms.size() != VerTableOrErr->size())
8124 return;
8125
8126 ArrayRef<Elf_Word> ShNdxTable = this->getShndxTable(SymTabSec);
8127 for (size_t I = 0, E = Syms.size(); I < E; ++I) {
8128 DictScope S(W, "Symbol");
8129 W.printNumber("Version", (*VerTableOrErr)[I].vs_index & VERSYM_VERSION);
8130 W.printString("Name",
8131 this->getFullSymbolName(Syms[I], I, ShNdxTable, StrTable,
8132 /*IsDynamic=*/true));
8133 }
8134}
8135
8136constexpr EnumStringDef<unsigned, 2> SymVersionFlagsDefs[] = {
8137 {.Names: {"Base", "BASE"}, .Value: VER_FLG_BASE},
8138 {.Names: {"Weak", "WEAK"}, .Value: VER_FLG_WEAK},
8139 {.Names: {"Info", "INFO"}, .Value: VER_FLG_INFO},
8140};
8141constexpr auto SymVersionFlags = BUILD_ENUM_STRINGS(SymVersionFlagsDefs);
8142
8143template <class ELFT>
8144void LLVMELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
8145 ListScope SD(W, "VersionDefinitions");
8146 if (!Sec)
8147 return;
8148
8149 Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
8150 if (!V) {
8151 this->reportUniqueWarning(V.takeError());
8152 return;
8153 }
8154
8155 for (const VerDef &D : *V) {
8156 DictScope Def(W, "Definition");
8157 W.printNumber(Label: "Version", Value: D.Version);
8158 W.printFlags(Label: "Flags", Value: D.Flags, Flags: EnumStrings(SymVersionFlags));
8159 W.printNumber(Label: "Index", Value: D.Ndx);
8160 W.printNumber(Label: "Hash", Value: D.Hash);
8161 W.printString(Label: "Name", Value: D.Name);
8162 W.printList(
8163 "Predecessors", D.AuxV,
8164 [](raw_ostream &OS, const VerdAux &Aux) { OS << Aux.Name.c_str(); });
8165 }
8166}
8167
8168template <class ELFT>
8169void LLVMELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
8170 ListScope SD(W, "VersionRequirements");
8171 if (!Sec)
8172 return;
8173
8174 Expected<std::vector<VerNeed>> V =
8175 this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
8176 if (!V) {
8177 this->reportUniqueWarning(V.takeError());
8178 return;
8179 }
8180
8181 for (const VerNeed &VN : *V) {
8182 DictScope Entry(W, "Dependency");
8183 W.printNumber(Label: "Version", Value: VN.Version);
8184 W.printNumber(Label: "Count", Value: VN.Cnt);
8185 W.printString(Label: "FileName", Value: VN.File.c_str());
8186
8187 ListScope L(W, "Entries");
8188 for (const VernAux &Aux : VN.AuxV) {
8189 DictScope Entry(W, "Entry");
8190 W.printNumber(Label: "Hash", Value: Aux.Hash);
8191 W.printFlags(Label: "Flags", Value: Aux.Flags, Flags: EnumStrings(SymVersionFlags));
8192 W.printNumber(Label: "Index", Value: Aux.Other);
8193 W.printString(Label: "Name", Value: Aux.Name.c_str());
8194 }
8195 }
8196}
8197
8198template <class ELFT>
8199void LLVMELFDumper<ELFT>::printHashHistogramStats(size_t NBucket,
8200 size_t MaxChain,
8201 size_t TotalSyms,
8202 ArrayRef<size_t> Count,
8203 bool IsGnu) const {
8204 StringRef HistName = IsGnu ? "GnuHashHistogram" : "HashHistogram";
8205 StringRef BucketName = IsGnu ? "Bucket" : "Chain";
8206 StringRef ListName = IsGnu ? "Buckets" : "Chains";
8207 DictScope Outer(W, HistName);
8208 W.printNumber(Label: "TotalBuckets", Value: NBucket);
8209 ListScope Buckets(W, ListName);
8210 size_t CumulativeNonZero = 0;
8211 for (size_t I = 0; I < MaxChain; ++I) {
8212 CumulativeNonZero += Count[I] * I;
8213 DictScope Bucket(W, BucketName);
8214 W.printNumber(Label: "Length", Value: I);
8215 W.printNumber(Label: "Count", Value: Count[I]);
8216 W.printNumber(Label: "Percentage", Value: (float)(Count[I] * 100.0) / NBucket);
8217 W.printNumber(Label: "Coverage", Value: (float)(CumulativeNonZero * 100.0) / TotalSyms);
8218 }
8219}
8220
8221// Returns true if rel/rela section exists, and populates SymbolIndices.
8222// Otherwise returns false.
8223template <class ELFT>
8224static bool getSymbolIndices(const typename ELFT::Shdr *CGRelSection,
8225 const ELFFile<ELFT> &Obj,
8226 const LLVMELFDumper<ELFT> *Dumper,
8227 SmallVector<uint32_t, 128> &SymbolIndices) {
8228 if (!CGRelSection) {
8229 Dumper->reportUniqueWarning(
8230 "relocation section for a call graph section doesn't exist");
8231 return false;
8232 }
8233
8234 if (CGRelSection->sh_type == SHT_REL) {
8235 typename ELFT::RelRange CGProfileRel;
8236 Expected<typename ELFT::RelRange> CGProfileRelOrError =
8237 Obj.rels(*CGRelSection);
8238 if (!CGProfileRelOrError) {
8239 Dumper->reportUniqueWarning("unable to load relocations for "
8240 "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
8241 toString(CGProfileRelOrError.takeError()));
8242 return false;
8243 }
8244
8245 CGProfileRel = *CGProfileRelOrError;
8246 for (const typename ELFT::Rel &Rel : CGProfileRel)
8247 SymbolIndices.push_back(Elt: Rel.getSymbol(Obj.isMips64EL()));
8248 } else {
8249 // MC unconditionally produces SHT_REL, but GNU strip/objcopy may convert
8250 // the format to SHT_RELA
8251 // (https://sourceware.org/bugzilla/show_bug.cgi?id=28035)
8252 typename ELFT::RelaRange CGProfileRela;
8253 Expected<typename ELFT::RelaRange> CGProfileRelaOrError =
8254 Obj.relas(*CGRelSection);
8255 if (!CGProfileRelaOrError) {
8256 Dumper->reportUniqueWarning("unable to load relocations for "
8257 "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
8258 toString(CGProfileRelaOrError.takeError()));
8259 return false;
8260 }
8261
8262 CGProfileRela = *CGProfileRelaOrError;
8263 for (const typename ELFT::Rela &Rela : CGProfileRela)
8264 SymbolIndices.push_back(Elt: Rela.getSymbol(Obj.isMips64EL()));
8265 }
8266
8267 return true;
8268}
8269
8270template <class ELFT> void LLVMELFDumper<ELFT>::printCGProfile() {
8271 auto IsMatch = [](const Elf_Shdr &Sec) -> bool {
8272 return Sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE;
8273 };
8274
8275 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SecToRelocMapOrErr =
8276 this->Obj.getSectionAndRelocations(IsMatch);
8277 if (!SecToRelocMapOrErr) {
8278 this->reportUniqueWarning("unable to get CG Profile section(s): " +
8279 toString(SecToRelocMapOrErr.takeError()));
8280 return;
8281 }
8282
8283 for (const auto &CGMapEntry : *SecToRelocMapOrErr) {
8284 const Elf_Shdr *CGSection = CGMapEntry.first;
8285 const Elf_Shdr *CGRelSection = CGMapEntry.second;
8286
8287 Expected<ArrayRef<Elf_CGProfile>> CGProfileOrErr =
8288 this->Obj.template getSectionContentsAsArray<Elf_CGProfile>(*CGSection);
8289 if (!CGProfileOrErr) {
8290 this->reportUniqueWarning(
8291 "unable to load the SHT_LLVM_CALL_GRAPH_PROFILE section: " +
8292 toString(CGProfileOrErr.takeError()));
8293 return;
8294 }
8295
8296 SmallVector<uint32_t, 128> SymbolIndices;
8297 bool UseReloc =
8298 getSymbolIndices<ELFT>(CGRelSection, this->Obj, this, SymbolIndices);
8299 if (UseReloc && SymbolIndices.size() != CGProfileOrErr->size() * 2) {
8300 this->reportUniqueWarning(
8301 "number of from/to pairs does not match number of frequencies");
8302 UseReloc = false;
8303 }
8304
8305 ListScope L(W, "CGProfile");
8306 for (uint32_t I = 0, Size = CGProfileOrErr->size(); I != Size; ++I) {
8307 const Elf_CGProfile &CGPE = (*CGProfileOrErr)[I];
8308 DictScope D(W, "CGProfileEntry");
8309 if (UseReloc) {
8310 uint32_t From = SymbolIndices[I * 2];
8311 uint32_t To = SymbolIndices[I * 2 + 1];
8312 W.printNumber("From", this->getStaticSymbolName(From), From);
8313 W.printNumber("To", this->getStaticSymbolName(To), To);
8314 }
8315 W.printNumber("Weight", CGPE.cgp_weight);
8316 }
8317 }
8318}
8319
8320template <class ELFT> void LLVMELFDumper<ELFT>::printCallGraphInfo() {
8321 // Call graph section is of type SHT_LLVM_CALL_GRAPH. Typically named
8322 // ".llvm.callgraph". First fetch the section by its type.
8323 using Elf_Shdr = typename ELFT::Shdr;
8324 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> MapOrErr =
8325 this->Obj.getSectionAndRelocations([](const Elf_Shdr &Sec) {
8326 return Sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH;
8327 });
8328 if (!MapOrErr) {
8329 reportWarning(createError("unable to read SHT_LLVM_CALL_GRAPH section: " +
8330 toString(MapOrErr.takeError())),
8331 this->FileName);
8332 return;
8333 }
8334 if (MapOrErr->empty()) {
8335 reportWarning(createError(Err: "no SHT_LLVM_CALL_GRAPH section found"),
8336 this->FileName);
8337 return;
8338 }
8339
8340 std::unique_ptr<ListScope> CGI;
8341 for (const auto &CGMapEntry : *MapOrErr) {
8342 const Elf_Shdr *CGSection = CGMapEntry.first;
8343 const Elf_Shdr *CGRelSection = CGMapEntry.second;
8344
8345 SmallVector<FunctionCallgraphInfo, 16> FuncCGInfos =
8346 this->processCallGraphSection(CGSection);
8347 if (FuncCGInfos.empty())
8348 continue;
8349
8350 std::vector<Relocation<ELFT>> Relocations;
8351 const Elf_Shdr *RelocSymTab = nullptr;
8352 if (this->Obj.getHeader().e_type == ELF::ET_REL) {
8353 if (CGRelSection) {
8354 Expected<const typename ELFT::Shdr *> SymtabOrErr =
8355 this->Obj.getSection(CGRelSection->sh_link);
8356 if (!SymtabOrErr) {
8357 reportWarning(createError("invalid section linked to " +
8358 this->describe(*CGRelSection) + ": " +
8359 toString(SymtabOrErr.takeError())),
8360 this->FileName);
8361 return;
8362 }
8363 RelocSymTab = *SymtabOrErr;
8364 this->forEachRelocationDo(*CGRelSection, [&](const auto &R, ...) {
8365 Relocations.push_back(R);
8366 });
8367 llvm::stable_sort(Relocations, [](const auto &LHS, const auto &RHS) {
8368 return LHS.Offset < RHS.Offset;
8369 });
8370 }
8371 }
8372
8373 auto GetFunctionNames = [&](uint64_t FuncAddr) {
8374 SmallVector<uint32_t> FuncSymIndexes =
8375 this->getSymbolIndexesForFunctionAddress(FuncAddr, std::nullopt);
8376 SmallVector<std::string> FuncSymNames;
8377 FuncSymNames.reserve(N: FuncSymIndexes.size());
8378 for (uint32_t Index : FuncSymIndexes)
8379 FuncSymNames.push_back(this->getStaticSymbolName(Index));
8380 return FuncSymNames;
8381 };
8382
8383 auto PrintNonRelocatableFuncSymbol = [&](uint64_t FuncEntryPC) {
8384 SmallVector<std::string> FuncSymNames = GetFunctionNames(FuncEntryPC);
8385 if (!FuncSymNames.empty())
8386 W.printList(Label: "Names", List: FuncSymNames);
8387 W.printHex(Label: "Address", Value: FuncEntryPC);
8388 };
8389
8390 auto PrintRelocatableFuncSymbol = [&](uint64_t RelocOffset) {
8391 auto R = llvm::find_if(Relocations, [&](const Relocation<ELFT> &R) {
8392 return R.Offset == RelocOffset;
8393 });
8394 if (R == Relocations.end()) {
8395 this->reportUniqueWarning("missing relocation for symbol at offset " +
8396 Twine(RelocOffset));
8397 return;
8398 }
8399 Expected<RelSymbol<ELFT>> RelSymOrErr =
8400 this->getRelocationTarget(*R, RelocSymTab);
8401 if (!RelSymOrErr) {
8402 this->reportUniqueWarning(RelSymOrErr.takeError());
8403 return;
8404 }
8405 W.printString("Name", RelSymOrErr->Name);
8406 };
8407
8408 auto PrintFunc = [&](uint64_t FuncPC) {
8409 uint64_t FuncEntryPC = FuncPC;
8410 // In ARM thumb mode the LSB of the function pointer is set to 1. Since
8411 // this detail is unncessary in call graph reconstruction, we are clearing
8412 // this bit to facilate tooling.
8413 if (this->Obj.getHeader().e_machine == ELF::EM_ARM)
8414 FuncEntryPC = FuncPC & ~1;
8415 if (this->Obj.getHeader().e_type == ELF::ET_REL)
8416 PrintRelocatableFuncSymbol(FuncEntryPC);
8417 else
8418 PrintNonRelocatableFuncSymbol(FuncEntryPC);
8419 };
8420 if (!CGI)
8421 CGI = std::make_unique<ListScope>(args&: W, args: "CallGraph");
8422 for (const FunctionCallgraphInfo &CGInfo : FuncCGInfos) {
8423 DictScope D(W, "Function");
8424 PrintFunc(CGInfo.FunctionAddress);
8425 W.printNumber(Label: "Version", Value: CGInfo.FormatVersionNumber);
8426 W.printBoolean(Label: "IsIndirectTarget", Value: CGInfo.IsIndirectTarget);
8427 W.printHex(Label: "TypeID", Value: CGInfo.FunctionTypeID);
8428 W.printNumber(Label: "NumDirectCallees", Value: CGInfo.DirectCallees.size());
8429 {
8430 ListScope DCs(W, "DirectCallees");
8431 for (uint64_t CalleePC : CGInfo.DirectCallees) {
8432 DictScope D(W);
8433 PrintFunc(CalleePC);
8434 }
8435 }
8436 W.printNumber(Label: "NumIndirectTargetTypeIDs", Value: CGInfo.IndirectTypeIDs.size());
8437 SmallVector<uint64_t, 4> IndirectTypeIDsList(
8438 CGInfo.IndirectTypeIDs.begin(), CGInfo.IndirectTypeIDs.end());
8439 W.printHexList(Label: "IndirectTypeIDs", List: ArrayRef(IndirectTypeIDsList));
8440 }
8441 }
8442}
8443
8444template <class ELFT>
8445void LLVMELFDumper<ELFT>::printBBAddrMaps(bool PrettyPGOAnalysis) {
8446 bool IsRelocatable = this->Obj.getHeader().e_type == ELF::ET_REL;
8447 using Elf_Shdr = typename ELFT::Shdr;
8448 auto IsMatch = [](const Elf_Shdr &Sec) -> bool {
8449 return Sec.sh_type == ELF::SHT_LLVM_BB_ADDR_MAP;
8450 };
8451 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SecRelocMapOrErr =
8452 this->Obj.getSectionAndRelocations(IsMatch);
8453 if (!SecRelocMapOrErr) {
8454 this->reportUniqueWarning(
8455 "failed to get SHT_LLVM_BB_ADDR_MAP section(s): " +
8456 toString(SecRelocMapOrErr.takeError()));
8457 return;
8458 }
8459 for (auto const &[Sec, RelocSec] : *SecRelocMapOrErr) {
8460 std::optional<const Elf_Shdr *> FunctionSec;
8461 if (IsRelocatable)
8462 FunctionSec =
8463 unwrapOrError(this->FileName, this->Obj.getSection(Sec->sh_link));
8464 ListScope L(W, "BBAddrMap");
8465 if (IsRelocatable && !RelocSec) {
8466 this->reportUniqueWarning("unable to get relocation section for " +
8467 this->describe(*Sec));
8468 continue;
8469 }
8470 std::vector<PGOAnalysisMap> PGOAnalyses;
8471 Expected<std::vector<BBAddrMap>> BBAddrMapOrErr =
8472 this->Obj.decodeBBAddrMap(*Sec, RelocSec, &PGOAnalyses);
8473 if (!BBAddrMapOrErr) {
8474 this->reportUniqueWarning("unable to dump BB addr map section: " +
8475 toString(E: BBAddrMapOrErr.takeError()));
8476 continue;
8477 }
8478 for (const auto &[AM, PAM] : zip_equal(t&: *BBAddrMapOrErr, u&: PGOAnalyses)) {
8479 DictScope D(W, "Function");
8480 W.printHex(Label: "At", Value: AM.getFunctionAddress());
8481 SmallVector<uint32_t> FuncSymIndex =
8482 this->getSymbolIndexesForFunctionAddress(AM.getFunctionAddress(),
8483 FunctionSec);
8484 std::string FuncName = "<?>";
8485 if (FuncSymIndex.empty())
8486 this->reportUniqueWarning(
8487 "could not identify function symbol for address (0x" +
8488 Twine::utohexstr(Val: AM.getFunctionAddress()) + ") in " +
8489 this->describe(*Sec));
8490 else
8491 FuncName = this->getStaticSymbolName(FuncSymIndex.front());
8492 W.printString(Label: "Name", Value: FuncName);
8493 {
8494 ListScope BBRL(W, "BB Ranges");
8495 for (const BBAddrMap::BBRangeEntry &BBR : AM.BBRanges) {
8496 DictScope BBRD(W);
8497 W.printHex(Label: "Base Address", Value: BBR.BaseAddress);
8498 ListScope BBEL(W, "BB Entries");
8499 for (const BBAddrMap::BBEntry &BBE : BBR.BBEntries) {
8500 DictScope BBED(W);
8501 W.printNumber(Label: "ID", Value: BBE.ID);
8502 W.printHex(Label: "Offset", Value: BBE.Offset);
8503 if (!BBE.CallsiteEndOffsets.empty())
8504 W.printList(Label: "Callsite End Offsets", List: BBE.CallsiteEndOffsets);
8505 if (PAM.FeatEnable.BBHash)
8506 W.printHex(Label: "Hash", Value: BBE.Hash);
8507 W.printHex(Label: "Size", Value: BBE.Size);
8508 W.printBoolean(Label: "HasReturn", Value: BBE.hasReturn());
8509 W.printBoolean(Label: "HasTailCall", Value: BBE.hasTailCall());
8510 W.printBoolean(Label: "IsEHPad", Value: BBE.isEHPad());
8511 W.printBoolean(Label: "CanFallThrough", Value: BBE.canFallThrough());
8512 W.printBoolean(Label: "HasIndirectBranch", Value: BBE.hasIndirectBranch());
8513 }
8514 }
8515 }
8516
8517 if (PAM.FeatEnable.hasPGOAnalysis()) {
8518 DictScope PD(W, "PGO analyses");
8519
8520 if (PAM.FeatEnable.FuncEntryCount)
8521 W.printNumber(Label: "FuncEntryCount", Value: PAM.FuncEntryCount);
8522
8523 if (PAM.FeatEnable.hasPGOAnalysisBBData()) {
8524 ListScope L(W, "PGO BB entries");
8525 for (const PGOAnalysisMap::PGOBBEntry &PBBE : PAM.BBEntries) {
8526 DictScope L(W);
8527
8528 if (PAM.FeatEnable.BBFreq) {
8529 if (PrettyPGOAnalysis) {
8530 std::string BlockFreqStr;
8531 raw_string_ostream SS(BlockFreqStr);
8532 printRelativeBlockFreq(OS&: SS, EntryFreq: PAM.BBEntries.front().BlockFreq,
8533 Freq: PBBE.BlockFreq);
8534 W.printString(Label: "Frequency", Value: BlockFreqStr);
8535 } else {
8536 W.printNumber(Label: "Frequency", Value: PBBE.BlockFreq.getFrequency());
8537 }
8538 if (PAM.FeatEnable.PostLinkCfg)
8539 W.printNumber(Label: "PostLink Frequency", Value: PBBE.PostLinkBlockFreq);
8540 }
8541
8542 if (PAM.FeatEnable.BrProb) {
8543 ListScope L(W, "Successors");
8544 for (const auto &Succ : PBBE.Successors) {
8545 DictScope L(W);
8546 W.printNumber(Label: "ID", Value: Succ.ID);
8547 if (PrettyPGOAnalysis) {
8548 W.printObject(Label: "Probability", Value: Succ.Prob);
8549 } else {
8550 W.printHex(Label: "Probability", Value: Succ.Prob.getNumerator());
8551 }
8552 if (PAM.FeatEnable.PostLinkCfg)
8553 W.printNumber(Label: "PostLink Probability", Value: Succ.PostLinkFreq);
8554 }
8555 }
8556 }
8557 }
8558 }
8559 }
8560 }
8561}
8562
8563template <class ELFT> void LLVMELFDumper<ELFT>::printAddrsig() {
8564 ListScope L(W, "Addrsig");
8565 if (!this->DotAddrsigSec)
8566 return;
8567
8568 Expected<std::vector<uint64_t>> SymsOrErr =
8569 decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
8570 if (!SymsOrErr) {
8571 this->reportUniqueWarning(SymsOrErr.takeError());
8572 return;
8573 }
8574
8575 for (uint64_t Sym : *SymsOrErr)
8576 W.printNumber("Sym", this->getStaticSymbolName(Sym), Sym);
8577}
8578
8579template <typename ELFT>
8580static bool printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
8581 ScopedPrinter &W,
8582 typename ELFT::Half EMachine) {
8583 // Return true if we were able to pretty-print the note, false otherwise.
8584 switch (NoteType) {
8585 default:
8586 return false;
8587 case ELF::NT_GNU_ABI_TAG: {
8588 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
8589 if (!AbiTag.IsValid) {
8590 W.printString(Label: "ABI", Value: "<corrupt GNU_ABI_TAG>");
8591 return false;
8592 } else {
8593 W.printString(Label: "OS", Value: AbiTag.OSName);
8594 W.printString(Label: "ABI", Value: AbiTag.ABI);
8595 }
8596 break;
8597 }
8598 case ELF::NT_GNU_BUILD_ID: {
8599 W.printString(Label: "Build ID", Value: getGNUBuildId(Desc));
8600 break;
8601 }
8602 case ELF::NT_GNU_GOLD_VERSION:
8603 W.printString(Label: "Version", Value: getDescAsStringRef(Desc));
8604 break;
8605 case ELF::NT_GNU_PROPERTY_TYPE_0:
8606 ListScope D(W, "Property");
8607 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc, EMachine))
8608 W.printString(Value: Property);
8609 break;
8610 }
8611 return true;
8612}
8613
8614static bool printAndroidNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
8615 ScopedPrinter &W) {
8616 // Return true if we were able to pretty-print the note, false otherwise.
8617 AndroidNoteProperties Props = getAndroidNoteProperties(NoteType, Desc);
8618 if (Props.empty())
8619 return false;
8620 for (const auto &KV : Props)
8621 W.printString(Label: KV.first, Value: KV.second);
8622 return true;
8623}
8624
8625template <class ELFT>
8626void LLVMELFDumper<ELFT>::printMemtag(
8627 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
8628 const ArrayRef<uint8_t> AndroidNoteDesc,
8629 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) {
8630 {
8631 ListScope L(W, "Memtag Dynamic Entries:");
8632 if (DynamicEntries.empty())
8633 W.printString(Value: "< none found >");
8634 for (const auto &DynamicEntryKV : DynamicEntries)
8635 W.printString(Label: DynamicEntryKV.first, Value: DynamicEntryKV.second);
8636 }
8637
8638 if (!AndroidNoteDesc.empty()) {
8639 ListScope L(W, "Memtag Android Note:");
8640 printAndroidNoteLLVMStyle(NoteType: ELF::NT_ANDROID_TYPE_MEMTAG, Desc: AndroidNoteDesc, W);
8641 }
8642
8643 if (Descriptors.empty())
8644 return;
8645
8646 {
8647 ListScope L(W, "Memtag Global Descriptors:");
8648 for (const auto &[Addr, BytesToTag] : Descriptors) {
8649 W.printHex(Label: "0x" + utohexstr(X: Addr, /*LowerCase=*/true), Value: BytesToTag);
8650 }
8651 }
8652}
8653
8654template <typename ELFT>
8655static bool printLLVMOMPOFFLOADNoteLLVMStyle(uint32_t NoteType,
8656 ArrayRef<uint8_t> Desc,
8657 ScopedPrinter &W) {
8658 switch (NoteType) {
8659 default:
8660 return false;
8661 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
8662 W.printString(Label: "Version", Value: getDescAsStringRef(Desc));
8663 break;
8664 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
8665 W.printString(Label: "Producer", Value: getDescAsStringRef(Desc));
8666 break;
8667 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
8668 W.printString(Label: "Producer version", Value: getDescAsStringRef(Desc));
8669 break;
8670 }
8671 return true;
8672}
8673
8674static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) {
8675 W.printNumber(Label: "Page Size", Value: Note.PageSize);
8676 ListScope D(W, "Mappings");
8677 for (const CoreFileMapping &Mapping : Note.Mappings) {
8678 DictScope D(W);
8679 W.printHex(Label: "Start", Value: Mapping.Start);
8680 W.printHex(Label: "End", Value: Mapping.End);
8681 W.printHex(Label: "Offset", Value: Mapping.Offset);
8682 W.printString(Label: "Filename", Value: Mapping.Filename);
8683 }
8684}
8685
8686template <class ELFT> void LLVMELFDumper<ELFT>::printNotes() {
8687 ListScope L(W, "NoteSections");
8688
8689 std::unique_ptr<DictScope> NoteSectionScope;
8690 std::unique_ptr<ListScope> NotesScope;
8691 size_t Align = 0;
8692 auto StartNotes = [&](std::optional<StringRef> SecName,
8693 const typename ELFT::Off Offset,
8694 const typename ELFT::Addr Size, size_t Al) {
8695 Align = std::max<size_t>(a: Al, b: 4);
8696 NoteSectionScope = std::make_unique<DictScope>(args&: W, args: "NoteSection");
8697 W.printString(Label: "Name", Value: SecName ? *SecName : "<?>");
8698 W.printHex("Offset", Offset);
8699 W.printHex("Size", Size);
8700 NotesScope = std::make_unique<ListScope>(args&: W, args: "Notes");
8701 };
8702
8703 auto EndNotes = [&] {
8704 NotesScope.reset();
8705 NoteSectionScope.reset();
8706 };
8707
8708 auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
8709 DictScope D2(W);
8710 StringRef Name = Note.getName();
8711 ArrayRef<uint8_t> Descriptor = Note.getDesc(Align);
8712 Elf_Word Type = Note.getType();
8713
8714 // Print the note owner/type.
8715 W.printString(Label: "Owner", Value: Name);
8716 W.printHex(Label: "Data size", Value: Descriptor.size());
8717
8718 StringRef NoteType =
8719 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
8720 if (!NoteType.empty())
8721 W.printString(Label: "Type", Value: NoteType);
8722 else
8723 W.printString("Type",
8724 "Unknown (" + to_string(format_hex(Type, 10)) + ")");
8725
8726 const typename ELFT::Half EMachine = this->Obj.getHeader().e_machine;
8727 // Print the description, or fallback to printing raw bytes for unknown
8728 // owners/if we fail to pretty-print the contents.
8729 if (Name == "GNU") {
8730 if (printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W, EMachine))
8731 return Error::success();
8732 } else if (Name == "FreeBSD") {
8733 if (std::optional<FreeBSDNote> N =
8734 getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
8735 W.printString(Label: N->Type, Value: N->Value);
8736 return Error::success();
8737 }
8738 } else if (Name == "AMD") {
8739 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
8740 if (!N.Type.empty()) {
8741 W.printString(Label: N.Type, Value: N.Value);
8742 return Error::success();
8743 }
8744 } else if (Name == "AMDGPU") {
8745 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
8746 if (!N.Type.empty()) {
8747 W.printString(Label: N.Type, Value: N.Value);
8748 return Error::success();
8749 }
8750 } else if (Name == "LLVMOMPOFFLOAD") {
8751 if (printLLVMOMPOFFLOADNoteLLVMStyle<ELFT>(Type, Descriptor, W))
8752 return Error::success();
8753 } else if (Name == "CORE") {
8754 if (Type == ELF::NT_FILE) {
8755 DataExtractor DescExtractor(Descriptor, ELFT::Endianness ==
8756 llvm::endianness::little);
8757 if (Expected<CoreNote> N =
8758 readCoreNote(Desc: DescExtractor, AddressSize: sizeof(Elf_Addr))) {
8759 printCoreNoteLLVMStyle(Note: *N, W);
8760 return Error::success();
8761 } else {
8762 return N.takeError();
8763 }
8764 }
8765 } else if (Name == "Android") {
8766 if (printAndroidNoteLLVMStyle(Type, Descriptor, W))
8767 return Error::success();
8768 }
8769 if (!Descriptor.empty()) {
8770 W.printBinaryBlock(Label: "Description data", Value: Descriptor);
8771 }
8772 return Error::success();
8773 };
8774
8775 processNotesHelper(*this, /*StartNotesFn=*/StartNotes,
8776 /*ProcessNoteFn=*/ProcessNote, /*FinishNotesFn=*/EndNotes);
8777}
8778
8779template <class ELFT> void LLVMELFDumper<ELFT>::printELFLinkerOptions() {
8780 ListScope L(W, "LinkerOptions");
8781
8782 unsigned I = -1;
8783 for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) {
8784 ++I;
8785 if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS)
8786 continue;
8787
8788 Expected<ArrayRef<uint8_t>> ContentsOrErr =
8789 this->Obj.getSectionContents(Shdr);
8790 if (!ContentsOrErr) {
8791 this->reportUniqueWarning("unable to read the content of the "
8792 "SHT_LLVM_LINKER_OPTIONS section: " +
8793 toString(E: ContentsOrErr.takeError()));
8794 continue;
8795 }
8796 if (ContentsOrErr->empty())
8797 continue;
8798
8799 if (ContentsOrErr->back() != 0) {
8800 this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " +
8801 Twine(I) +
8802 " is broken: the "
8803 "content is not null-terminated");
8804 continue;
8805 }
8806
8807 SmallVector<StringRef, 16> Strings;
8808 toStringRef(Input: ContentsOrErr->drop_back()).split(A&: Strings, Separator: '\0');
8809 if (Strings.size() % 2 != 0) {
8810 this->reportUniqueWarning(
8811 "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) +
8812 " is broken: an incomplete "
8813 "key-value pair was found. The last possible key was: \"" +
8814 Strings.back() + "\"");
8815 continue;
8816 }
8817
8818 for (size_t I = 0; I < Strings.size(); I += 2)
8819 W.printString(Label: Strings[I], Value: Strings[I + 1]);
8820 }
8821}
8822
8823template <class ELFT> void LLVMELFDumper<ELFT>::printDependentLibs() {
8824 ListScope L(W, "DependentLibs");
8825 this->printDependentLibsHelper(
8826 [](const Elf_Shdr &) {},
8827 [this](StringRef Lib, uint64_t) { W.printString(Value: Lib); });
8828}
8829
8830template <class ELFT> void LLVMELFDumper<ELFT>::printStackSizes() {
8831 ListScope L(W, "StackSizes");
8832 if (this->Obj.getHeader().e_type == ELF::ET_REL)
8833 this->printRelocatableStackSizes([]() {});
8834 else
8835 this->printNonRelocatableStackSizes([]() {});
8836}
8837
8838template <class ELFT>
8839void LLVMELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
8840 ArrayRef<std::string> FuncNames) {
8841 DictScope D(W, "Entry");
8842 W.printList(Label: "Functions", List: FuncNames);
8843 W.printHex(Label: "Size", Value: Size);
8844}
8845
8846template <class ELFT>
8847void LLVMELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
8848 auto PrintEntry = [&](const Elf_Addr *E) {
8849 W.printHex("Address", Parser.getGotAddress(E));
8850 W.printNumber("Access", Parser.getGotOffset(E));
8851 W.printHex("Initial", *E);
8852 };
8853
8854 DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT");
8855
8856 W.printHex("Canonical gp value", Parser.getGp());
8857 {
8858 ListScope RS(W, "Reserved entries");
8859 {
8860 DictScope D(W, "Entry");
8861 PrintEntry(Parser.getGotLazyResolver());
8862 W.printString(Label: "Purpose", Value: StringRef("Lazy resolver"));
8863 }
8864
8865 if (Parser.getGotModulePointer()) {
8866 DictScope D(W, "Entry");
8867 PrintEntry(Parser.getGotModulePointer());
8868 W.printString(Label: "Purpose", Value: StringRef("Module pointer (GNU extension)"));
8869 }
8870 }
8871 {
8872 ListScope LS(W, "Local entries");
8873 for (auto &E : Parser.getLocalEntries()) {
8874 DictScope D(W, "Entry");
8875 PrintEntry(&E);
8876 }
8877 }
8878
8879 if (Parser.IsStatic)
8880 return;
8881
8882 {
8883 ListScope GS(W, "Global entries");
8884 for (auto &E : Parser.getGlobalEntries()) {
8885 DictScope D(W, "Entry");
8886
8887 PrintEntry(&E);
8888
8889 const Elf_Sym &Sym = *Parser.getGotSym(&E);
8890 W.printHex("Value", Sym.st_value);
8891 W.printEnum("Type", Sym.getType(), getElfSymbolTypes());
8892
8893 const unsigned SymIndex = &Sym - this->dynamic_symbols().begin();
8894 DataRegion<Elf_Word> ShndxTable(
8895 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
8896 printSymbolSection(Symbol: Sym, SymIndex, ShndxTable);
8897
8898 std::string SymName = this->getFullSymbolName(
8899 Sym, SymIndex, ShndxTable, this->DynamicStringTable, true);
8900 W.printNumber("Name", SymName, Sym.st_name);
8901 }
8902 }
8903
8904 W.printNumber(Label: "Number of TLS and multi-GOT entries",
8905 Value: uint64_t(Parser.getOtherEntries().size()));
8906}
8907
8908template <class ELFT>
8909void LLVMELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
8910 auto PrintEntry = [&](const Elf_Addr *E) {
8911 W.printHex("Address", Parser.getPltAddress(E));
8912 W.printHex("Initial", *E);
8913 };
8914
8915 DictScope GS(W, "PLT GOT");
8916
8917 {
8918 ListScope RS(W, "Reserved entries");
8919 {
8920 DictScope D(W, "Entry");
8921 PrintEntry(Parser.getPltLazyResolver());
8922 W.printString(Label: "Purpose", Value: StringRef("PLT lazy resolver"));
8923 }
8924
8925 if (auto E = Parser.getPltModulePointer()) {
8926 DictScope D(W, "Entry");
8927 PrintEntry(E);
8928 W.printString(Label: "Purpose", Value: StringRef("Module pointer"));
8929 }
8930 }
8931 {
8932 ListScope LS(W, "Entries");
8933 DataRegion<Elf_Word> ShndxTable(
8934 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
8935 for (auto &E : Parser.getPltEntries()) {
8936 DictScope D(W, "Entry");
8937 PrintEntry(&E);
8938
8939 const Elf_Sym &Sym = *Parser.getPltSym(&E);
8940 W.printHex("Value", Sym.st_value);
8941 W.printEnum("Type", Sym.getType(), getElfSymbolTypes());
8942 printSymbolSection(Symbol: Sym, SymIndex: &Sym - this->dynamic_symbols().begin(),
8943 ShndxTable);
8944
8945 const Elf_Sym *FirstSym = cantFail(
8946 this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
8947 std::string SymName = this->getFullSymbolName(
8948 Sym, &Sym - FirstSym, ShndxTable, Parser.getPltStrTable(), true);
8949 W.printNumber("Name", SymName, Sym.st_name);
8950 }
8951 }
8952}
8953
8954template <class ELFT> void LLVMELFDumper<ELFT>::printMipsABIFlags() {
8955 const Elf_Mips_ABIFlags<ELFT> *Flags;
8956 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
8957 getMipsAbiFlagsSection(*this)) {
8958 Flags = *SecOrErr;
8959 if (!Flags) {
8960 W.startLine() << "There is no .MIPS.abiflags section in the file.\n";
8961 return;
8962 }
8963 } else {
8964 this->reportUniqueWarning(SecOrErr.takeError());
8965 return;
8966 }
8967
8968 raw_ostream &OS = W.getOStream();
8969 DictScope GS(W, "MIPS ABI Flags");
8970
8971 W.printNumber("Version", Flags->version);
8972 W.startLine() << "ISA: ";
8973 if (Flags->isa_rev <= 1)
8974 OS << format("MIPS%u", Flags->isa_level);
8975 else
8976 OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev);
8977 OS << "\n";
8978 W.printEnum("ISA Extension", Flags->isa_ext, EnumStrings(ElfMipsISAExtType));
8979 W.printFlags("ASEs", Flags->ases, EnumStrings(ElfMipsASEFlags));
8980 W.printEnum("FP ABI", Flags->fp_abi, EnumStrings(ElfMipsFpABIType));
8981 W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size));
8982 W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size));
8983 W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size));
8984 W.printFlags("Flags 1", Flags->flags1, EnumStrings(ElfMipsFlags1));
8985 W.printHex("Flags 2", Flags->flags2);
8986}
8987
8988template <class ELFT>
8989void JSONELFDumper<ELFT>::printFileSummary(StringRef FileStr, ObjectFile &Obj,
8990 ArrayRef<std::string> InputFilenames,
8991 const Archive *A) {
8992 FileScope = std::make_unique<DictScope>(this->W);
8993 DictScope D(this->W, "FileSummary");
8994 this->W.printString("File", FileStr);
8995 this->W.printString("Format", Obj.getFileFormatName());
8996 this->W.printString("Arch", Triple::getArchTypeName(Kind: Obj.getArch()));
8997 this->W.printString(
8998 "AddressSize",
8999 std::string(formatv(Fmt: "{0}bit", Vals: 8 * Obj.getBytesInAddress())));
9000 this->printLoadName();
9001}
9002
9003template <class ELFT>
9004void JSONELFDumper<ELFT>::printZeroSymbolOtherField(
9005 const Elf_Sym &Symbol) const {
9006 // We want the JSON format to be uniform, since it is machine readable, so
9007 // always print the `Other` field the same way.
9008 this->printSymbolOtherField(Symbol);
9009}
9010
9011template <class ELFT>
9012void JSONELFDumper<ELFT>::printDefaultRelRelaReloc(const Relocation<ELFT> &R,
9013 StringRef SymbolName,
9014 StringRef RelocName) {
9015 this->printExpandedRelRelaReloc(R, SymbolName, RelocName);
9016}
9017
9018template <class ELFT>
9019void JSONELFDumper<ELFT>::printRelocationSectionInfo(const Elf_Shdr &Sec,
9020 StringRef Name,
9021 const unsigned SecNdx) {
9022 DictScope Group(this->W);
9023 this->W.printNumber("SectionIndex", SecNdx);
9024 ListScope D(this->W, "Relocs");
9025 this->printRelocationsHelper(Sec);
9026}
9027
9028template <class ELFT>
9029std::string JSONELFDumper<ELFT>::getGroupSectionHeaderName() const {
9030 return "GroupSections";
9031}
9032
9033template <class ELFT>
9034void JSONELFDumper<ELFT>::printSectionGroupMembers(StringRef Name,
9035 uint64_t Idx) const {
9036 DictScope Grp(this->W);
9037 this->W.printString("Name", Name);
9038 this->W.printNumber("Index", Idx);
9039}
9040
9041template <class ELFT> void JSONELFDumper<ELFT>::printEmptyGroupMessage() const {
9042 // JSON output does not need to print anything for empty groups
9043}
9044