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