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 unsigned(ELF::EF_RISCV_FLOAT_ABI));
3762 else if (e.e_machine == EM_SPARC32PLUS || e.e_machine == EM_SPARCV9)
3763 ElfFlags = printFlags(e.e_flags, EnumStrings(ElfHeaderSPARCFlags),
3764 unsigned(ELF::EF_SPARCV9_MM));
3765 else if (e.e_machine == EM_AVR)
3766 ElfFlags = printFlags(e.e_flags, EnumStrings(ElfHeaderAVRFlags),
3767 unsigned(ELF::EF_AVR_ARCH_MASK));
3768 else if (e.e_machine == EM_LOONGARCH)
3769 ElfFlags = printFlags(e.e_flags, EnumStrings(ElfHeaderLoongArchFlags),
3770 unsigned(ELF::EF_LOONGARCH_ABI_MODIFIER_MASK),
3771 unsigned(ELF::EF_LOONGARCH_OBJABI_MASK));
3772 else if (e.e_machine == EM_XTENSA)
3773 ElfFlags = printFlags(e.e_flags, EnumStrings(ElfHeaderXtensaFlags),
3774 unsigned(ELF::EF_XTENSA_MACH));
3775 else if (e.e_machine == EM_CUDA) {
3776 unsigned Mask = e.e_ident[ELF::EI_ABIVERSION] == ELF::ELFABIVERSION_CUDA_V1
3777 ? ELF::EF_CUDA_SM
3778 : ELF::EF_CUDA_SM_MASK;
3779 ElfFlags = printFlags(e.e_flags, EnumStrings(ElfHeaderNVPTXFlags), Mask);
3780 if (e.e_ident[ELF::EI_ABIVERSION] == ELF::ELFABIVERSION_CUDA_V1 &&
3781 (e.e_flags & ELF::EF_CUDA_ACCELERATORS_V1))
3782 ElfFlags += "a";
3783 else if (e.e_ident[ELF::EI_ABIVERSION] == ELF::ELFABIVERSION_CUDA_V2 &&
3784 (e.e_flags & ELF::EF_CUDA_ACCELERATORS))
3785 ElfFlags += "a";
3786 } else if (e.e_machine == EM_AMDGPU) {
3787 switch (e.e_ident[ELF::EI_ABIVERSION]) {
3788 default:
3789 break;
3790 case 0:
3791 // ELFOSABI_AMDGPU_PAL, ELFOSABI_AMDGPU_MESA3D support *_V3 flags.
3792 [[fallthrough]];
3793 case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
3794 ElfFlags =
3795 printFlags(e.e_flags, EnumStrings(ElfHeaderAMDGPUFlagsABIVersion3),
3796 unsigned(ELF::EF_AMDGPU_MACH));
3797 break;
3798 case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
3799 case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
3800 ElfFlags =
3801 printFlags(e.e_flags, EnumStrings(ElfHeaderAMDGPUFlagsABIVersion4),
3802 unsigned(ELF::EF_AMDGPU_MACH),
3803 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
3804 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
3805 break;
3806 case ELF::ELFABIVERSION_AMDGPU_HSA_V6: {
3807 ElfFlags =
3808 printFlags(e.e_flags, EnumStrings(ElfHeaderAMDGPUFlagsABIVersion4),
3809 unsigned(ELF::EF_AMDGPU_MACH),
3810 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
3811 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
3812 if (auto GenericV = e.e_flags & ELF::EF_AMDGPU_GENERIC_VERSION) {
3813 ElfFlags +=
3814 ", generic_v" +
3815 to_string(GenericV >> ELF::EF_AMDGPU_GENERIC_VERSION_OFFSET);
3816 }
3817 } break;
3818 }
3819 }
3820 Str = "0x" + utohexstr(e.e_flags, /*LowerCase=*/true);
3821 if (!ElfFlags.empty())
3822 Str = Str + ", " + ElfFlags;
3823 printFields(OS, Str1: "Flags:", Str2: Str);
3824 Str = to_string(e.e_ehsize) + " (bytes)";
3825 printFields(OS, Str1: "Size of this header:", Str2: Str);
3826 Str = to_string(e.e_phentsize) + " (bytes)";
3827 printFields(OS, Str1: "Size of program headers:", Str2: Str);
3828 Str = this->getProgramHeadersNumString();
3829 printFields(OS, Str1: "Number of program headers:", Str2: Str);
3830 Str = to_string(e.e_shentsize) + " (bytes)";
3831 printFields(OS, Str1: "Size of section headers:", Str2: Str);
3832 Str = getSectionHeadersNumString(this->Obj, this->FileName);
3833 printFields(OS, Str1: "Number of section headers:", Str2: Str);
3834 Str = getSectionHeaderTableIndexString(this->Obj, this->FileName);
3835 printFields(OS, Str1: "Section header string table index:", Str2: Str);
3836}
3837
3838template <class ELFT> std::vector<GroupSection> ELFDumper<ELFT>::getGroups() {
3839 auto GetSignature = [&](const Elf_Sym &Sym, unsigned SymNdx,
3840 const Elf_Shdr &Symtab) -> StringRef {
3841 Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(Symtab);
3842 if (!StrTableOrErr) {
3843 reportUniqueWarning("unable to get the string table for " +
3844 describe(Sec: Symtab) + ": " +
3845 toString(E: StrTableOrErr.takeError()));
3846 return "<?>";
3847 }
3848
3849 StringRef Strings = *StrTableOrErr;
3850 if (Sym.st_name >= Strings.size()) {
3851 reportUniqueWarning("unable to get the name of the symbol with index " +
3852 Twine(SymNdx) + ": st_name (0x" +
3853 Twine::utohexstr(Val: Sym.st_name) +
3854 ") is past the end of the string table of size 0x" +
3855 Twine::utohexstr(Val: Strings.size()));
3856 return "<?>";
3857 }
3858
3859 return StrTableOrErr->data() + Sym.st_name;
3860 };
3861
3862 std::vector<GroupSection> Ret;
3863 uint64_t I = 0;
3864 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
3865 ++I;
3866 if (Sec.sh_type != ELF::SHT_GROUP)
3867 continue;
3868
3869 StringRef Signature = "<?>";
3870 if (Expected<const Elf_Shdr *> SymtabOrErr = Obj.getSection(Sec.sh_link)) {
3871 if (Expected<const Elf_Sym *> SymOrErr =
3872 Obj.template getEntry<Elf_Sym>(**SymtabOrErr, Sec.sh_info))
3873 Signature = GetSignature(**SymOrErr, Sec.sh_info, **SymtabOrErr);
3874 else
3875 reportUniqueWarning("unable to get the signature symbol for " +
3876 describe(Sec) + ": " +
3877 toString(SymOrErr.takeError()));
3878 } else {
3879 reportUniqueWarning("unable to get the symbol table for " +
3880 describe(Sec) + ": " +
3881 toString(SymtabOrErr.takeError()));
3882 }
3883
3884 ArrayRef<Elf_Word> Data;
3885 if (Expected<ArrayRef<Elf_Word>> ContentsOrErr =
3886 Obj.template getSectionContentsAsArray<Elf_Word>(Sec)) {
3887 if (ContentsOrErr->empty())
3888 reportUniqueWarning("unable to read the section group flag from the " +
3889 describe(Sec) + ": the section is empty");
3890 else
3891 Data = *ContentsOrErr;
3892 } else {
3893 reportUniqueWarning("unable to get the content of the " + describe(Sec) +
3894 ": " + toString(ContentsOrErr.takeError()));
3895 }
3896
3897 Ret.push_back({getPrintableSectionName(Sec),
3898 maybeDemangle(Name: Signature),
3899 Sec.sh_name,
3900 I - 1,
3901 Sec.sh_link,
3902 Sec.sh_info,
3903 Data.empty() ? Elf_Word(0) : Data[0],
3904 {}});
3905
3906 if (Data.empty())
3907 continue;
3908
3909 std::vector<GroupMember> &GM = Ret.back().Members;
3910 for (uint32_t Ndx : Data.slice(1)) {
3911 if (Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(Ndx)) {
3912 GM.push_back({getPrintableSectionName(Sec: **SecOrErr), Ndx});
3913 } else {
3914 reportUniqueWarning("unable to get the section with index " +
3915 Twine(Ndx) + " when dumping the " + describe(Sec) +
3916 ": " + toString(SecOrErr.takeError()));
3917 GM.push_back(x: {.Name: "<?>", .Index: Ndx});
3918 }
3919 }
3920 }
3921 return Ret;
3922}
3923
3924static DenseMap<uint64_t, const GroupSection *>
3925mapSectionsToGroups(ArrayRef<GroupSection> Groups) {
3926 DenseMap<uint64_t, const GroupSection *> Ret;
3927 for (const GroupSection &G : Groups)
3928 for (const GroupMember &GM : G.Members)
3929 Ret.insert(KV: {GM.Index, &G});
3930 return Ret;
3931}
3932
3933template <class ELFT> void GNUELFDumper<ELFT>::printGroupSections() {
3934 std::vector<GroupSection> V = this->getGroups();
3935 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(Groups: V);
3936 for (const GroupSection &G : V) {
3937 OS << "\n"
3938 << getGroupType(Flag: G.Type) << " group section ["
3939 << format_decimal(N: G.Index, Width: 5) << "] `" << G.Name << "' [" << G.Signature
3940 << "] contains " << G.Members.size() << " sections:\n"
3941 << " [Index] Name\n";
3942 for (const GroupMember &GM : G.Members) {
3943 const GroupSection *MainGroup = Map[GM.Index];
3944 if (MainGroup != &G)
3945 this->reportUniqueWarning(
3946 "section with index " + Twine(GM.Index) +
3947 ", included in the group section with index " +
3948 Twine(MainGroup->Index) +
3949 ", was also found in the group section with index " +
3950 Twine(G.Index));
3951 OS << " [" << format_decimal(N: GM.Index, Width: 5) << "] " << GM.Name << "\n";
3952 }
3953 }
3954
3955 if (V.empty())
3956 OS << "There are no section groups in this file.\n";
3957}
3958
3959template <class ELFT>
3960void GNUELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
3961 const RelSymbol<ELFT> &RelSym) {
3962 // First two fields are bit width dependent. The rest of them are fixed width.
3963 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
3964 Field Fields[5] = {0, 10 + Bias, 19 + 2 * Bias, 42 + 2 * Bias, 53 + 2 * Bias};
3965 unsigned Width = ELFT::Is64Bits ? 16 : 8;
3966
3967 Fields[0].Str = to_string(format_hex_no_prefix(R.Offset, Width));
3968 Fields[1].Str = to_string(format_hex_no_prefix(R.Info, Width));
3969
3970 SmallString<32> RelocName;
3971 Fields[2].Str = this->getRelocTypeName(R.Type, RelocName);
3972
3973 if (RelSym.Sym)
3974 Fields[3].Str =
3975 to_string(format_hex_no_prefix(RelSym.Sym->getValue(), Width));
3976 if (RelSym.Sym && RelSym.Name.empty())
3977 Fields[4].Str = "<null>";
3978 else
3979 Fields[4].Str = std::string(RelSym.Name);
3980
3981 for (const Field &F : Fields)
3982 printField(F);
3983
3984 std::string Addend;
3985 if (std::optional<int64_t> A = R.Addend) {
3986 int64_t RelAddend = *A;
3987 if (!Fields[4].Str.empty()) {
3988 if (RelAddend < 0) {
3989 Addend = " - ";
3990 RelAddend = -static_cast<uint64_t>(RelAddend);
3991 } else {
3992 Addend = " + ";
3993 }
3994 }
3995 Addend += utohexstr(X: RelAddend, /*LowerCase=*/true);
3996 }
3997 OS << Addend << "\n";
3998}
3999
4000template <class ELFT>
4001static void printRelocHeaderFields(formatted_raw_ostream &OS, unsigned SType,
4002 const typename ELFT::Ehdr &EHeader,
4003 uint64_t CrelHdr = 0) {
4004 bool IsRela = SType == ELF::SHT_RELA || SType == ELF::SHT_ANDROID_RELA;
4005 if (ELFT::Is64Bits)
4006 OS << " Offset Info Type Symbol's "
4007 "Value Symbol's Name";
4008 else
4009 OS << " Offset Info Type Sym. Value Symbol's Name";
4010 if (IsRela || (SType == ELF::SHT_CREL && (CrelHdr & CREL_HDR_ADDEND)))
4011 OS << " + Addend";
4012 OS << "\n";
4013}
4014
4015template <class ELFT>
4016void GNUELFDumper<ELFT>::printDynamicRelocHeader(unsigned Type, StringRef Name,
4017 const DynRegionInfo &Reg) {
4018 uint64_t Offset = Reg.Addr - this->Obj.base();
4019 OS << "\n'" << Name.str().c_str() << "' relocation section at offset 0x"
4020 << utohexstr(X: Offset, /*LowerCase=*/true);
4021 if (Type != ELF::SHT_CREL)
4022 OS << " contains " << Reg.Size << " bytes";
4023 OS << ":\n";
4024 printRelocHeaderFields<ELFT>(OS, Type, this->Obj.getHeader());
4025}
4026
4027template <class ELFT>
4028static bool isRelocationSec(const typename ELFT::Shdr &Sec,
4029 const typename ELFT::Ehdr &EHeader) {
4030 return Sec.sh_type == ELF::SHT_REL || Sec.sh_type == ELF::SHT_RELA ||
4031 Sec.sh_type == ELF::SHT_RELR || Sec.sh_type == ELF::SHT_CREL ||
4032 Sec.sh_type == ELF::SHT_ANDROID_REL ||
4033 Sec.sh_type == ELF::SHT_ANDROID_RELA ||
4034 Sec.sh_type == ELF::SHT_ANDROID_RELR ||
4035 (EHeader.e_machine == EM_AARCH64 &&
4036 Sec.sh_type == ELF::SHT_AARCH64_AUTH_RELR);
4037}
4038
4039template <class ELFT> void GNUELFDumper<ELFT>::printRelocations() {
4040 auto PrintAsRelr = [&](const Elf_Shdr &Sec) {
4041 return Sec.sh_type == ELF::SHT_RELR ||
4042 Sec.sh_type == ELF::SHT_ANDROID_RELR ||
4043 (this->Obj.getHeader().e_machine == EM_AARCH64 &&
4044 Sec.sh_type == ELF::SHT_AARCH64_AUTH_RELR);
4045 };
4046 auto GetEntriesNum = [&](const Elf_Shdr &Sec) -> Expected<size_t> {
4047 // Android's packed relocation section needs to be unpacked first
4048 // to get the actual number of entries.
4049 if (Sec.sh_type == ELF::SHT_ANDROID_REL ||
4050 Sec.sh_type == ELF::SHT_ANDROID_RELA) {
4051 Expected<std::vector<typename ELFT::Rela>> RelasOrErr =
4052 this->Obj.android_relas(Sec);
4053 if (!RelasOrErr)
4054 return RelasOrErr.takeError();
4055 return RelasOrErr->size();
4056 }
4057
4058 if (Sec.sh_type == ELF::SHT_CREL) {
4059 Expected<ArrayRef<uint8_t>> ContentsOrErr =
4060 this->Obj.getSectionContents(Sec);
4061 if (!ContentsOrErr)
4062 return ContentsOrErr.takeError();
4063 auto NumOrErr = this->Obj.getCrelHeader(*ContentsOrErr);
4064 if (!NumOrErr)
4065 return NumOrErr.takeError();
4066 return *NumOrErr / 8;
4067 }
4068
4069 if (PrintAsRelr(Sec)) {
4070 Expected<Elf_Relr_Range> RelrsOrErr = this->Obj.relrs(Sec);
4071 if (!RelrsOrErr)
4072 return RelrsOrErr.takeError();
4073 return this->Obj.decode_relrs(*RelrsOrErr).size();
4074 }
4075
4076 return Sec.getEntityCount();
4077 };
4078
4079 bool HasRelocSections = false;
4080 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4081 if (!isRelocationSec<ELFT>(Sec, this->Obj.getHeader()))
4082 continue;
4083 HasRelocSections = true;
4084
4085 std::string EntriesNum = "<?>";
4086 if (Expected<size_t> NumOrErr = GetEntriesNum(Sec))
4087 EntriesNum = std::to_string(val: *NumOrErr);
4088 else
4089 this->reportUniqueWarning("unable to get the number of relocations in " +
4090 this->describe(Sec) + ": " +
4091 toString(E: NumOrErr.takeError()));
4092
4093 uintX_t Offset = Sec.sh_offset;
4094 StringRef Name = this->getPrintableSectionName(Sec);
4095 OS << "\nRelocation section '" << Name << "' at offset 0x"
4096 << utohexstr(Offset, /*LowerCase=*/true) << " contains " << EntriesNum
4097 << " entries:\n";
4098
4099 if (PrintAsRelr(Sec)) {
4100 printRelr(Sec);
4101 } else {
4102 uint64_t CrelHdr = 0;
4103 // For CREL, read the header and call printRelocationsHelper only if
4104 // GetEntriesNum(Sec) succeeded.
4105 if (Sec.sh_type == ELF::SHT_CREL && EntriesNum != "<?>") {
4106 CrelHdr = cantFail(this->Obj.getCrelHeader(
4107 cantFail(this->Obj.getSectionContents(Sec))));
4108 }
4109 printRelocHeaderFields<ELFT>(OS, Sec.sh_type, this->Obj.getHeader(),
4110 CrelHdr);
4111 if (Sec.sh_type != ELF::SHT_CREL || EntriesNum != "<?>")
4112 this->printRelocationsHelper(Sec);
4113 }
4114 }
4115 if (!HasRelocSections)
4116 OS << "\nThere are no relocations in this file.\n";
4117}
4118
4119template <class ELFT> void GNUELFDumper<ELFT>::printRelr(const Elf_Shdr &Sec) {
4120 Expected<Elf_Relr_Range> RangeOrErr = this->Obj.relrs(Sec);
4121 if (!RangeOrErr) {
4122 this->reportUniqueWarning("unable to read relocations from " +
4123 this->describe(Sec) + ": " +
4124 toString(RangeOrErr.takeError()));
4125 return;
4126 }
4127 if (ELFT::Is64Bits)
4128 OS << "Index: Entry Address Symbolic Address\n";
4129 else
4130 OS << "Index: Entry Address Symbolic Address\n";
4131
4132 // If .symtab is available, collect its defined symbols and sort them by
4133 // st_value.
4134 SmallVector<std::pair<uint64_t, std::string>, 0> Syms;
4135 if (this->DotSymtabSec) {
4136 Elf_Sym_Range Symtab;
4137 std::optional<StringRef> Strtab;
4138 std::tie(Symtab, Strtab) = this->getSymtabAndStrtab();
4139 if (Symtab.size() && Strtab) {
4140 for (auto [I, Sym] : enumerate(Symtab)) {
4141 if (!Sym.st_shndx)
4142 continue;
4143 Syms.emplace_back(Sym.st_value,
4144 this->getFullSymbolName(Sym, I, ArrayRef<Elf_Word>(),
4145 *Strtab, false));
4146 }
4147 }
4148 }
4149 llvm::stable_sort(Range&: Syms);
4150
4151 typename ELFT::uint Base = 0;
4152 size_t I = 0;
4153 auto Print = [&](uint64_t Where) {
4154 OS << format_hex_no_prefix(Where, ELFT::Is64Bits ? 16 : 8);
4155 for (; I < Syms.size() && Syms[I].first <= Where; ++I)
4156 ;
4157 // Try symbolizing the address. Find the nearest symbol before or at the
4158 // address and print the symbol and the address difference.
4159 if (I) {
4160 OS << " " << Syms[I - 1].second;
4161 if (Syms[I - 1].first < Where)
4162 OS << " + 0x" << Twine::utohexstr(Val: Where - Syms[I - 1].first);
4163 }
4164 OS << '\n';
4165 };
4166 for (auto [Index, R] : enumerate(*RangeOrErr)) {
4167 typename ELFT::uint Entry = R;
4168 OS << formatv("{0:4}: ", Index)
4169 << format_hex_no_prefix(Entry, ELFT::Is64Bits ? 16 : 8) << ' ';
4170 if ((Entry & 1) == 0) {
4171 Print(Entry);
4172 Base = Entry + sizeof(typename ELFT::uint);
4173 } else {
4174 bool First = true;
4175 for (auto Where = Base; Entry >>= 1;
4176 Where += sizeof(typename ELFT::uint)) {
4177 if (Entry & 1) {
4178 if (First)
4179 First = false;
4180 else
4181 OS.indent(NumSpaces: ELFT::Is64Bits ? 24 : 16);
4182 Print(Where);
4183 }
4184 }
4185 Base += (CHAR_BIT * sizeof(Entry) - 1) * sizeof(typename ELFT::uint);
4186 }
4187 }
4188}
4189
4190// Print the offset of a particular section from anyone of the ranges:
4191// [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER].
4192// If 'Type' does not fall within any of those ranges, then a string is
4193// returned as '<unknown>' followed by the type value.
4194static std::string getSectionTypeOffsetString(unsigned Type) {
4195 if (Type >= SHT_LOOS && Type <= SHT_HIOS)
4196 return "LOOS+0x" + utohexstr(X: Type - SHT_LOOS, /*LowerCase=*/true);
4197 else if (Type >= SHT_LOPROC && Type <= SHT_HIPROC)
4198 return "LOPROC+0x" + utohexstr(X: Type - SHT_LOPROC, /*LowerCase=*/true);
4199 else if (Type >= SHT_LOUSER && Type <= SHT_HIUSER)
4200 return "LOUSER+0x" + utohexstr(X: Type - SHT_LOUSER, /*LowerCase=*/true);
4201 return "0x" + utohexstr(X: Type, /*LowerCase=*/true) + ": <unknown>";
4202}
4203
4204static std::string getSectionTypeString(unsigned Machine, unsigned Type) {
4205 StringRef Name = getELFSectionTypeName(Machine, Type);
4206
4207 // Handle SHT_GNU_* type names.
4208 if (Name.consume_front(Prefix: "SHT_GNU_")) {
4209 if (Name == "HASH")
4210 return "GNU_HASH";
4211 // E.g. SHT_GNU_verneed -> VERNEED.
4212 return Name.upper();
4213 }
4214
4215 if (Name == "SHT_SYMTAB_SHNDX")
4216 return "SYMTAB SECTION INDICES";
4217
4218 if (Name.consume_front(Prefix: "SHT_"))
4219 return Name.str();
4220 return getSectionTypeOffsetString(Type);
4221}
4222
4223static void printSectionDescription(formatted_raw_ostream &OS,
4224 unsigned EMachine) {
4225 OS << "Key to Flags:\n";
4226 OS << " W (write), A (alloc), X (execute), M (merge), S (strings), I "
4227 "(info),\n";
4228 OS << " L (link order), O (extra OS processing required), G (group), T "
4229 "(TLS),\n";
4230 OS << " C (compressed), x (unknown), o (OS specific), E (exclude),\n";
4231 OS << " R (retain)";
4232
4233 if (EMachine == EM_X86_64)
4234 OS << ", l (large)";
4235 else if (EMachine == EM_ARM || EMachine == EM_AARCH64)
4236 OS << ", y (purecode)";
4237
4238 OS << ", p (processor specific)\n";
4239}
4240
4241template <class ELFT> void GNUELFDumper<ELFT>::printSectionHeaders() {
4242 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
4243 if (Sections.empty()) {
4244 OS << "\nThere are no sections in this file.\n";
4245 Expected<StringRef> SecStrTableOrErr =
4246 this->Obj.getSectionStringTable(Sections, this->WarningHandler);
4247 if (!SecStrTableOrErr)
4248 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4249 return;
4250 }
4251 unsigned Bias = ELFT::Is64Bits ? 0 : 8;
4252 OS << "There are " << to_string(Sections.size())
4253 << " section headers, starting at offset "
4254 << "0x" << utohexstr(this->Obj.getHeader().e_shoff, /*LowerCase=*/true) << ":\n\n";
4255 OS << "Section Headers:\n";
4256 Field Fields[11] = {
4257 {"[Nr]", 2}, {"Name", 7}, {"Type", 25},
4258 {"Address", 41}, {"Off", 58 - Bias}, {"Size", 65 - Bias},
4259 {"ES", 72 - Bias}, {"Flg", 75 - Bias}, {"Lk", 79 - Bias},
4260 {"Inf", 82 - Bias}, {"Al", 86 - Bias}};
4261 for (const Field &F : Fields)
4262 printField(F);
4263 OS << "\n";
4264
4265 StringRef SecStrTable;
4266 if (Expected<StringRef> SecStrTableOrErr =
4267 this->Obj.getSectionStringTable(Sections, this->WarningHandler))
4268 SecStrTable = *SecStrTableOrErr;
4269 else
4270 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4271
4272 size_t SectionIndex = 0;
4273 for (const Elf_Shdr &Sec : Sections) {
4274 Fields[0].Str = to_string(Value: SectionIndex);
4275 if (SecStrTable.empty())
4276 Fields[1].Str = "<no-strings>";
4277 else
4278 Fields[1].Str = std::string(unwrapOrError<StringRef>(
4279 this->FileName, this->Obj.getSectionName(Sec, SecStrTable)));
4280 Fields[2].Str =
4281 getSectionTypeString(this->Obj.getHeader().e_machine, Sec.sh_type);
4282 Fields[3].Str =
4283 to_string(format_hex_no_prefix(Sec.sh_addr, ELFT::Is64Bits ? 16 : 8));
4284 Fields[4].Str = to_string(format_hex_no_prefix(Sec.sh_offset, 6));
4285 Fields[5].Str = to_string(format_hex_no_prefix(Sec.sh_size, 6));
4286 Fields[6].Str = to_string(format_hex_no_prefix(Sec.sh_entsize, 2));
4287 Fields[7].Str = getGNUFlags(this->Obj.getHeader().e_ident[ELF::EI_OSABI],
4288 this->Obj.getHeader().e_machine, Sec.sh_flags);
4289 Fields[8].Str = to_string(Sec.sh_link);
4290 Fields[9].Str = to_string(Sec.sh_info);
4291 Fields[10].Str = to_string(Sec.sh_addralign);
4292
4293 OS.PadToColumn(NewCol: Fields[0].Column);
4294 OS << "[" << right_justify(Fields[0].Str, 2) << "]";
4295 for (int i = 1; i < 7; i++)
4296 printField(F: Fields[i]);
4297 OS.PadToColumn(NewCol: Fields[7].Column);
4298 OS << right_justify(Fields[7].Str, 3);
4299 OS.PadToColumn(NewCol: Fields[8].Column);
4300 OS << right_justify(Fields[8].Str, 2);
4301 OS.PadToColumn(NewCol: Fields[9].Column);
4302 OS << right_justify(Fields[9].Str, 3);
4303 OS.PadToColumn(NewCol: Fields[10].Column);
4304 OS << right_justify(Fields[10].Str, 2);
4305 OS << "\n";
4306 ++SectionIndex;
4307 }
4308 printSectionDescription(OS, this->Obj.getHeader().e_machine);
4309}
4310
4311template <class ELFT>
4312void GNUELFDumper<ELFT>::printSymtabMessage(const Elf_Shdr *Symtab,
4313 size_t Entries,
4314 bool NonVisibilityBitsUsed,
4315 bool ExtraSymInfo) const {
4316 StringRef Name;
4317 if (Symtab)
4318 Name = this->getPrintableSectionName(*Symtab);
4319 if (!Name.empty())
4320 OS << "\nSymbol table '" << Name << "'";
4321 else
4322 OS << "\nSymbol table for image";
4323 OS << " contains " << Entries << " entries:\n";
4324
4325 if (ELFT::Is64Bits) {
4326 OS << " Num: Value Size Type Bind Vis";
4327 if (ExtraSymInfo)
4328 OS << "+Other";
4329 } else {
4330 OS << " Num: Value Size Type Bind Vis";
4331 if (ExtraSymInfo)
4332 OS << "+Other";
4333 }
4334
4335 OS.PadToColumn(NewCol: (ELFT::Is64Bits ? 56 : 48) + (NonVisibilityBitsUsed ? 13 : 0));
4336 if (ExtraSymInfo)
4337 OS << "Ndx(SecName) Name [+ Version Info]\n";
4338 else
4339 OS << "Ndx Name\n";
4340}
4341
4342template <class ELFT>
4343std::string GNUELFDumper<ELFT>::getSymbolSectionNdx(
4344 const Elf_Sym &Symbol, unsigned SymIndex, DataRegion<Elf_Word> ShndxTable,
4345 bool ExtraSymInfo) const {
4346 unsigned SectionIndex = Symbol.st_shndx;
4347 switch (SectionIndex) {
4348 case ELF::SHN_UNDEF:
4349 return "UND";
4350 case ELF::SHN_ABS:
4351 return "ABS";
4352 case ELF::SHN_COMMON:
4353 return "COM";
4354 case ELF::SHN_XINDEX: {
4355 Expected<uint32_t> IndexOrErr =
4356 object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, ShndxTable);
4357 if (!IndexOrErr) {
4358 assert(Symbol.st_shndx == SHN_XINDEX &&
4359 "getExtendedSymbolTableIndex should only fail due to an invalid "
4360 "SHT_SYMTAB_SHNDX table/reference");
4361 this->reportUniqueWarning(IndexOrErr.takeError());
4362 return "RSV[0xffff]";
4363 }
4364 SectionIndex = *IndexOrErr;
4365 break;
4366 }
4367 default:
4368 // Find if:
4369 // Processor specific
4370 if (SectionIndex >= ELF::SHN_LOPROC && SectionIndex <= ELF::SHN_HIPROC)
4371 return std::string("PRC[0x") +
4372 to_string(Value: format_hex_no_prefix(N: SectionIndex, Width: 4)) + "]";
4373 // OS specific
4374 if (SectionIndex >= ELF::SHN_LOOS && SectionIndex <= ELF::SHN_HIOS)
4375 return std::string("OS[0x") +
4376 to_string(Value: format_hex_no_prefix(N: SectionIndex, Width: 4)) + "]";
4377 // Architecture reserved:
4378 if (SectionIndex >= ELF::SHN_LORESERVE &&
4379 SectionIndex <= ELF::SHN_HIRESERVE)
4380 return std::string("RSV[0x") +
4381 to_string(Value: format_hex_no_prefix(N: SectionIndex, Width: 4)) + "]";
4382 break;
4383 }
4384
4385 std::string Extra;
4386 if (ExtraSymInfo) {
4387 auto Sec = this->Obj.getSection(SectionIndex);
4388 if (!Sec) {
4389 this->reportUniqueWarning(Sec.takeError());
4390 } else {
4391 auto SecName = this->Obj.getSectionName(**Sec);
4392 if (!SecName)
4393 this->reportUniqueWarning(SecName.takeError());
4394 else
4395 Extra = Twine(" (" + *SecName + ")").str();
4396 }
4397 }
4398 return to_string(Value: format_decimal(N: SectionIndex, Width: 3)) + Extra;
4399}
4400
4401template <class ELFT>
4402void GNUELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
4403 DataRegion<Elf_Word> ShndxTable,
4404 std::optional<StringRef> StrTable,
4405 bool IsDynamic, bool NonVisibilityBitsUsed,
4406 bool ExtraSymInfo) const {
4407 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4408 Field Fields[8] = {0, 8, 17 + Bias, 23 + Bias,
4409 31 + Bias, 38 + Bias, 48 + Bias, 51 + Bias};
4410 Fields[0].Str = to_string(Value: format_decimal(N: SymIndex, Width: 6)) + ":";
4411 Fields[1].Str =
4412 to_string(format_hex_no_prefix(Symbol.st_value, ELFT::Is64Bits ? 16 : 8));
4413 Fields[2].Str = to_string(format_decimal(Symbol.st_size, 5));
4414
4415 unsigned char SymbolType = Symbol.getType();
4416 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
4417 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
4418 Fields[3].Str = EnumStrings(AMDGPUSymbolTypes).toStringOrHex(Value: SymbolType, StrIdx: 1);
4419 else
4420 Fields[3].Str = getElfSymbolTypes().toStringOrHex(Value: SymbolType, StrIdx: 1);
4421
4422 Fields[4].Str =
4423 EnumStrings(ElfSymbolBindings).toStringOrHex(Symbol.getBinding(), 1);
4424 Fields[5].Str = EnumStrings(ElfSymbolVisibilities)
4425 .toStringOrHex(Symbol.getVisibility(), 1);
4426
4427 if (Symbol.st_other & ~0x3) {
4428 if (this->Obj.getHeader().e_machine == ELF::EM_AARCH64) {
4429 uint8_t Other = Symbol.st_other & ~0x3;
4430 if (Other & STO_AARCH64_VARIANT_PCS) {
4431 Other &= ~STO_AARCH64_VARIANT_PCS;
4432 Fields[5].Str += " [VARIANT_PCS";
4433 if (Other != 0)
4434 Fields[5].Str.append(" | " + utohexstr(X: Other, /*LowerCase=*/true));
4435 Fields[5].Str.append("]");
4436 }
4437 } else if (this->Obj.getHeader().e_machine == ELF::EM_RISCV) {
4438 uint8_t Other = Symbol.st_other & ~0x3;
4439 if (Other & STO_RISCV_VARIANT_CC) {
4440 Other &= ~STO_RISCV_VARIANT_CC;
4441 Fields[5].Str += " [VARIANT_CC";
4442 if (Other != 0)
4443 Fields[5].Str.append(" | " + utohexstr(X: Other, /*LowerCase=*/true));
4444 Fields[5].Str.append("]");
4445 }
4446 } else {
4447 Fields[5].Str +=
4448 " [<other: " + to_string(format_hex(Symbol.st_other, 2)) + ">]";
4449 }
4450 }
4451
4452 Fields[6].Column += NonVisibilityBitsUsed ? 13 : 0;
4453 Fields[6].Str =
4454 getSymbolSectionNdx(Symbol, SymIndex, ShndxTable, ExtraSymInfo);
4455
4456 Fields[7].Column += ExtraSymInfo ? 10 : 0;
4457 Fields[7].Str = this->getFullSymbolName(Symbol, SymIndex, ShndxTable,
4458 StrTable, IsDynamic);
4459 for (const Field &Entry : Fields)
4460 printField(F: Entry);
4461 OS << "\n";
4462}
4463
4464template <class ELFT>
4465void GNUELFDumper<ELFT>::printHashedSymbol(const Elf_Sym *Symbol,
4466 unsigned SymIndex,
4467 DataRegion<Elf_Word> ShndxTable,
4468 StringRef StrTable,
4469 uint32_t Bucket) {
4470 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4471 Field Fields[9] = {0, 6, 11, 20 + Bias, 25 + Bias,
4472 34 + Bias, 41 + Bias, 49 + Bias, 53 + Bias};
4473 Fields[0].Str = to_string(Value: format_decimal(N: SymIndex, Width: 5));
4474 Fields[1].Str = to_string(Value: format_decimal(N: Bucket, Width: 3)) + ":";
4475
4476 Fields[2].Str = to_string(
4477 format_hex_no_prefix(Symbol->st_value, ELFT::Is64Bits ? 16 : 8));
4478 Fields[3].Str = to_string(format_decimal(Symbol->st_size, 5));
4479
4480 unsigned char SymbolType = Symbol->getType();
4481 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
4482 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
4483 Fields[4].Str = EnumStrings(AMDGPUSymbolTypes).toString(Value: SymbolType, StrIdx: 1);
4484 else
4485 Fields[4].Str = getElfSymbolTypes().toStringOrHex(Value: SymbolType, StrIdx: 1);
4486
4487 Fields[5].Str =
4488 EnumStrings(ElfSymbolBindings).toString(Symbol->getBinding(), 1);
4489 Fields[6].Str =
4490 EnumStrings(ElfSymbolVisibilities).toString(Symbol->getVisibility(), 1);
4491 Fields[7].Str = getSymbolSectionNdx(Symbol: *Symbol, SymIndex, ShndxTable);
4492 Fields[8].Str =
4493 this->getFullSymbolName(*Symbol, SymIndex, ShndxTable, StrTable, true);
4494
4495 for (const Field &Entry : Fields)
4496 printField(F: Entry);
4497 OS << "\n";
4498}
4499
4500template <class ELFT>
4501void GNUELFDumper<ELFT>::printSymbols(bool PrintSymbols,
4502 bool PrintDynamicSymbols,
4503 bool ExtraSymInfo) {
4504 if (!PrintSymbols && !PrintDynamicSymbols)
4505 return;
4506 // GNU readelf prints both the .dynsym and .symtab with --symbols.
4507 this->printSymbolsHelper(true, ExtraSymInfo);
4508 if (PrintSymbols)
4509 this->printSymbolsHelper(false, ExtraSymInfo);
4510}
4511
4512template <class ELFT>
4513void GNUELFDumper<ELFT>::printHashTableSymbols(const Elf_Hash &SysVHash) {
4514 if (this->DynamicStringTable.empty())
4515 return;
4516
4517 if (ELFT::Is64Bits)
4518 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4519 else
4520 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4521 OS << "\n";
4522
4523 Elf_Sym_Range DynSyms = this->dynamic_symbols();
4524 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
4525 if (!FirstSym) {
4526 this->reportUniqueWarning(
4527 Twine("unable to print symbols for the .hash table: the "
4528 "dynamic symbol table ") +
4529 (this->DynSymRegion ? "is empty" : "was not found"));
4530 return;
4531 }
4532
4533 DataRegion<Elf_Word> ShndxTable(
4534 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
4535 auto Buckets = SysVHash.buckets();
4536 auto Chains = SysVHash.chains();
4537 for (uint32_t Buc = 0; Buc < SysVHash.nbucket; Buc++) {
4538 if (Buckets[Buc] == ELF::STN_UNDEF)
4539 continue;
4540 BitVector Visited(SysVHash.nchain);
4541 for (uint32_t Ch = Buckets[Buc]; Ch < SysVHash.nchain; Ch = Chains[Ch]) {
4542 if (Ch == ELF::STN_UNDEF)
4543 break;
4544
4545 if (Visited[Ch]) {
4546 this->reportUniqueWarning(".hash section is invalid: bucket " +
4547 Twine(Ch) +
4548 ": a cycle was detected in the linked chain");
4549 break;
4550 }
4551
4552 printHashedSymbol(Symbol: FirstSym + Ch, SymIndex: Ch, ShndxTable, StrTable: this->DynamicStringTable,
4553 Bucket: Buc);
4554 Visited[Ch] = true;
4555 }
4556 }
4557}
4558
4559template <class ELFT>
4560void GNUELFDumper<ELFT>::printGnuHashTableSymbols(const Elf_GnuHash &GnuHash) {
4561 if (this->DynamicStringTable.empty())
4562 return;
4563
4564 Elf_Sym_Range DynSyms = this->dynamic_symbols();
4565 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0];
4566 if (!FirstSym) {
4567 this->reportUniqueWarning(
4568 Twine("unable to print symbols for the .gnu.hash table: the "
4569 "dynamic symbol table ") +
4570 (this->DynSymRegion ? "is empty" : "was not found"));
4571 return;
4572 }
4573
4574 auto GetSymbol = [&](uint64_t SymIndex,
4575 uint64_t SymsTotal) -> const Elf_Sym * {
4576 if (SymIndex >= SymsTotal) {
4577 this->reportUniqueWarning(
4578 "unable to print hashed symbol with index " + Twine(SymIndex) +
4579 ", which is greater than or equal to the number of dynamic symbols "
4580 "(" +
4581 Twine::utohexstr(Val: SymsTotal) + ")");
4582 return nullptr;
4583 }
4584 return FirstSym + SymIndex;
4585 };
4586
4587 Expected<ArrayRef<Elf_Word>> ValuesOrErr =
4588 getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHash);
4589 ArrayRef<Elf_Word> Values;
4590 if (!ValuesOrErr)
4591 this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH "
4592 "section: " +
4593 toString(ValuesOrErr.takeError()));
4594 else
4595 Values = *ValuesOrErr;
4596
4597 DataRegion<Elf_Word> ShndxTable(
4598 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
4599 ArrayRef<Elf_Word> Buckets = GnuHash.buckets();
4600 for (uint32_t Buc = 0; Buc < GnuHash.nbuckets; Buc++) {
4601 if (Buckets[Buc] == ELF::STN_UNDEF)
4602 continue;
4603 uint32_t Index = Buckets[Buc];
4604 // Print whole chain.
4605 while (true) {
4606 uint32_t SymIndex = Index++;
4607 if (const Elf_Sym *Sym = GetSymbol(SymIndex, DynSyms.size()))
4608 printHashedSymbol(Symbol: Sym, SymIndex, ShndxTable, StrTable: this->DynamicStringTable,
4609 Bucket: Buc);
4610 else
4611 break;
4612
4613 if (SymIndex < GnuHash.symndx) {
4614 this->reportUniqueWarning(
4615 "unable to read the hash value for symbol with index " +
4616 Twine(SymIndex) +
4617 ", which is less than the index of the first hashed symbol (" +
4618 Twine(GnuHash.symndx) + ")");
4619 break;
4620 }
4621
4622 // Chain ends at symbol with stopper bit.
4623 if ((Values[SymIndex - GnuHash.symndx] & 1) == 1)
4624 break;
4625 }
4626 }
4627}
4628
4629template <class ELFT> void GNUELFDumper<ELFT>::printHashSymbols() {
4630 if (this->HashTable) {
4631 OS << "\n Symbol table of .hash for image:\n";
4632 if (Error E = checkHashTable<ELFT>(*this, this->HashTable))
4633 this->reportUniqueWarning(std::move(E));
4634 else
4635 printHashTableSymbols(SysVHash: *this->HashTable);
4636 }
4637
4638 // Try printing the .gnu.hash table.
4639 if (this->GnuHashTable) {
4640 OS << "\n Symbol table of .gnu.hash for image:\n";
4641 if (ELFT::Is64Bits)
4642 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4643 else
4644 OS << " Num Buc: Value Size Type Bind Vis Ndx Name";
4645 OS << "\n";
4646
4647 if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable))
4648 this->reportUniqueWarning(std::move(E));
4649 else
4650 printGnuHashTableSymbols(GnuHash: *this->GnuHashTable);
4651 }
4652}
4653
4654template <class ELFT> void GNUELFDumper<ELFT>::printSectionDetails() {
4655 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections());
4656 if (Sections.empty()) {
4657 OS << "\nThere are no sections in this file.\n";
4658 Expected<StringRef> SecStrTableOrErr =
4659 this->Obj.getSectionStringTable(Sections, this->WarningHandler);
4660 if (!SecStrTableOrErr)
4661 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4662 return;
4663 }
4664 OS << "There are " << to_string(Sections.size())
4665 << " section headers, starting at offset "
4666 << "0x" << utohexstr(this->Obj.getHeader().e_shoff, /*LowerCase=*/true) << ":\n\n";
4667
4668 OS << "Section Headers:\n";
4669
4670 auto PrintFields = [&](ArrayRef<Field> V) {
4671 for (const Field &F : V)
4672 printField(F);
4673 OS << "\n";
4674 };
4675
4676 PrintFields({{"[Nr]", 2}, {"Name", 7}});
4677
4678 constexpr bool Is64 = ELFT::Is64Bits;
4679 PrintFields({{"Type", 7},
4680 {Is64 ? "Address" : "Addr", 23},
4681 {{"Off"}, Is64 ? 40 : 32},
4682 {{"Size"}, Is64 ? 47 : 39},
4683 {{"ES"}, Is64 ? 54 : 46},
4684 {{"Lk"}, Is64 ? 59 : 51},
4685 {{"Inf"}, Is64 ? 62 : 54},
4686 {{"Al"}, Is64 ? 66 : 57}});
4687 PrintFields({{"Flags", 7}});
4688
4689 StringRef SecStrTable;
4690 if (Expected<StringRef> SecStrTableOrErr =
4691 this->Obj.getSectionStringTable(Sections, this->WarningHandler))
4692 SecStrTable = *SecStrTableOrErr;
4693 else
4694 this->reportUniqueWarning(SecStrTableOrErr.takeError());
4695
4696 size_t SectionIndex = 0;
4697 const unsigned AddrSize = Is64 ? 16 : 8;
4698 for (const Elf_Shdr &S : Sections) {
4699 StringRef Name = "<?>";
4700 if (Expected<StringRef> NameOrErr =
4701 this->Obj.getSectionName(S, SecStrTable))
4702 Name = *NameOrErr;
4703 else
4704 this->reportUniqueWarning(NameOrErr.takeError());
4705
4706 OS.PadToColumn(NewCol: 2);
4707 OS << "[" << right_justify(Str: to_string(Value: SectionIndex), Width: 2) << "]";
4708 PrintFields({{Name, 7}});
4709 PrintFields(
4710 {{getSectionTypeString(this->Obj.getHeader().e_machine, S.sh_type), 7},
4711 {to_string(format_hex_no_prefix(S.sh_addr, AddrSize)), 23},
4712 {to_string(format_hex_no_prefix(S.sh_offset, 6)), Is64 ? 39 : 32},
4713 {to_string(format_hex_no_prefix(S.sh_size, 6)), Is64 ? 47 : 39},
4714 {to_string(format_hex_no_prefix(S.sh_entsize, 2)), Is64 ? 54 : 46},
4715 {to_string(S.sh_link), Is64 ? 59 : 51},
4716 {to_string(S.sh_info), Is64 ? 63 : 55},
4717 {to_string(S.sh_addralign), Is64 ? 66 : 58}});
4718
4719 OS.PadToColumn(NewCol: 7);
4720 OS << "[" << to_string(format_hex_no_prefix(S.sh_flags, AddrSize)) << "]: ";
4721
4722 DenseMap<unsigned, StringRef> FlagToName = {
4723 {SHF_WRITE, "WRITE"}, {SHF_ALLOC, "ALLOC"},
4724 {SHF_EXECINSTR, "EXEC"}, {SHF_MERGE, "MERGE"},
4725 {SHF_STRINGS, "STRINGS"}, {SHF_INFO_LINK, "INFO LINK"},
4726 {SHF_LINK_ORDER, "LINK ORDER"}, {SHF_OS_NONCONFORMING, "OS NONCONF"},
4727 {SHF_GROUP, "GROUP"}, {SHF_TLS, "TLS"},
4728 {SHF_COMPRESSED, "COMPRESSED"}, {SHF_EXCLUDE, "EXCLUDE"}};
4729
4730 uint64_t Flags = S.sh_flags;
4731 uint64_t UnknownFlags = 0;
4732 ListSeparator LS;
4733 while (Flags) {
4734 // Take the least significant bit as a flag.
4735 uint64_t Flag = Flags & -Flags;
4736 Flags -= Flag;
4737
4738 auto It = FlagToName.find(Val: Flag);
4739 if (It != FlagToName.end())
4740 OS << LS << It->second;
4741 else
4742 UnknownFlags |= Flag;
4743 }
4744
4745 auto PrintUnknownFlags = [&](uint64_t Mask, StringRef Name) {
4746 uint64_t FlagsToPrint = UnknownFlags & Mask;
4747 if (!FlagsToPrint)
4748 return;
4749
4750 OS << LS << Name << " ("
4751 << to_string(Value: format_hex_no_prefix(N: FlagsToPrint, Width: AddrSize)) << ")";
4752 UnknownFlags &= ~Mask;
4753 };
4754
4755 PrintUnknownFlags(SHF_MASKOS, "OS");
4756 PrintUnknownFlags(SHF_MASKPROC, "PROC");
4757 PrintUnknownFlags(uint64_t(-1), "UNKNOWN");
4758
4759 OS << "\n";
4760 ++SectionIndex;
4761
4762 if (!(S.sh_flags & SHF_COMPRESSED))
4763 continue;
4764 Expected<ArrayRef<uint8_t>> Data = this->Obj.getSectionContents(S);
4765 if (!Data || Data->size() < sizeof(Elf_Chdr)) {
4766 consumeError(Err: Data.takeError());
4767 reportWarning(createError(Err: "SHF_COMPRESSED section '" + Name +
4768 "' does not have an Elf_Chdr header"),
4769 this->FileName);
4770 OS.indent(NumSpaces: 7);
4771 OS << "[<corrupt>]";
4772 } else {
4773 OS.indent(NumSpaces: 7);
4774 auto *Chdr = reinterpret_cast<const Elf_Chdr *>(Data->data());
4775 if (Chdr->ch_type == ELFCOMPRESS_ZLIB)
4776 OS << "ZLIB";
4777 else if (Chdr->ch_type == ELFCOMPRESS_ZSTD)
4778 OS << "ZSTD";
4779 else
4780 OS << format(Fmt: "[<unknown>: 0x%x]", Vals: unsigned(Chdr->ch_type));
4781 OS << ", " << format_hex_no_prefix(Chdr->ch_size, ELFT::Is64Bits ? 16 : 8)
4782 << ", " << Chdr->ch_addralign;
4783 }
4784 OS << '\n';
4785 }
4786}
4787
4788static inline std::string printPhdrFlags(unsigned Flag) {
4789 std::string Str;
4790 Str = (Flag & PF_R) ? "R" : " ";
4791 Str += (Flag & PF_W) ? "W" : " ";
4792 Str += (Flag & PF_X) ? "E" : " ";
4793 return Str;
4794}
4795
4796template <class ELFT>
4797static bool checkTLSSections(const typename ELFT::Phdr &Phdr,
4798 const typename ELFT::Shdr &Sec) {
4799 if (Sec.sh_flags & ELF::SHF_TLS) {
4800 // .tbss must only be shown in the PT_TLS segment.
4801 if (Sec.sh_type == ELF::SHT_NOBITS)
4802 return Phdr.p_type == ELF::PT_TLS;
4803
4804 // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO
4805 // segments.
4806 return (Phdr.p_type == ELF::PT_TLS) || (Phdr.p_type == ELF::PT_LOAD) ||
4807 (Phdr.p_type == ELF::PT_GNU_RELRO);
4808 }
4809
4810 // PT_TLS must only have SHF_TLS sections.
4811 return Phdr.p_type != ELF::PT_TLS;
4812}
4813
4814template <class ELFT>
4815static bool checkPTDynamic(const typename ELFT::Phdr &Phdr,
4816 const typename ELFT::Shdr &Sec) {
4817 if (Phdr.p_type != ELF::PT_DYNAMIC || Phdr.p_memsz == 0 || Sec.sh_size != 0)
4818 return true;
4819
4820 // We get here when we have an empty section. Only non-empty sections can be
4821 // at the start or at the end of PT_DYNAMIC.
4822 // Is section within the phdr both based on offset and VMA?
4823 bool CheckOffset = (Sec.sh_type == ELF::SHT_NOBITS) ||
4824 (Sec.sh_offset > Phdr.p_offset &&
4825 Sec.sh_offset < Phdr.p_offset + Phdr.p_filesz);
4826 bool CheckVA = !(Sec.sh_flags & ELF::SHF_ALLOC) ||
4827 (Sec.sh_addr > Phdr.p_vaddr && Sec.sh_addr < Phdr.p_memsz);
4828 return CheckOffset && CheckVA;
4829}
4830
4831template <class ELFT>
4832void GNUELFDumper<ELFT>::printProgramHeaders(
4833 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
4834 bool ShouldPrintSectionMapping =
4835 (PrintSectionMapping != cl::boolOrDefault::BOU_FALSE);
4836 // Exit early if no program header or section mapping details were requested.
4837 if (!PrintProgramHeaders && !ShouldPrintSectionMapping)
4838 return;
4839
4840 if (PrintProgramHeaders) {
4841 Expected<uint32_t> PhNumOrErr = this->Obj.getPhNum();
4842 if (!PhNumOrErr) {
4843 this->reportUniqueWarning(PhNumOrErr.takeError());
4844 ShouldPrintSectionMapping = false;
4845 } else if (*PhNumOrErr == 0) {
4846 OS << "\nThere are no program headers in this file.\n";
4847 } else {
4848 printProgramHeaders();
4849 }
4850 }
4851
4852 if (ShouldPrintSectionMapping)
4853 printSectionMapping();
4854}
4855
4856template <class ELFT> void GNUELFDumper<ELFT>::printProgramHeaders() {
4857 unsigned Bias = ELFT::Is64Bits ? 8 : 0;
4858 const Elf_Ehdr &Header = this->Obj.getHeader();
4859 Field Fields[8] = {2, 17, 26, 37 + Bias,
4860 48 + Bias, 56 + Bias, 64 + Bias, 68 + Bias};
4861 uint32_t PhNum = 0;
4862 Expected<uint32_t> PhNumOrErr = this->Obj.getPhNum();
4863
4864 // The caller already performs this check, so failure is impossible.
4865 if (PhNumOrErr)
4866 PhNum = *PhNumOrErr;
4867 else
4868 cantFail(Err: PhNumOrErr.takeError());
4869
4870 OS << "\nElf file type is "
4871 << EnumStrings(ElfObjectFileType).toStringOrHex(Header.e_type, 1) << "\n"
4872 << "Entry point " << format_hex(Header.e_entry, 3) << "\n"
4873 << "There are " << PhNum << " program headers,"
4874 << " starting at offset " << Header.e_phoff << "\n\n"
4875 << "Program Headers:\n";
4876 if (ELFT::Is64Bits)
4877 OS << " Type Offset VirtAddr PhysAddr "
4878 << " FileSiz MemSiz Flg Align\n";
4879 else
4880 OS << " Type Offset VirtAddr PhysAddr FileSiz "
4881 << "MemSiz Flg Align\n";
4882
4883 unsigned Width = ELFT::Is64Bits ? 18 : 10;
4884 unsigned SizeWidth = ELFT::Is64Bits ? 8 : 7;
4885
4886 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4887 if (!PhdrsOrErr) {
4888 this->reportUniqueWarning("unable to dump program headers: " +
4889 toString(PhdrsOrErr.takeError()));
4890 return;
4891 }
4892
4893 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4894 Fields[0].Str = getGNUPtType(Header.e_machine, Phdr.p_type);
4895 Fields[1].Str = to_string(format_hex(Phdr.p_offset, 8));
4896 Fields[2].Str = to_string(format_hex(Phdr.p_vaddr, Width));
4897 Fields[3].Str = to_string(format_hex(Phdr.p_paddr, Width));
4898 Fields[4].Str = to_string(format_hex(Phdr.p_filesz, SizeWidth));
4899 Fields[5].Str = to_string(format_hex(Phdr.p_memsz, SizeWidth));
4900 Fields[6].Str = printPhdrFlags(Phdr.p_flags);
4901 Fields[7].Str = to_string(format_hex(Phdr.p_align, 1));
4902 for (const Field &F : Fields)
4903 printField(F);
4904 if (Phdr.p_type == ELF::PT_INTERP) {
4905 OS << "\n";
4906 auto ReportBadInterp = [&](const Twine &Msg) {
4907 this->reportUniqueWarning(
4908 "unable to read program interpreter name at offset 0x" +
4909 Twine::utohexstr(Val: Phdr.p_offset) + ": " + Msg);
4910 };
4911
4912 if (Phdr.p_offset >= this->Obj.getBufSize()) {
4913 ReportBadInterp("it goes past the end of the file (0x" +
4914 Twine::utohexstr(Val: this->Obj.getBufSize()) + ")");
4915 continue;
4916 }
4917
4918 const char *Data =
4919 reinterpret_cast<const char *>(this->Obj.base()) + Phdr.p_offset;
4920 size_t MaxSize = this->Obj.getBufSize() - Phdr.p_offset;
4921 size_t Len = strnlen(string: Data, maxlen: MaxSize);
4922 if (Len == MaxSize) {
4923 ReportBadInterp("it is not null-terminated");
4924 continue;
4925 }
4926
4927 OS << " [Requesting program interpreter: ";
4928 OS << StringRef(Data, Len) << "]";
4929 }
4930 OS << "\n";
4931 }
4932}
4933
4934template <class ELFT> void GNUELFDumper<ELFT>::printSectionMapping() {
4935 OS << "\n Section to Segment mapping:\n Segment Sections...\n";
4936 DenseSet<const Elf_Shdr *> BelongsToSegment;
4937 int Phnum = 0;
4938
4939 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
4940 if (!PhdrsOrErr) {
4941 this->reportUniqueWarning(
4942 "can't read program headers to build section to segment mapping: " +
4943 toString(PhdrsOrErr.takeError()));
4944 return;
4945 }
4946
4947 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
4948 std::string Sections;
4949 OS << format(Fmt: " %2.2d ", Vals: Phnum++);
4950 // Check if each section is in a segment and then print mapping.
4951 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4952 if (Sec.sh_type == ELF::SHT_NULL)
4953 continue;
4954
4955 // readelf additionally makes sure it does not print zero sized sections
4956 // at end of segments and for PT_DYNAMIC both start and end of section
4957 // .tbss must only be shown in PT_TLS section.
4958 if (isSectionInSegment<ELFT>(Phdr, Sec) &&
4959 checkTLSSections<ELFT>(Phdr, Sec) &&
4960 checkPTDynamic<ELFT>(Phdr, Sec)) {
4961 Sections +=
4962 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4963 " ";
4964 BelongsToSegment.insert(&Sec);
4965 }
4966 }
4967 OS << Sections << "\n";
4968 OS.flush();
4969 }
4970
4971 // Display sections that do not belong to a segment.
4972 std::string Sections;
4973 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
4974 if (BelongsToSegment.find(&Sec) == BelongsToSegment.end())
4975 Sections +=
4976 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() +
4977 ' ';
4978 }
4979 if (!Sections.empty()) {
4980 OS << " None " << Sections << '\n';
4981 OS.flush();
4982 }
4983}
4984
4985namespace {
4986
4987template <class ELFT>
4988RelSymbol<ELFT> getSymbolForReloc(const ELFDumper<ELFT> &Dumper,
4989 const Relocation<ELFT> &Reloc) {
4990 using Elf_Sym = typename ELFT::Sym;
4991 auto WarnAndReturn = [&](const Elf_Sym *Sym,
4992 const Twine &Reason) -> RelSymbol<ELFT> {
4993 Dumper.reportUniqueWarning(
4994 "unable to get name of the dynamic symbol with index " +
4995 Twine(Reloc.Symbol) + ": " + Reason);
4996 return {Sym, "<corrupt>"};
4997 };
4998
4999 ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols();
5000 const Elf_Sym *FirstSym = Symbols.begin();
5001 if (!FirstSym)
5002 return WarnAndReturn(nullptr, "no dynamic symbol table found");
5003
5004 // We might have an object without a section header. In this case the size of
5005 // Symbols is zero, because there is no way to know the size of the dynamic
5006 // table. We should allow this case and not print a warning.
5007 if (!Symbols.empty() && Reloc.Symbol >= Symbols.size())
5008 return WarnAndReturn(
5009 nullptr,
5010 "index is greater than or equal to the number of dynamic symbols (" +
5011 Twine(Symbols.size()) + ")");
5012
5013 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
5014 const uint64_t FileSize = Obj.getBufSize();
5015 const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) +
5016 (uint64_t)Reloc.Symbol * sizeof(Elf_Sym);
5017 if (SymOffset + sizeof(Elf_Sym) > FileSize)
5018 return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(Val: SymOffset) +
5019 " goes past the end of the file (0x" +
5020 Twine::utohexstr(Val: FileSize) + ")");
5021
5022 const Elf_Sym *Sym = FirstSym + Reloc.Symbol;
5023 Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable());
5024 if (!ErrOrName)
5025 return WarnAndReturn(Sym, toString(E: ErrOrName.takeError()));
5026
5027 return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(Name: *ErrOrName)};
5028}
5029} // namespace
5030
5031template <class ELFT>
5032static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj,
5033 typename ELFT::DynRange Tags) {
5034 size_t Max = 0;
5035 for (const typename ELFT::Dyn &Dyn : Tags)
5036 Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size());
5037 return Max;
5038}
5039
5040template <class ELFT> void GNUELFDumper<ELFT>::printDynamicTable() {
5041 Elf_Dyn_Range Table = this->dynamic_table();
5042 if (Table.empty())
5043 return;
5044
5045 OS << "Dynamic section at offset "
5046 << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable.Addr) -
5047 this->Obj.base(),
5048 1)
5049 << " contains " << Table.size() << " entries:\n";
5050
5051 // The type name is surrounded with round brackets, hence add 2.
5052 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2;
5053 // The "Name/Value" column should be indented from the "Type" column by N
5054 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
5055 // space (1) = 3.
5056 OS << " Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type"
5057 << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
5058
5059 std::string ValueFmt = " %-" + std::to_string(val: MaxTagSize) + "s ";
5060 for (auto Entry : Table) {
5061 uintX_t Tag = Entry.getTag();
5062 std::string Type =
5063 std::string("(") + this->Obj.getDynamicTagAsString(Tag) + ")";
5064 std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
5065 OS << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10)
5066 << format(Fmt: ValueFmt.c_str(), Vals: Type.c_str()) << Value << "\n";
5067 }
5068}
5069
5070template <class ELFT> void GNUELFDumper<ELFT>::printDynamicRelocations() {
5071 this->printDynamicRelocationsHelper();
5072}
5073
5074template <class ELFT>
5075void ELFDumper<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) {
5076 printRelRelaReloc(R, RelSym: getSymbolForReloc(*this, R));
5077}
5078
5079template <class ELFT>
5080void ELFDumper<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) {
5081 this->forEachRelocationDo(
5082 Sec, RelRelaFn: [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec,
5083 const Elf_Shdr *SymTab) { printReloc(R, RelIndex: Ndx, Sec, SymTab); });
5084}
5085
5086template <class ELFT> void ELFDumper<ELFT>::printDynamicRelocationsHelper() {
5087 const bool IsMips64EL = this->Obj.isMips64EL();
5088 auto DumpCrelRegion = [&](DynRegionInfo &Region) {
5089 // While the size is unknown, a valid CREL has at least one byte. We can
5090 // check whether Addr is in bounds, and then decode CREL until the file
5091 // end.
5092 Region.Size = Region.EntSize = 1;
5093 if (!Region.template getAsArrayRef<uint8_t>().empty()) {
5094 const uint64_t Offset =
5095 Region.Addr - reinterpret_cast<const uint8_t *>(
5096 ObjF.getMemoryBufferRef().getBufferStart());
5097 const uint64_t ObjSize = ObjF.getMemoryBufferRef().getBufferSize();
5098 auto RelsOrRelas =
5099 Obj.decodeCrel(ArrayRef<uint8_t>(Region.Addr, ObjSize - Offset));
5100 if (!RelsOrRelas) {
5101 reportUniqueWarning(toString(RelsOrRelas.takeError()));
5102 } else {
5103 for (const Elf_Rel &R : RelsOrRelas->first)
5104 printDynamicReloc(R: Relocation<ELFT>(R, false));
5105 for (const Elf_Rela &R : RelsOrRelas->second)
5106 printDynamicReloc(R: Relocation<ELFT>(R, false));
5107 }
5108 }
5109 };
5110
5111 if (this->DynCrelRegion.Addr) {
5112 printDynamicRelocHeader(Type: ELF::SHT_CREL, Name: "CREL", Reg: this->DynCrelRegion);
5113 DumpCrelRegion(this->DynCrelRegion);
5114 }
5115
5116 if (this->DynRelaRegion.Size > 0) {
5117 printDynamicRelocHeader(Type: ELF::SHT_RELA, Name: "RELA", Reg: this->DynRelaRegion);
5118 for (const Elf_Rela &Rela :
5119 this->DynRelaRegion.template getAsArrayRef<Elf_Rela>())
5120 printDynamicReloc(R: Relocation<ELFT>(Rela, IsMips64EL));
5121 }
5122
5123 if (this->DynRelRegion.Size > 0) {
5124 printDynamicRelocHeader(Type: ELF::SHT_REL, Name: "REL", Reg: this->DynRelRegion);
5125 for (const Elf_Rel &Rel :
5126 this->DynRelRegion.template getAsArrayRef<Elf_Rel>())
5127 printDynamicReloc(R: Relocation<ELFT>(Rel, IsMips64EL));
5128 }
5129
5130 if (this->DynRelrRegion.Size > 0) {
5131 printDynamicRelocHeader(Type: ELF::SHT_REL, Name: "RELR", Reg: this->DynRelrRegion);
5132 Elf_Relr_Range Relrs =
5133 this->DynRelrRegion.template getAsArrayRef<Elf_Relr>();
5134 for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs))
5135 printDynamicReloc(R: Relocation<ELFT>(Rel, IsMips64EL));
5136 }
5137
5138 if (this->DynPLTRelRegion.Size) {
5139 if (this->DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) {
5140 printDynamicRelocHeader(Type: ELF::SHT_RELA, Name: "PLT", Reg: this->DynPLTRelRegion);
5141 for (const Elf_Rela &Rela :
5142 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rela>())
5143 printDynamicReloc(R: Relocation<ELFT>(Rela, IsMips64EL));
5144 } else if (this->DynPLTRelRegion.EntSize == 1) {
5145 DumpCrelRegion(this->DynPLTRelRegion);
5146 } else {
5147 printDynamicRelocHeader(Type: ELF::SHT_REL, Name: "PLT", Reg: this->DynPLTRelRegion);
5148 for (const Elf_Rel &Rel :
5149 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rel>())
5150 printDynamicReloc(R: Relocation<ELFT>(Rel, IsMips64EL));
5151 }
5152 }
5153}
5154
5155template <class ELFT>
5156void GNUELFDumper<ELFT>::printGNUVersionSectionProlog(
5157 const typename ELFT::Shdr &Sec, const Twine &Label, unsigned EntriesNum) {
5158 // Don't inline the SecName, because it might report a warning to stderr and
5159 // corrupt the output.
5160 StringRef SecName = this->getPrintableSectionName(Sec);
5161 OS << Label << " section '" << SecName << "' "
5162 << "contains " << EntriesNum << " entries:\n";
5163
5164 StringRef LinkedSecName = "<corrupt>";
5165 if (Expected<const typename ELFT::Shdr *> LinkedSecOrErr =
5166 this->Obj.getSection(Sec.sh_link))
5167 LinkedSecName = this->getPrintableSectionName(**LinkedSecOrErr);
5168 else
5169 this->reportUniqueWarning("invalid section linked to " +
5170 this->describe(Sec) + ": " +
5171 toString(LinkedSecOrErr.takeError()));
5172
5173 OS << " Addr: " << format_hex_no_prefix(Sec.sh_addr, 16)
5174 << " Offset: " << format_hex(Sec.sh_offset, 8)
5175 << " Link: " << Sec.sh_link << " (" << LinkedSecName << ")\n";
5176}
5177
5178template <class ELFT>
5179void GNUELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
5180 if (!Sec)
5181 return;
5182
5183 printGNUVersionSectionProlog(Sec: *Sec, Label: "Version symbols",
5184 EntriesNum: Sec->sh_size / sizeof(Elf_Versym));
5185 Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
5186 this->getVersionTable(*Sec, /*SymTab=*/nullptr,
5187 /*StrTab=*/nullptr, /*SymTabSec=*/nullptr);
5188 if (!VerTableOrErr) {
5189 this->reportUniqueWarning(VerTableOrErr.takeError());
5190 return;
5191 }
5192
5193 SmallVector<std::optional<VersionEntry>, 0> *VersionMap = nullptr;
5194 if (Expected<SmallVector<std::optional<VersionEntry>, 0> *> MapOrErr =
5195 this->getVersionMap())
5196 VersionMap = *MapOrErr;
5197 else
5198 this->reportUniqueWarning(MapOrErr.takeError());
5199
5200 ArrayRef<Elf_Versym> VerTable = *VerTableOrErr;
5201 std::vector<StringRef> Versions;
5202 for (size_t I = 0, E = VerTable.size(); I < E; ++I) {
5203 unsigned Ndx = VerTable[I].vs_index;
5204 if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) {
5205 Versions.emplace_back(args: Ndx == VER_NDX_LOCAL ? "*local*" : "*global*");
5206 continue;
5207 }
5208
5209 if (!VersionMap) {
5210 Versions.emplace_back(args: "<corrupt>");
5211 continue;
5212 }
5213
5214 bool IsDefault;
5215 Expected<StringRef> NameOrErr = this->Obj.getSymbolVersionByIndex(
5216 Ndx, IsDefault, *VersionMap, /*IsSymHidden=*/std::nullopt);
5217 if (!NameOrErr) {
5218 this->reportUniqueWarning("unable to get a version for entry " +
5219 Twine(I) + " of " + this->describe(*Sec) +
5220 ": " + toString(E: NameOrErr.takeError()));
5221 Versions.emplace_back(args: "<corrupt>");
5222 continue;
5223 }
5224 Versions.emplace_back(args&: *NameOrErr);
5225 }
5226
5227 // readelf prints 4 entries per line.
5228 uint64_t Entries = VerTable.size();
5229 for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) {
5230 OS << " " << format_hex_no_prefix(N: VersymRow, Width: 3) << ":";
5231 for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) {
5232 unsigned Ndx = VerTable[VersymRow + I].vs_index;
5233 OS << format(Fmt: "%4x%c", Vals: Ndx & VERSYM_VERSION,
5234 Vals: Ndx & VERSYM_HIDDEN ? 'h' : ' ');
5235 OS << left_justify(Str: "(" + std::string(Versions[VersymRow + I]) + ")", Width: 13);
5236 }
5237 OS << '\n';
5238 }
5239 OS << '\n';
5240}
5241
5242static std::string versionFlagToString(unsigned Flags) {
5243 if (Flags == 0)
5244 return "none";
5245
5246 std::string Ret;
5247 auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) {
5248 if (!(Flags & Flag))
5249 return;
5250 if (!Ret.empty())
5251 Ret += " | ";
5252 Ret += Name;
5253 Flags &= ~Flag;
5254 };
5255
5256 AddFlag(VER_FLG_BASE, "BASE");
5257 AddFlag(VER_FLG_WEAK, "WEAK");
5258 AddFlag(VER_FLG_INFO, "INFO");
5259 AddFlag(~0, "<unknown>");
5260 return Ret;
5261}
5262
5263template <class ELFT>
5264void GNUELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
5265 if (!Sec)
5266 return;
5267
5268 printGNUVersionSectionProlog(Sec: *Sec, Label: "Version definition", EntriesNum: Sec->sh_info);
5269
5270 Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
5271 if (!V) {
5272 this->reportUniqueWarning(V.takeError());
5273 return;
5274 }
5275
5276 for (const VerDef &Def : *V) {
5277 OS << format(Fmt: " 0x%04x: Rev: %u Flags: %s Index: %u Cnt: %u Name: %s\n",
5278 Vals: Def.Offset, Vals: Def.Version,
5279 Vals: versionFlagToString(Flags: Def.Flags).c_str(), Vals: Def.Ndx, Vals: Def.Cnt,
5280 Vals: Def.Name.data());
5281 unsigned I = 0;
5282 for (const VerdAux &Aux : Def.AuxV)
5283 OS << format(Fmt: " 0x%04x: Parent %u: %s\n", Vals: Aux.Offset, Vals: ++I,
5284 Vals: Aux.Name.data());
5285 }
5286
5287 OS << '\n';
5288}
5289
5290template <class ELFT>
5291void GNUELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
5292 if (!Sec)
5293 return;
5294
5295 unsigned VerneedNum = Sec->sh_info;
5296 printGNUVersionSectionProlog(Sec: *Sec, Label: "Version needs", EntriesNum: VerneedNum);
5297
5298 Expected<std::vector<VerNeed>> V =
5299 this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
5300 if (!V) {
5301 this->reportUniqueWarning(V.takeError());
5302 return;
5303 }
5304
5305 for (const VerNeed &VN : *V) {
5306 OS << format(Fmt: " 0x%04x: Version: %u File: %s Cnt: %u\n", Vals: VN.Offset,
5307 Vals: VN.Version, Vals: VN.File.data(), Vals: VN.Cnt);
5308 for (const VernAux &Aux : VN.AuxV)
5309 OS << format(Fmt: " 0x%04x: Name: %s Flags: %s Version: %u\n", Vals: Aux.Offset,
5310 Vals: Aux.Name.data(), Vals: versionFlagToString(Flags: Aux.Flags).c_str(),
5311 Vals: Aux.Other);
5312 }
5313 OS << '\n';
5314}
5315
5316template <class ELFT>
5317void GNUELFDumper<ELFT>::printHashHistogramStats(size_t NBucket,
5318 size_t MaxChain,
5319 size_t TotalSyms,
5320 ArrayRef<size_t> Count,
5321 bool IsGnu) const {
5322 size_t CumulativeNonZero = 0;
5323 OS << "Histogram for" << (IsGnu ? " `.gnu.hash'" : "")
5324 << " bucket list length (total of " << NBucket << " buckets)\n"
5325 << " Length Number % of total Coverage\n";
5326 for (size_t I = 0; I < MaxChain; ++I) {
5327 CumulativeNonZero += Count[I] * I;
5328 OS << format(Fmt: "%7lu %-10lu (%5.1f%%) %5.1f%%\n", Vals: I, Vals: Count[I],
5329 Vals: (Count[I] * 100.0) / NBucket,
5330 Vals: (CumulativeNonZero * 100.0) / TotalSyms);
5331 }
5332}
5333
5334template <class ELFT> void GNUELFDumper<ELFT>::printCGProfile() {
5335 OS << "GNU output style is not supported for --cg-profile\n";
5336}
5337
5338template <class ELFT>
5339SmallVector<FunctionCallGraphInfo, 16>
5340ELFDumper<ELFT>::processCallGraphSection(const Elf_Shdr *CGSection) {
5341 SmallVector<FunctionCallGraphInfo, 16> FuncCGInfos;
5342 ArrayRef<uint8_t> Contents = cantFail(Obj.getSectionContents(*CGSection));
5343 DataExtractor Data(Contents, Obj.isLE());
5344 DataExtractor::Cursor C(0);
5345 uint64_t UnknownCount = 0;
5346 while (C && C.tell() < CGSection->sh_size) {
5347 uint8_t FormatVersionNumber = Data.getU8(C);
5348 assert(C && "always expect the one byte read to succeed when C.tell() < "
5349 "CGSection->sh_size is true.");
5350 if (FormatVersionNumber != 0) {
5351 reportWarning(Err: createError(Err: "unknown format version value [" +
5352 std::to_string(val: FormatVersionNumber) +
5353 "] in SHT_LLVM_CALL_GRAPH type section"),
5354 Input: FileName);
5355 return {};
5356 }
5357
5358 uint8_t FlagsVal = Data.getU8(C);
5359 if (!C) {
5360 reportWarning(
5361 Err: createError(Err: "failed while reading call graph info's Flags: " +
5362 toString(E: C.takeError())),
5363 Input: FileName);
5364 return {};
5365 }
5366 callgraph::Flags CGFlags = static_cast<callgraph::Flags>(FlagsVal);
5367 constexpr callgraph::Flags ValidFlags = callgraph::IsIndirectTarget |
5368 callgraph::HasDirectCallees |
5369 callgraph::HasIndirectCallees;
5370 constexpr uint8_t ValidMask = static_cast<uint8_t>(ValidFlags);
5371 if ((FlagsVal & ~ValidMask) != 0) {
5372 reportWarning(Err: createError(Err: "unsupported Flags value [" +
5373 std::to_string(val: FlagsVal) + "] "),
5374 Input: FileName);
5375 return {};
5376 }
5377
5378 uint64_t FuncAddrOffset = C.tell();
5379 uint64_t FuncAddr =
5380 static_cast<uint64_t>(Data.getUnsigned(C, Size: sizeof(typename ELFT::uint)));
5381 if (!C) {
5382 reportWarning(
5383 Err: createError(
5384 Err: "failed while reading call graph info function entry PC: " +
5385 toString(E: C.takeError())),
5386 Input: FileName);
5387 return {};
5388 }
5389
5390 bool IsETREL = this->Obj.getHeader().e_type == ELF::ET_REL;
5391 // Create a new entry for this function.
5392 FunctionCallGraphInfo CGInfo;
5393 CGInfo.FunctionAddress = IsETREL ? FuncAddrOffset : FuncAddr;
5394 CGInfo.FormatVersionNumber = FormatVersionNumber;
5395 bool IsIndirectTarget =
5396 (CGFlags & callgraph::IsIndirectTarget) != callgraph::None;
5397 CGInfo.IsIndirectTarget = IsIndirectTarget;
5398 uint64_t TypeID = Data.getU64(C);
5399 if (!C) {
5400 reportWarning(Err: createError(Err: "failed while reading function type ID: " +
5401 toString(E: C.takeError())),
5402 Input: FileName);
5403 return {};
5404 }
5405 CGInfo.FunctionTypeID = TypeID;
5406 if (IsIndirectTarget && TypeID == 0)
5407 ++UnknownCount;
5408
5409 if (CGFlags & callgraph::HasDirectCallees) {
5410 // Read number of direct call sites for this function.
5411 uint64_t NumDirectCallees = Data.getULEB128(C);
5412 if (!C) {
5413 reportWarning(
5414 Err: createError(Err: "failed while reading number of direct callees: " +
5415 toString(E: C.takeError())),
5416 Input: FileName);
5417 return {};
5418 }
5419 // Read unique direct callees and populate FuncCGInfos.
5420 for (uint64_t I = 0; I < NumDirectCallees; ++I) {
5421 uint64_t CalleeOffset = C.tell();
5422 uint64_t Callee = static_cast<uint64_t>(
5423 Data.getUnsigned(C, Size: sizeof(typename ELFT::uint)));
5424 if (!C) {
5425 reportWarning(Err: createError(Err: "failed while reading direct callee: " +
5426 toString(E: C.takeError())),
5427 Input: FileName);
5428 return {};
5429 }
5430 CGInfo.DirectCallees.insert(V: (IsETREL ? CalleeOffset : Callee));
5431 }
5432 }
5433
5434 if (CGFlags & callgraph::HasIndirectCallees) {
5435 uint64_t NumIndirectTargetTypeIDs = Data.getULEB128(C);
5436 if (!C) {
5437 reportWarning(
5438 Err: createError(
5439 Err: "failed while reading number of indirect target type IDs: " +
5440 toString(E: C.takeError())),
5441 Input: FileName);
5442 return {};
5443 }
5444 // Read unique indirect target type IDs and populate FuncCGInfos.
5445 for (uint64_t I = 0; I < NumIndirectTargetTypeIDs; ++I) {
5446 uint64_t TargetType = Data.getU64(C);
5447 if (!C) {
5448 reportWarning(
5449 Err: createError(Err: "failed while reading indirect target type ID: " +
5450 toString(E: C.takeError())),
5451 Input: FileName);
5452 return {};
5453 }
5454 CGInfo.IndirectTypeIDs.insert(V: TargetType);
5455 }
5456 }
5457 FuncCGInfos.push_back(Elt: CGInfo);
5458 }
5459
5460 if (UnknownCount)
5461 reportUniqueWarning(
5462 "SHT_LLVM_CALL_GRAPH type section has unknown type ID for " +
5463 Twine(UnknownCount) + " indirect targets");
5464 return FuncCGInfos;
5465}
5466
5467template <class ELFT>
5468void GNUELFDumper<ELFT>::printBBAddrMaps(bool /*PrettyPGOAnalysis*/) {
5469 OS << "GNU output style is not supported for --bb-addr-map\n";
5470}
5471
5472static Expected<std::vector<uint64_t>> toULEB128Array(ArrayRef<uint8_t> Data) {
5473 std::vector<uint64_t> Ret;
5474 const uint8_t *Cur = Data.begin();
5475 const uint8_t *End = Data.end();
5476 while (Cur != End) {
5477 unsigned Size;
5478 const char *Err = nullptr;
5479 Ret.push_back(x: decodeULEB128(p: Cur, n: &Size, end: End, error: &Err));
5480 if (Err)
5481 return createError(Err);
5482 Cur += Size;
5483 }
5484 return Ret;
5485}
5486
5487template <class ELFT>
5488static Expected<std::vector<uint64_t>>
5489decodeAddrsigSection(const ELFFile<ELFT> &Obj, const typename ELFT::Shdr &Sec) {
5490 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Sec);
5491 if (!ContentsOrErr)
5492 return ContentsOrErr.takeError();
5493
5494 if (Expected<std::vector<uint64_t>> SymsOrErr =
5495 toULEB128Array(Data: *ContentsOrErr))
5496 return *SymsOrErr;
5497 else
5498 return createError("unable to decode " + describe(Obj, Sec) + ": " +
5499 toString(E: SymsOrErr.takeError()));
5500}
5501
5502template <class ELFT> void GNUELFDumper<ELFT>::printAddrsig() {
5503 if (!this->DotAddrsigSec)
5504 return;
5505
5506 Expected<std::vector<uint64_t>> SymsOrErr =
5507 decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
5508 if (!SymsOrErr) {
5509 this->reportUniqueWarning(SymsOrErr.takeError());
5510 return;
5511 }
5512
5513 StringRef Name = this->getPrintableSectionName(*this->DotAddrsigSec);
5514 OS << "\nAddress-significant symbols section '" << Name << "'"
5515 << " contains " << SymsOrErr->size() << " entries:\n";
5516 OS << " Num: Name\n";
5517
5518 Field Fields[2] = {0, 8};
5519 size_t SymIndex = 0;
5520 for (uint64_t Sym : *SymsOrErr) {
5521 Fields[0].Str = to_string(Value: format_decimal(N: ++SymIndex, Width: 6)) + ":";
5522 Fields[1].Str = this->getStaticSymbolName(Sym);
5523 for (const Field &Entry : Fields)
5524 printField(F: Entry);
5525 OS << "\n";
5526 }
5527}
5528
5529template <class ELFT>
5530static bool printAArch64PAuthABICoreInfo(raw_ostream &OS, uint32_t DataSize,
5531 ArrayRef<uint8_t> Desc) {
5532 OS << " AArch64 PAuth ABI core info: ";
5533 // DataSize - size without padding, Desc.size() - size with padding
5534 if (DataSize != 16) {
5535 OS << format(Fmt: "<corrupted size: expected 16, got %d>", Vals: DataSize);
5536 return false;
5537 }
5538
5539 uint64_t Platform =
5540 support::endian::read64<ELFT::Endianness>(Desc.data() + 0);
5541 uint64_t Version = support::endian::read64<ELFT::Endianness>(Desc.data() + 8);
5542
5543 const char *PlatformDesc = [Platform]() {
5544 switch (Platform) {
5545 case AARCH64_PAUTH_PLATFORM_INVALID:
5546 return "invalid";
5547 case AARCH64_PAUTH_PLATFORM_BAREMETAL:
5548 return "baremetal";
5549 case AARCH64_PAUTH_PLATFORM_LLVM_LINUX:
5550 return "llvm_linux";
5551 default:
5552 return "unknown";
5553 }
5554 }();
5555
5556 std::string VersionDesc = [Platform, Version]() -> std::string {
5557 if (Platform != AARCH64_PAUTH_PLATFORM_LLVM_LINUX)
5558 return "";
5559 if (Version >= (1 << (AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST + 1)))
5560 return "unknown";
5561
5562 std::array<StringRef, AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST + 1>
5563 Flags;
5564 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS] = "Intrinsics";
5565 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS] = "Calls";
5566 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS] = "Returns";
5567 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS] = "AuthTraps";
5568 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR] =
5569 "VTPtrAddressDiscrimination";
5570 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR] =
5571 "VTPtrTypeDiscrimination";
5572 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI] = "InitFini";
5573 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC] =
5574 "InitFiniAddressDiscrimination";
5575 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT] = "ELFGOT";
5576 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS] = "IndirectGotos";
5577 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR] =
5578 "TypeInfoVTPtrDiscrimination";
5579 Flags[AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR] =
5580 "FPtrTypeDiscrimination";
5581
5582 static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR ==
5583 AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST,
5584 "Update when new enum items are defined");
5585
5586 std::string Desc;
5587 for (uint32_t I = 0, End = Flags.size(); I < End; ++I) {
5588 if (!(Version & (1ULL << I)))
5589 Desc += '!';
5590 Desc +=
5591 Twine("PointerAuth" + Flags[I] + (I == End - 1 ? "" : ", ")).str();
5592 }
5593 return Desc;
5594 }();
5595
5596 OS << format(Fmt: "platform 0x%" PRIx64 " (%s), version 0x%" PRIx64, Vals: Platform,
5597 Vals: PlatformDesc, Vals: Version);
5598 if (!VersionDesc.empty())
5599 OS << format(Fmt: " (%s)", Vals: VersionDesc.c_str());
5600
5601 return true;
5602}
5603
5604template <typename ELFT>
5605static std::string getGNUProperty(uint32_t Type, uint32_t DataSize,
5606 ArrayRef<uint8_t> Data,
5607 typename ELFT::Half EMachine) {
5608 std::string str;
5609 raw_string_ostream OS(str);
5610 uint32_t PrData;
5611 auto DumpBit = [&](uint32_t Flag, StringRef Name) {
5612 if (PrData & Flag) {
5613 PrData &= ~Flag;
5614 OS << Name;
5615 if (PrData)
5616 OS << ", ";
5617 }
5618 };
5619
5620 switch (Type) {
5621 default:
5622 OS << format(Fmt: "<application-specific type 0x%x>", Vals: Type);
5623 return str;
5624 case GNU_PROPERTY_STACK_SIZE: {
5625 OS << "stack size: ";
5626 if (DataSize == sizeof(typename ELFT::uint))
5627 OS << formatv(Fmt: "{0:x}",
5628 Vals: (uint64_t)(*(const typename ELFT::Addr *)Data.data()));
5629 else
5630 OS << format(Fmt: "<corrupt length: 0x%x>", Vals: DataSize);
5631 return str;
5632 }
5633 case GNU_PROPERTY_NO_COPY_ON_PROTECTED:
5634 OS << "no copy on protected";
5635 if (DataSize)
5636 OS << format(Fmt: " <corrupt length: 0x%x>", Vals: DataSize);
5637 return str;
5638 case GNU_PROPERTY_AARCH64_FEATURE_1_AND:
5639 case GNU_PROPERTY_X86_FEATURE_1_AND:
5640 static_assert(GNU_PROPERTY_AARCH64_FEATURE_1_AND ==
5641 GNU_PROPERTY_RISCV_FEATURE_1_AND,
5642 "GNU_PROPERTY_RISCV_FEATURE_1_AND should equal "
5643 "GNU_PROPERTY_AARCH64_FEATURE_1_AND, otherwise "
5644 "GNU_PROPERTY_RISCV_FEATURE_1_AND would be skipped!");
5645
5646 if (EMachine == EM_AARCH64 && Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) {
5647 OS << "aarch64 feature: ";
5648 } else if (EMachine == EM_RISCV &&
5649 Type == GNU_PROPERTY_RISCV_FEATURE_1_AND) {
5650 OS << "RISC-V feature: ";
5651 } else if ((EMachine == EM_386 || EMachine == EM_X86_64) &&
5652 Type == GNU_PROPERTY_X86_FEATURE_1_AND) {
5653 OS << "x86 feature: ";
5654 } else {
5655 OS << format(Fmt: "<application-specific type 0x%x>", Vals: Type);
5656 return str;
5657 }
5658
5659 if (DataSize != 4) {
5660 OS << format(Fmt: "<corrupt length: 0x%x>", Vals: DataSize);
5661 return str;
5662 }
5663 PrData = endian::read32<ELFT::Endianness>(Data.data());
5664 if (PrData == 0) {
5665 OS << "<None>";
5666 return str;
5667 }
5668
5669 if (EMachine == EM_AARCH64) {
5670 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI, "BTI");
5671 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC, "PAC");
5672 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_GCS, "GCS");
5673 } else if (EMachine == EM_RISCV) {
5674 DumpBit(GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_UNLABELED,
5675 "ZICFILP-unlabeled");
5676 DumpBit(GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS, "ZICFISS");
5677 DumpBit(GNU_PROPERTY_RISCV_FEATURE_1_CFI_LP_FUNC_SIG, "ZICFILP-func-sig");
5678 } else {
5679 DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT, "IBT");
5680 DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK, "SHSTK");
5681 }
5682 if (PrData)
5683 OS << format(Fmt: "<unknown flags: 0x%x>", Vals: PrData);
5684 return str;
5685 case GNU_PROPERTY_AARCH64_FEATURE_PAUTH:
5686 printAArch64PAuthABICoreInfo<ELFT>(OS, DataSize, Data);
5687 return str;
5688 case GNU_PROPERTY_X86_FEATURE_2_NEEDED:
5689 case GNU_PROPERTY_X86_FEATURE_2_USED:
5690 OS << "x86 feature "
5691 << (Type == GNU_PROPERTY_X86_FEATURE_2_NEEDED ? "needed: " : "used: ");
5692 if (DataSize != 4) {
5693 OS << format(Fmt: "<corrupt length: 0x%x>", Vals: DataSize);
5694 return str;
5695 }
5696 PrData = endian::read32<ELFT::Endianness>(Data.data());
5697 if (PrData == 0) {
5698 OS << "<None>";
5699 return str;
5700 }
5701 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86, "x86");
5702 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87, "x87");
5703 DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX, "MMX");
5704 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM, "XMM");
5705 DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM, "YMM");
5706 DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM, "ZMM");
5707 DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR, "FXSR");
5708 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE, "XSAVE");
5709 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT, "XSAVEOPT");
5710 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC, "XSAVEC");
5711 if (PrData)
5712 OS << format(Fmt: "<unknown flags: 0x%x>", Vals: PrData);
5713 return str;
5714 case GNU_PROPERTY_X86_ISA_1_NEEDED:
5715 case GNU_PROPERTY_X86_ISA_1_USED:
5716 OS << "x86 ISA "
5717 << (Type == GNU_PROPERTY_X86_ISA_1_NEEDED ? "needed: " : "used: ");
5718 if (DataSize != 4) {
5719 OS << format(Fmt: "<corrupt length: 0x%x>", Vals: DataSize);
5720 return str;
5721 }
5722 PrData = endian::read32<ELFT::Endianness>(Data.data());
5723 if (PrData == 0) {
5724 OS << "<None>";
5725 return str;
5726 }
5727 DumpBit(GNU_PROPERTY_X86_ISA_1_BASELINE, "x86-64-baseline");
5728 DumpBit(GNU_PROPERTY_X86_ISA_1_V2, "x86-64-v2");
5729 DumpBit(GNU_PROPERTY_X86_ISA_1_V3, "x86-64-v3");
5730 DumpBit(GNU_PROPERTY_X86_ISA_1_V4, "x86-64-v4");
5731 if (PrData)
5732 OS << format(Fmt: "<unknown flags: 0x%x>", Vals: PrData);
5733 return str;
5734 }
5735}
5736
5737template <typename ELFT>
5738static SmallVector<std::string, 4>
5739getGNUPropertyList(ArrayRef<uint8_t> Arr, typename ELFT::Half EMachine) {
5740 using Elf_Word = typename ELFT::Word;
5741
5742 SmallVector<std::string, 4> Properties;
5743 while (Arr.size() >= 8) {
5744 uint32_t Type = *reinterpret_cast<const Elf_Word *>(Arr.data());
5745 uint32_t DataSize = *reinterpret_cast<const Elf_Word *>(Arr.data() + 4);
5746 Arr = Arr.drop_front(N: 8);
5747
5748 // Take padding size into account if present.
5749 uint64_t PaddedSize = alignTo(Value: DataSize, Align: sizeof(typename ELFT::uint));
5750 std::string str;
5751 raw_string_ostream OS(str);
5752 if (Arr.size() < PaddedSize) {
5753 OS << format(Fmt: "<corrupt type (0x%x) datasz: 0x%x>", Vals: Type, Vals: DataSize);
5754 Properties.push_back(Elt: str);
5755 break;
5756 }
5757 Properties.push_back(getGNUProperty<ELFT>(
5758 Type, DataSize, Arr.take_front(N: PaddedSize), EMachine));
5759 Arr = Arr.drop_front(N: PaddedSize);
5760 }
5761
5762 if (!Arr.empty())
5763 Properties.push_back(Elt: "<corrupted GNU_PROPERTY_TYPE_0>");
5764
5765 return Properties;
5766}
5767
5768struct GNUAbiTag {
5769 std::string OSName;
5770 std::string ABI;
5771 bool IsValid;
5772};
5773
5774template <typename ELFT> static GNUAbiTag getGNUAbiTag(ArrayRef<uint8_t> Desc) {
5775 typedef typename ELFT::Word Elf_Word;
5776
5777 ArrayRef<Elf_Word> Words(reinterpret_cast<const Elf_Word *>(Desc.begin()),
5778 reinterpret_cast<const Elf_Word *>(Desc.end()));
5779
5780 if (Words.size() < 4)
5781 return {.OSName: "", .ABI: "", /*IsValid=*/false};
5782
5783 static const char *OSNames[] = {
5784 "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable",
5785 };
5786 StringRef OSName = "Unknown";
5787 if (Words[0] < std::size(OSNames))
5788 OSName = OSNames[Words[0]];
5789 uint32_t Major = Words[1], Minor = Words[2], Patch = Words[3];
5790 std::string str;
5791 raw_string_ostream ABI(str);
5792 ABI << Major << "." << Minor << "." << Patch;
5793 return {.OSName: std::string(OSName), .ABI: str, /*IsValid=*/true};
5794}
5795
5796static std::string getGNUBuildId(ArrayRef<uint8_t> Desc) {
5797 std::string str;
5798 raw_string_ostream OS(str);
5799 for (uint8_t B : Desc)
5800 OS << format_hex_no_prefix(N: B, Width: 2);
5801 return str;
5802}
5803
5804static StringRef getDescAsStringRef(ArrayRef<uint8_t> Desc) {
5805 return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
5806}
5807
5808template <typename ELFT>
5809static bool printGNUNote(raw_ostream &OS, uint32_t NoteType,
5810 ArrayRef<uint8_t> Desc, typename ELFT::Half EMachine) {
5811 // Return true if we were able to pretty-print the note, false otherwise.
5812 switch (NoteType) {
5813 default:
5814 return false;
5815 case ELF::NT_GNU_ABI_TAG: {
5816 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
5817 if (!AbiTag.IsValid)
5818 OS << " <corrupt GNU_ABI_TAG>";
5819 else
5820 OS << " OS: " << AbiTag.OSName << ", ABI: " << AbiTag.ABI;
5821 break;
5822 }
5823 case ELF::NT_GNU_BUILD_ID: {
5824 OS << " Build ID: " << getGNUBuildId(Desc);
5825 break;
5826 }
5827 case ELF::NT_GNU_GOLD_VERSION:
5828 OS << " Version: " << getDescAsStringRef(Desc);
5829 break;
5830 case ELF::NT_GNU_PROPERTY_TYPE_0:
5831 OS << " Properties:";
5832 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc, EMachine))
5833 OS << " " << Property << "\n";
5834 break;
5835 }
5836 OS << '\n';
5837 return true;
5838}
5839
5840using AndroidNoteProperties = std::vector<std::pair<StringRef, std::string>>;
5841static AndroidNoteProperties getAndroidNoteProperties(uint32_t NoteType,
5842 ArrayRef<uint8_t> Desc) {
5843 AndroidNoteProperties Props;
5844 switch (NoteType) {
5845 case ELF::NT_ANDROID_TYPE_MEMTAG:
5846 if (Desc.empty()) {
5847 Props.emplace_back(args: "Invalid .note.android.memtag", args: "");
5848 return Props;
5849 }
5850
5851 switch (Desc[0] & NT_MEMTAG_LEVEL_MASK) {
5852 case NT_MEMTAG_LEVEL_NONE:
5853 Props.emplace_back(args: "Tagging Mode", args: "NONE");
5854 break;
5855 case NT_MEMTAG_LEVEL_ASYNC:
5856 Props.emplace_back(args: "Tagging Mode", args: "ASYNC");
5857 break;
5858 case NT_MEMTAG_LEVEL_SYNC:
5859 Props.emplace_back(args: "Tagging Mode", args: "SYNC");
5860 break;
5861 default:
5862 Props.emplace_back(
5863 args: "Tagging Mode",
5864 args: ("Unknown (" + Twine::utohexstr(Val: Desc[0] & NT_MEMTAG_LEVEL_MASK) + ")")
5865 .str());
5866 break;
5867 }
5868 Props.emplace_back(args: "Heap",
5869 args: (Desc[0] & NT_MEMTAG_HEAP) ? "Enabled" : "Disabled");
5870 Props.emplace_back(args: "Stack",
5871 args: (Desc[0] & NT_MEMTAG_STACK) ? "Enabled" : "Disabled");
5872 break;
5873 default:
5874 return Props;
5875 }
5876 return Props;
5877}
5878
5879static bool printAndroidNote(raw_ostream &OS, uint32_t NoteType,
5880 ArrayRef<uint8_t> Desc) {
5881 // Return true if we were able to pretty-print the note, false otherwise.
5882 AndroidNoteProperties Props = getAndroidNoteProperties(NoteType, Desc);
5883 if (Props.empty())
5884 return false;
5885 for (const auto &KV : Props)
5886 OS << " " << KV.first << ": " << KV.second << '\n';
5887 return true;
5888}
5889
5890template <class ELFT>
5891void GNUELFDumper<ELFT>::printMemtag(
5892 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
5893 const ArrayRef<uint8_t> AndroidNoteDesc,
5894 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) {
5895 OS << "Memtag Dynamic Entries:\n";
5896 if (DynamicEntries.empty())
5897 OS << " < none found >\n";
5898 for (const auto &DynamicEntryKV : DynamicEntries)
5899 OS << " " << DynamicEntryKV.first << ": " << DynamicEntryKV.second
5900 << "\n";
5901
5902 if (!AndroidNoteDesc.empty()) {
5903 OS << "Memtag Android Note:\n";
5904 printAndroidNote(OS, NoteType: ELF::NT_ANDROID_TYPE_MEMTAG, Desc: AndroidNoteDesc);
5905 }
5906
5907 if (Descriptors.empty())
5908 return;
5909
5910 OS << "Memtag Global Descriptors:\n";
5911 for (const auto &[Addr, BytesToTag] : Descriptors) {
5912 OS << " 0x" << utohexstr(X: Addr, /*LowerCase=*/true) << ": 0x"
5913 << utohexstr(X: BytesToTag, /*LowerCase=*/true) << "\n";
5914 }
5915}
5916
5917template <typename ELFT>
5918static bool printLLVMOMPOFFLOADNote(raw_ostream &OS, uint32_t NoteType,
5919 ArrayRef<uint8_t> Desc) {
5920 switch (NoteType) {
5921 default:
5922 return false;
5923 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
5924 OS << " Version: " << getDescAsStringRef(Desc);
5925 break;
5926 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
5927 OS << " Producer: " << getDescAsStringRef(Desc);
5928 break;
5929 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
5930 OS << " Producer version: " << getDescAsStringRef(Desc);
5931 break;
5932 }
5933 OS << '\n';
5934 return true;
5935}
5936
5937constexpr EnumStringDef<unsigned> FreeBSDFeatureCtlFlagsDefs[] = {
5938 {.Names: {"ASLR_DISABLE"}, .Value: NT_FREEBSD_FCTL_ASLR_DISABLE},
5939 {.Names: {"PROTMAX_DISABLE"}, .Value: NT_FREEBSD_FCTL_PROTMAX_DISABLE},
5940 {.Names: {"STKGAP_DISABLE"}, .Value: NT_FREEBSD_FCTL_STKGAP_DISABLE},
5941 {.Names: {"WXNEEDED"}, .Value: NT_FREEBSD_FCTL_WXNEEDED},
5942 {.Names: {"LA48"}, .Value: NT_FREEBSD_FCTL_LA48},
5943 {.Names: {"ASG_DISABLE"}, .Value: NT_FREEBSD_FCTL_ASG_DISABLE},
5944};
5945constexpr auto FreeBSDFeatureCtlFlags =
5946 BUILD_ENUM_STRINGS(FreeBSDFeatureCtlFlagsDefs);
5947
5948struct FreeBSDNote {
5949 std::string Type;
5950 std::string Value;
5951};
5952
5953template <typename ELFT>
5954static std::optional<FreeBSDNote>
5955getFreeBSDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc, bool IsCore) {
5956 if (IsCore)
5957 return std::nullopt; // No pretty-printing yet.
5958 switch (NoteType) {
5959 case ELF::NT_FREEBSD_ABI_TAG:
5960 if (Desc.size() != 4)
5961 return std::nullopt;
5962 return FreeBSDNote{"ABI tag",
5963 utostr(endian::read32<ELFT::Endianness>(Desc.data()))};
5964 case ELF::NT_FREEBSD_ARCH_TAG:
5965 return FreeBSDNote{.Type: "Arch tag", .Value: toStringRef(Input: Desc).str()};
5966 case ELF::NT_FREEBSD_FEATURE_CTL: {
5967 if (Desc.size() != 4)
5968 return std::nullopt;
5969 unsigned Value = endian::read32<ELFT::Endianness>(Desc.data());
5970 std::string FlagsStr;
5971 raw_string_ostream OS(FlagsStr);
5972 printFlags(Value, Flags: EnumStrings(FreeBSDFeatureCtlFlags), OS);
5973 if (FlagsStr.empty())
5974 OS << "0x" << utohexstr(X: Value, /*LowerCase=*/true);
5975 else
5976 OS << "(0x" << utohexstr(X: Value, /*LowerCase=*/true) << ")";
5977 return FreeBSDNote{.Type: "Feature flags", .Value: FlagsStr};
5978 }
5979 default:
5980 return std::nullopt;
5981 }
5982}
5983
5984struct AMDNote {
5985 std::string Type;
5986 std::string Value;
5987};
5988
5989template <typename ELFT>
5990static AMDNote getAMDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
5991 switch (NoteType) {
5992 default:
5993 return {.Type: "", .Value: ""};
5994 case ELF::NT_AMD_HSA_CODE_OBJECT_VERSION: {
5995 struct CodeObjectVersion {
5996 support::aligned_ulittle32_t MajorVersion;
5997 support::aligned_ulittle32_t MinorVersion;
5998 };
5999 if (Desc.size() != sizeof(CodeObjectVersion))
6000 return {.Type: "AMD HSA Code Object Version",
6001 .Value: "Invalid AMD HSA Code Object Version"};
6002 std::string VersionString;
6003 raw_string_ostream StrOS(VersionString);
6004 auto Version = reinterpret_cast<const CodeObjectVersion *>(Desc.data());
6005 StrOS << "[Major: " << Version->MajorVersion
6006 << ", Minor: " << Version->MinorVersion << "]";
6007 return {.Type: "AMD HSA Code Object Version", .Value: VersionString};
6008 }
6009 case ELF::NT_AMD_HSA_HSAIL: {
6010 struct HSAILProperties {
6011 support::aligned_ulittle32_t HSAILMajorVersion;
6012 support::aligned_ulittle32_t HSAILMinorVersion;
6013 uint8_t Profile;
6014 uint8_t MachineModel;
6015 uint8_t DefaultFloatRound;
6016 };
6017 if (Desc.size() != sizeof(HSAILProperties))
6018 return {.Type: "AMD HSA HSAIL Properties", .Value: "Invalid AMD HSA HSAIL Properties"};
6019 auto Properties = reinterpret_cast<const HSAILProperties *>(Desc.data());
6020 std::string HSAILPropetiesString;
6021 raw_string_ostream StrOS(HSAILPropetiesString);
6022 StrOS << "[HSAIL Major: " << Properties->HSAILMajorVersion
6023 << ", HSAIL Minor: " << Properties->HSAILMinorVersion
6024 << ", Profile: " << uint32_t(Properties->Profile)
6025 << ", Machine Model: " << uint32_t(Properties->MachineModel)
6026 << ", Default Float Round: "
6027 << uint32_t(Properties->DefaultFloatRound) << "]";
6028 return {.Type: "AMD HSA HSAIL Properties", .Value: HSAILPropetiesString};
6029 }
6030 case ELF::NT_AMD_HSA_ISA_VERSION: {
6031 struct IsaVersion {
6032 support::aligned_ulittle16_t VendorNameSize;
6033 support::aligned_ulittle16_t ArchitectureNameSize;
6034 support::aligned_ulittle32_t Major;
6035 support::aligned_ulittle32_t Minor;
6036 support::aligned_ulittle32_t Stepping;
6037 };
6038 if (Desc.size() < sizeof(IsaVersion))
6039 return {.Type: "AMD HSA ISA Version", .Value: "Invalid AMD HSA ISA Version"};
6040 auto Isa = reinterpret_cast<const IsaVersion *>(Desc.data());
6041 if (Desc.size() < sizeof(IsaVersion) +
6042 Isa->VendorNameSize + Isa->ArchitectureNameSize ||
6043 Isa->VendorNameSize == 0 || Isa->ArchitectureNameSize == 0)
6044 return {.Type: "AMD HSA ISA Version", .Value: "Invalid AMD HSA ISA Version"};
6045 std::string IsaString;
6046 raw_string_ostream StrOS(IsaString);
6047 StrOS << "[Vendor: "
6048 << StringRef((const char*)Desc.data() + sizeof(IsaVersion), Isa->VendorNameSize - 1)
6049 << ", Architecture: "
6050 << StringRef((const char*)Desc.data() + sizeof(IsaVersion) + Isa->VendorNameSize,
6051 Isa->ArchitectureNameSize - 1)
6052 << ", Major: " << Isa->Major << ", Minor: " << Isa->Minor
6053 << ", Stepping: " << Isa->Stepping << "]";
6054 return {.Type: "AMD HSA ISA Version", .Value: IsaString};
6055 }
6056 case ELF::NT_AMD_HSA_METADATA: {
6057 if (Desc.size() == 0)
6058 return {.Type: "AMD HSA Metadata", .Value: ""};
6059 return {
6060 .Type: "AMD HSA Metadata",
6061 .Value: std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size() - 1)};
6062 }
6063 case ELF::NT_AMD_HSA_ISA_NAME: {
6064 if (Desc.size() == 0)
6065 return {.Type: "AMD HSA ISA Name", .Value: ""};
6066 return {
6067 .Type: "AMD HSA ISA Name",
6068 .Value: std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())};
6069 }
6070 case ELF::NT_AMD_PAL_METADATA: {
6071 struct PALMetadata {
6072 support::aligned_ulittle32_t Key;
6073 support::aligned_ulittle32_t Value;
6074 };
6075 if (Desc.size() % sizeof(PALMetadata) != 0)
6076 return {.Type: "AMD PAL Metadata", .Value: "Invalid AMD PAL Metadata"};
6077 auto Isa = reinterpret_cast<const PALMetadata *>(Desc.data());
6078 std::string MetadataString;
6079 raw_string_ostream StrOS(MetadataString);
6080 for (size_t I = 0, E = Desc.size() / sizeof(PALMetadata); I < E; ++I) {
6081 StrOS << "[" << Isa[I].Key << ": " << Isa[I].Value << "]";
6082 }
6083 return {.Type: "AMD PAL Metadata", .Value: MetadataString};
6084 }
6085 }
6086}
6087
6088struct AMDGPUNote {
6089 std::string Type;
6090 std::string Value;
6091};
6092
6093template <typename ELFT>
6094static AMDGPUNote getAMDGPUNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) {
6095 switch (NoteType) {
6096 default:
6097 return {.Type: "", .Value: ""};
6098 case ELF::NT_AMDGPU_METADATA: {
6099 StringRef MsgPackString =
6100 StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
6101 msgpack::Document MsgPackDoc;
6102 if (!MsgPackDoc.readFromBlob(Blob: MsgPackString, /*Multi=*/false))
6103 return {.Type: "", .Value: ""};
6104
6105 std::string MetadataString;
6106
6107 // FIXME: Metadata Verifier only works with AMDHSA.
6108 // This is an ugly workaround to avoid the verifier for other MD
6109 // formats (e.g. amdpal)
6110 if (MsgPackString.contains(Other: "amdhsa.")) {
6111 AMDGPU::HSAMD::V3::MetadataVerifier Verifier(true);
6112 if (!Verifier.verify(HSAMetadataRoot&: MsgPackDoc.getRoot()))
6113 MetadataString = "Invalid AMDGPU Metadata\n";
6114 }
6115
6116 raw_string_ostream StrOS(MetadataString);
6117 if (MsgPackDoc.getRoot().isScalar()) {
6118 // TODO: passing a scalar root to toYAML() asserts:
6119 // (PolymorphicTraits<T>::getKind(Val) != NodeKind::Scalar &&
6120 // "plain scalar documents are not supported")
6121 // To avoid this crash we print the raw data instead.
6122 return {.Type: "", .Value: ""};
6123 }
6124 MsgPackDoc.toYAML(OS&: StrOS);
6125 return {.Type: "AMDGPU Metadata", .Value: MetadataString};
6126 }
6127 }
6128}
6129
6130struct CoreFileMapping {
6131 uint64_t Start, End, Offset;
6132 StringRef Filename;
6133};
6134
6135struct CoreNote {
6136 uint64_t PageSize;
6137 std::vector<CoreFileMapping> Mappings;
6138};
6139
6140static Expected<CoreNote> readCoreNote(DataExtractor Desc,
6141 unsigned AddressSize) {
6142 // Expected format of the NT_FILE note description:
6143 // 1. # of file mappings (call it N)
6144 // 2. Page size
6145 // 3. N (start, end, offset) triples
6146 // 4. N packed filenames (null delimited)
6147 // Each field is an Elf_Addr, except for filenames which are char* strings.
6148
6149 CoreNote Ret;
6150
6151 if (!Desc.isValidOffsetForDataOfSize(offset: 2, length: AddressSize))
6152 return createError(Err: "the note of size 0x" + Twine::utohexstr(Val: Desc.size()) +
6153 " is too short, expected at least 0x" +
6154 Twine::utohexstr(Val: AddressSize * 2));
6155 if (Desc.getData().back() != 0)
6156 return createError(Err: "the note is not NUL terminated");
6157
6158 uint64_t DescOffset = 0;
6159 uint64_t FileCount = Desc.getUnsigned(offset_ptr: &DescOffset, byte_size: AddressSize);
6160 Ret.PageSize = Desc.getUnsigned(offset_ptr: &DescOffset, byte_size: AddressSize);
6161
6162 if (!Desc.isValidOffsetForDataOfSize(offset: 3 * FileCount * AddressSize,
6163 length: AddressSize))
6164 return createError(Err: "unable to read file mappings (found " +
6165 Twine(FileCount) + "): the note of size 0x" +
6166 Twine::utohexstr(Val: Desc.size()) + " is too short");
6167
6168 uint64_t FilenamesOffset = 0;
6169 DataExtractor Filenames(
6170 Desc.getData().drop_front(N: DescOffset + 3 * FileCount * AddressSize),
6171 Desc.isLittleEndian());
6172
6173 Ret.Mappings.resize(new_size: FileCount);
6174 size_t I = 0;
6175 for (CoreFileMapping &Mapping : Ret.Mappings) {
6176 ++I;
6177 if (!Filenames.isValidOffsetForDataOfSize(offset: FilenamesOffset, length: 1))
6178 return createError(
6179 Err: "unable to read the file name for the mapping with index " +
6180 Twine(I) + ": the note of size 0x" + Twine::utohexstr(Val: Desc.size()) +
6181 " is truncated");
6182 Mapping.Start = Desc.getUnsigned(offset_ptr: &DescOffset, byte_size: AddressSize);
6183 Mapping.End = Desc.getUnsigned(offset_ptr: &DescOffset, byte_size: AddressSize);
6184 Mapping.Offset = Desc.getUnsigned(offset_ptr: &DescOffset, byte_size: AddressSize);
6185 Mapping.Filename = Filenames.getCStrRef(OffsetPtr: &FilenamesOffset);
6186 }
6187
6188 return Ret;
6189}
6190
6191template <typename ELFT>
6192static void printCoreNote(raw_ostream &OS, const CoreNote &Note) {
6193 // Length of "0x<address>" string.
6194 const int FieldWidth = ELFT::Is64Bits ? 18 : 10;
6195
6196 OS << " Page size: " << format_decimal(N: Note.PageSize, Width: 0) << '\n';
6197 OS << " " << right_justify(Str: "Start", Width: FieldWidth) << " "
6198 << right_justify(Str: "End", Width: FieldWidth) << " "
6199 << right_justify(Str: "Page Offset", Width: FieldWidth) << '\n';
6200 for (const CoreFileMapping &Mapping : Note.Mappings) {
6201 OS << " " << format_hex(N: Mapping.Start, Width: FieldWidth) << " "
6202 << format_hex(N: Mapping.End, Width: FieldWidth) << " "
6203 << format_hex(N: Mapping.Offset, Width: FieldWidth) << "\n "
6204 << Mapping.Filename << '\n';
6205 }
6206}
6207
6208const NoteType GenericNoteTypes[] = {
6209 {.ID: ELF::NT_VERSION, .Name: "NT_VERSION (version)"},
6210 {.ID: ELF::NT_ARCH, .Name: "NT_ARCH (architecture)"},
6211 {.ID: ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN, .Name: "OPEN"},
6212 {.ID: ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC, .Name: "func"},
6213};
6214
6215const NoteType GNUNoteTypes[] = {
6216 {.ID: ELF::NT_GNU_ABI_TAG, .Name: "NT_GNU_ABI_TAG (ABI version tag)"},
6217 {.ID: ELF::NT_GNU_HWCAP, .Name: "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"},
6218 {.ID: ELF::NT_GNU_BUILD_ID, .Name: "NT_GNU_BUILD_ID (unique build ID bitstring)"},
6219 {.ID: ELF::NT_GNU_GOLD_VERSION, .Name: "NT_GNU_GOLD_VERSION (gold version)"},
6220 {.ID: ELF::NT_GNU_PROPERTY_TYPE_0, .Name: "NT_GNU_PROPERTY_TYPE_0 (property note)"},
6221};
6222
6223const NoteType FreeBSDCoreNoteTypes[] = {
6224 {.ID: ELF::NT_FREEBSD_THRMISC, .Name: "NT_THRMISC (thrmisc structure)"},
6225 {.ID: ELF::NT_FREEBSD_PROCSTAT_PROC, .Name: "NT_PROCSTAT_PROC (proc data)"},
6226 {.ID: ELF::NT_FREEBSD_PROCSTAT_FILES, .Name: "NT_PROCSTAT_FILES (files data)"},
6227 {.ID: ELF::NT_FREEBSD_PROCSTAT_VMMAP, .Name: "NT_PROCSTAT_VMMAP (vmmap data)"},
6228 {.ID: ELF::NT_FREEBSD_PROCSTAT_GROUPS, .Name: "NT_PROCSTAT_GROUPS (groups data)"},
6229 {.ID: ELF::NT_FREEBSD_PROCSTAT_UMASK, .Name: "NT_PROCSTAT_UMASK (umask data)"},
6230 {.ID: ELF::NT_FREEBSD_PROCSTAT_RLIMIT, .Name: "NT_PROCSTAT_RLIMIT (rlimit data)"},
6231 {.ID: ELF::NT_FREEBSD_PROCSTAT_OSREL, .Name: "NT_PROCSTAT_OSREL (osreldate data)"},
6232 {.ID: ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS,
6233 .Name: "NT_PROCSTAT_PSSTRINGS (ps_strings data)"},
6234 {.ID: ELF::NT_FREEBSD_PROCSTAT_AUXV, .Name: "NT_PROCSTAT_AUXV (auxv data)"},
6235};
6236
6237const NoteType FreeBSDNoteTypes[] = {
6238 {.ID: ELF::NT_FREEBSD_ABI_TAG, .Name: "NT_FREEBSD_ABI_TAG (ABI version tag)"},
6239 {.ID: ELF::NT_FREEBSD_NOINIT_TAG, .Name: "NT_FREEBSD_NOINIT_TAG (no .init tag)"},
6240 {.ID: ELF::NT_FREEBSD_ARCH_TAG, .Name: "NT_FREEBSD_ARCH_TAG (architecture tag)"},
6241 {.ID: ELF::NT_FREEBSD_FEATURE_CTL,
6242 .Name: "NT_FREEBSD_FEATURE_CTL (FreeBSD feature control)"},
6243};
6244
6245const NoteType NetBSDCoreNoteTypes[] = {
6246 {.ID: ELF::NT_NETBSDCORE_PROCINFO,
6247 .Name: "NT_NETBSDCORE_PROCINFO (procinfo structure)"},
6248 {.ID: ELF::NT_NETBSDCORE_AUXV, .Name: "NT_NETBSDCORE_AUXV (ELF auxiliary vector data)"},
6249 {.ID: ELF::NT_NETBSDCORE_LWPSTATUS, .Name: "PT_LWPSTATUS (ptrace_lwpstatus structure)"},
6250};
6251
6252const NoteType OpenBSDCoreNoteTypes[] = {
6253 {.ID: ELF::NT_OPENBSD_PROCINFO, .Name: "NT_OPENBSD_PROCINFO (procinfo structure)"},
6254 {.ID: ELF::NT_OPENBSD_AUXV, .Name: "NT_OPENBSD_AUXV (ELF auxiliary vector data)"},
6255 {.ID: ELF::NT_OPENBSD_REGS, .Name: "NT_OPENBSD_REGS (regular registers)"},
6256 {.ID: ELF::NT_OPENBSD_FPREGS, .Name: "NT_OPENBSD_FPREGS (floating point registers)"},
6257 {.ID: ELF::NT_OPENBSD_WCOOKIE, .Name: "NT_OPENBSD_WCOOKIE (window cookie)"},
6258 {.ID: ELF::NT_OPENBSD_PACMASK,
6259 .Name: "NT_OPENBSD_PACMASK (AArch64 Pointer Authentication Code mask)"},
6260};
6261
6262const NoteType AMDNoteTypes[] = {
6263 {.ID: ELF::NT_AMD_HSA_CODE_OBJECT_VERSION,
6264 .Name: "NT_AMD_HSA_CODE_OBJECT_VERSION (AMD HSA Code Object Version)"},
6265 {.ID: ELF::NT_AMD_HSA_HSAIL, .Name: "NT_AMD_HSA_HSAIL (AMD HSA HSAIL Properties)"},
6266 {.ID: ELF::NT_AMD_HSA_ISA_VERSION, .Name: "NT_AMD_HSA_ISA_VERSION (AMD HSA ISA Version)"},
6267 {.ID: ELF::NT_AMD_HSA_METADATA, .Name: "NT_AMD_HSA_METADATA (AMD HSA Metadata)"},
6268 {.ID: ELF::NT_AMD_HSA_ISA_NAME, .Name: "NT_AMD_HSA_ISA_NAME (AMD HSA ISA Name)"},
6269 {.ID: ELF::NT_AMD_PAL_METADATA, .Name: "NT_AMD_PAL_METADATA (AMD PAL Metadata)"},
6270};
6271
6272const NoteType AMDGPUNoteTypes[] = {
6273 {.ID: ELF::NT_AMDGPU_METADATA, .Name: "NT_AMDGPU_METADATA (AMDGPU Metadata)"},
6274};
6275
6276const NoteType LLVMOMPOFFLOADNoteTypes[] = {
6277 {.ID: ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION,
6278 .Name: "NT_LLVM_OPENMP_OFFLOAD_VERSION (image format version)"},
6279 {.ID: ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER,
6280 .Name: "NT_LLVM_OPENMP_OFFLOAD_PRODUCER (producing toolchain)"},
6281 {.ID: ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION,
6282 .Name: "NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION (producing toolchain version)"},
6283};
6284
6285const NoteType AndroidNoteTypes[] = {
6286 {.ID: ELF::NT_ANDROID_TYPE_IDENT, .Name: "NT_ANDROID_TYPE_IDENT"},
6287 {.ID: ELF::NT_ANDROID_TYPE_KUSER, .Name: "NT_ANDROID_TYPE_KUSER"},
6288 {.ID: ELF::NT_ANDROID_TYPE_MEMTAG,
6289 .Name: "NT_ANDROID_TYPE_MEMTAG (Android memory tagging information)"},
6290};
6291
6292const NoteType CoreNoteTypes[] = {
6293 {.ID: ELF::NT_PRSTATUS, .Name: "NT_PRSTATUS (prstatus structure)"},
6294 {.ID: ELF::NT_FPREGSET, .Name: "NT_FPREGSET (floating point registers)"},
6295 {.ID: ELF::NT_PRPSINFO, .Name: "NT_PRPSINFO (prpsinfo structure)"},
6296 {.ID: ELF::NT_TASKSTRUCT, .Name: "NT_TASKSTRUCT (task structure)"},
6297 {.ID: ELF::NT_AUXV, .Name: "NT_AUXV (auxiliary vector)"},
6298 {.ID: ELF::NT_PSTATUS, .Name: "NT_PSTATUS (pstatus structure)"},
6299 {.ID: ELF::NT_FPREGS, .Name: "NT_FPREGS (floating point registers)"},
6300 {.ID: ELF::NT_PSINFO, .Name: "NT_PSINFO (psinfo structure)"},
6301 {.ID: ELF::NT_LWPSTATUS, .Name: "NT_LWPSTATUS (lwpstatus_t structure)"},
6302 {.ID: ELF::NT_LWPSINFO, .Name: "NT_LWPSINFO (lwpsinfo_t structure)"},
6303 {.ID: ELF::NT_WIN32PSTATUS, .Name: "NT_WIN32PSTATUS (win32_pstatus structure)"},
6304
6305 {.ID: ELF::NT_PPC_VMX, .Name: "NT_PPC_VMX (ppc Altivec registers)"},
6306 {.ID: ELF::NT_PPC_VSX, .Name: "NT_PPC_VSX (ppc VSX registers)"},
6307 {.ID: ELF::NT_PPC_TAR, .Name: "NT_PPC_TAR (ppc TAR register)"},
6308 {.ID: ELF::NT_PPC_PPR, .Name: "NT_PPC_PPR (ppc PPR register)"},
6309 {.ID: ELF::NT_PPC_DSCR, .Name: "NT_PPC_DSCR (ppc DSCR register)"},
6310 {.ID: ELF::NT_PPC_EBB, .Name: "NT_PPC_EBB (ppc EBB registers)"},
6311 {.ID: ELF::NT_PPC_PMU, .Name: "NT_PPC_PMU (ppc PMU registers)"},
6312 {.ID: ELF::NT_PPC_TM_CGPR, .Name: "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"},
6313 {.ID: ELF::NT_PPC_TM_CFPR,
6314 .Name: "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"},
6315 {.ID: ELF::NT_PPC_TM_CVMX,
6316 .Name: "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"},
6317 {.ID: ELF::NT_PPC_TM_CVSX, .Name: "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"},
6318 {.ID: ELF::NT_PPC_TM_SPR, .Name: "NT_PPC_TM_SPR (ppc TM special purpose registers)"},
6319 {.ID: ELF::NT_PPC_TM_CTAR, .Name: "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"},
6320 {.ID: ELF::NT_PPC_TM_CPPR, .Name: "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"},
6321 {.ID: ELF::NT_PPC_TM_CDSCR, .Name: "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"},
6322
6323 {.ID: ELF::NT_386_TLS, .Name: "NT_386_TLS (x86 TLS information)"},
6324 {.ID: ELF::NT_386_IOPERM, .Name: "NT_386_IOPERM (x86 I/O permissions)"},
6325 {.ID: ELF::NT_X86_XSTATE, .Name: "NT_X86_XSTATE (x86 XSAVE extended state)"},
6326
6327 {.ID: ELF::NT_S390_HIGH_GPRS, .Name: "NT_S390_HIGH_GPRS (s390 upper register halves)"},
6328 {.ID: ELF::NT_S390_TIMER, .Name: "NT_S390_TIMER (s390 timer register)"},
6329 {.ID: ELF::NT_S390_TODCMP, .Name: "NT_S390_TODCMP (s390 TOD comparator register)"},
6330 {.ID: ELF::NT_S390_TODPREG, .Name: "NT_S390_TODPREG (s390 TOD programmable register)"},
6331 {.ID: ELF::NT_S390_CTRS, .Name: "NT_S390_CTRS (s390 control registers)"},
6332 {.ID: ELF::NT_S390_PREFIX, .Name: "NT_S390_PREFIX (s390 prefix register)"},
6333 {.ID: ELF::NT_S390_LAST_BREAK,
6334 .Name: "NT_S390_LAST_BREAK (s390 last breaking event address)"},
6335 {.ID: ELF::NT_S390_SYSTEM_CALL,
6336 .Name: "NT_S390_SYSTEM_CALL (s390 system call restart data)"},
6337 {.ID: ELF::NT_S390_TDB, .Name: "NT_S390_TDB (s390 transaction diagnostic block)"},
6338 {.ID: ELF::NT_S390_VXRS_LOW,
6339 .Name: "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"},
6340 {.ID: ELF::NT_S390_VXRS_HIGH, .Name: "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"},
6341 {.ID: ELF::NT_S390_GS_CB, .Name: "NT_S390_GS_CB (s390 guarded-storage registers)"},
6342 {.ID: ELF::NT_S390_GS_BC,
6343 .Name: "NT_S390_GS_BC (s390 guarded-storage broadcast control)"},
6344
6345 {.ID: ELF::NT_ARM_VFP, .Name: "NT_ARM_VFP (arm VFP registers)"},
6346 {.ID: ELF::NT_ARM_TLS, .Name: "NT_ARM_TLS (AArch TLS registers)"},
6347 {.ID: ELF::NT_ARM_HW_BREAK,
6348 .Name: "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"},
6349 {.ID: ELF::NT_ARM_HW_WATCH,
6350 .Name: "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"},
6351 {.ID: ELF::NT_ARM_SVE, .Name: "NT_ARM_SVE (AArch64 SVE registers)"},
6352 {.ID: ELF::NT_ARM_PAC_MASK,
6353 .Name: "NT_ARM_PAC_MASK (AArch64 Pointer Authentication code masks)"},
6354 {.ID: ELF::NT_ARM_TAGGED_ADDR_CTRL,
6355 .Name: "NT_ARM_TAGGED_ADDR_CTRL (AArch64 Tagged Address Control)"},
6356 {.ID: ELF::NT_ARM_SSVE, .Name: "NT_ARM_SSVE (AArch64 Streaming SVE registers)"},
6357 {.ID: ELF::NT_ARM_ZA, .Name: "NT_ARM_ZA (AArch64 SME ZA registers)"},
6358 {.ID: ELF::NT_ARM_ZT, .Name: "NT_ARM_ZT (AArch64 SME ZT registers)"},
6359 {.ID: ELF::NT_ARM_FPMR, .Name: "NT_ARM_FPMR (AArch64 Floating Point Mode Register)"},
6360 {.ID: ELF::NT_ARM_POE,
6361 .Name: "NT_ARM_POE (AArch64 Permission Overlay Extension Registers)"},
6362 {.ID: ELF::NT_ARM_GCS, .Name: "NT_ARM_GCS (AArch64 Guarded Control Stack state)"},
6363
6364 {.ID: ELF::NT_FILE, .Name: "NT_FILE (mapped files)"},
6365 {.ID: ELF::NT_PRXFPREG, .Name: "NT_PRXFPREG (user_xfpregs structure)"},
6366 {.ID: ELF::NT_SIGINFO, .Name: "NT_SIGINFO (siginfo_t data)"},
6367};
6368
6369template <class ELFT>
6370StringRef getNoteTypeName(const typename ELFT::Note &Note, unsigned ELFType) {
6371 uint32_t Type = Note.getType();
6372 auto FindNote = [&](ArrayRef<NoteType> V) -> StringRef {
6373 for (const NoteType &N : V)
6374 if (N.ID == Type)
6375 return N.Name;
6376 return "";
6377 };
6378
6379 StringRef Name = Note.getName();
6380 if (Name == "GNU")
6381 return FindNote(GNUNoteTypes);
6382 if (Name == "FreeBSD") {
6383 if (ELFType == ELF::ET_CORE) {
6384 // FreeBSD also places the generic core notes in the FreeBSD namespace.
6385 StringRef Result = FindNote(FreeBSDCoreNoteTypes);
6386 if (!Result.empty())
6387 return Result;
6388 return FindNote(CoreNoteTypes);
6389 } else {
6390 return FindNote(FreeBSDNoteTypes);
6391 }
6392 }
6393 if (ELFType == ELF::ET_CORE && Name.starts_with(Prefix: "NetBSD-CORE")) {
6394 StringRef Result = FindNote(NetBSDCoreNoteTypes);
6395 if (!Result.empty())
6396 return Result;
6397 return FindNote(CoreNoteTypes);
6398 }
6399 if (ELFType == ELF::ET_CORE && Name.starts_with(Prefix: "OpenBSD")) {
6400 // OpenBSD also places the generic core notes in the OpenBSD namespace.
6401 StringRef Result = FindNote(OpenBSDCoreNoteTypes);
6402 if (!Result.empty())
6403 return Result;
6404 return FindNote(CoreNoteTypes);
6405 }
6406 if (Name == "AMD")
6407 return FindNote(AMDNoteTypes);
6408 if (Name == "AMDGPU")
6409 return FindNote(AMDGPUNoteTypes);
6410 if (Name == "LLVMOMPOFFLOAD")
6411 return FindNote(LLVMOMPOFFLOADNoteTypes);
6412 if (Name == "Android")
6413 return FindNote(AndroidNoteTypes);
6414
6415 if (ELFType == ELF::ET_CORE)
6416 return FindNote(CoreNoteTypes);
6417 return FindNote(GenericNoteTypes);
6418}
6419
6420template <class ELFT>
6421static void processNotesHelper(
6422 const ELFDumper<ELFT> &Dumper,
6423 llvm::function_ref<void(std::optional<StringRef>, typename ELFT::Off,
6424 typename ELFT::Addr, size_t)>
6425 StartNotesFn,
6426 llvm::function_ref<Error(const typename ELFT::Note &, bool)> ProcessNoteFn,
6427 llvm::function_ref<void()> FinishNotesFn) {
6428 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile();
6429 bool IsCoreFile = Obj.getHeader().e_type == ELF::ET_CORE;
6430
6431 ArrayRef<typename ELFT::Shdr> Sections = cantFail(Obj.sections());
6432 if (!IsCoreFile && !Sections.empty()) {
6433 for (const typename ELFT::Shdr &S : Sections) {
6434 if (S.sh_type != SHT_NOTE)
6435 continue;
6436 StartNotesFn(expectedToOptional(Obj.getSectionName(S)), S.sh_offset,
6437 S.sh_size, S.sh_addralign);
6438 Error Err = Error::success();
6439 size_t I = 0;
6440 for (const typename ELFT::Note Note : Obj.notes(S, Err)) {
6441 if (Error E = ProcessNoteFn(Note, IsCoreFile))
6442 Dumper.reportUniqueWarning(
6443 "unable to read note with index " + Twine(I) + " from the " +
6444 describe(Obj, S) + ": " + toString(E: std::move(E)));
6445 ++I;
6446 }
6447 if (Err)
6448 Dumper.reportUniqueWarning("unable to read notes from the " +
6449 describe(Obj, S) + ": " +
6450 toString(E: std::move(Err)));
6451 FinishNotesFn();
6452 }
6453 return;
6454 }
6455
6456 Expected<ArrayRef<typename ELFT::Phdr>> PhdrsOrErr = Obj.program_headers();
6457 if (!PhdrsOrErr) {
6458 Dumper.reportUniqueWarning(
6459 "unable to read program headers to locate the PT_NOTE segment: " +
6460 toString(PhdrsOrErr.takeError()));
6461 return;
6462 }
6463
6464 for (size_t I = 0, E = (*PhdrsOrErr).size(); I != E; ++I) {
6465 const typename ELFT::Phdr &P = (*PhdrsOrErr)[I];
6466 if (P.p_type != PT_NOTE)
6467 continue;
6468 StartNotesFn(/*SecName=*/std::nullopt, P.p_offset, P.p_filesz, P.p_align);
6469 Error Err = Error::success();
6470 size_t Index = 0;
6471 for (const typename ELFT::Note Note : Obj.notes(P, Err)) {
6472 if (Error E = ProcessNoteFn(Note, IsCoreFile))
6473 Dumper.reportUniqueWarning("unable to read note with index " +
6474 Twine(Index) +
6475 " from the PT_NOTE segment with index " +
6476 Twine(I) + ": " + toString(E: std::move(E)));
6477 ++Index;
6478 }
6479 if (Err)
6480 Dumper.reportUniqueWarning(
6481 "unable to read notes from the PT_NOTE segment with index " +
6482 Twine(I) + ": " + toString(E: std::move(Err)));
6483 FinishNotesFn();
6484 }
6485}
6486
6487template <class ELFT> void GNUELFDumper<ELFT>::printNotes() {
6488 size_t Align = 0;
6489 bool IsFirstHeader = true;
6490 auto PrintHeader = [&](std::optional<StringRef> SecName,
6491 const typename ELFT::Off Offset,
6492 const typename ELFT::Addr Size, size_t Al) {
6493 Align = std::max<size_t>(a: Al, b: 4);
6494 // Print a newline between notes sections to match GNU readelf.
6495 if (!IsFirstHeader) {
6496 OS << '\n';
6497 } else {
6498 IsFirstHeader = false;
6499 }
6500
6501 OS << "Displaying notes found ";
6502
6503 if (SecName)
6504 OS << "in: " << *SecName << "\n";
6505 else
6506 OS << "at file offset " << format_hex(Offset, 10) << " with length "
6507 << format_hex(Size, 10) << ":\n";
6508
6509 OS << " Owner Data size \tDescription\n";
6510 };
6511
6512 auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
6513 StringRef Name = Note.getName();
6514 ArrayRef<uint8_t> Descriptor = Note.getDesc(Align);
6515 Elf_Word Type = Note.getType();
6516
6517 // Print the note owner/type.
6518 OS << " " << left_justify(Str: Name, Width: 20) << ' '
6519 << format_hex(N: Descriptor.size(), Width: 10) << '\t';
6520
6521 StringRef NoteType =
6522 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
6523 if (!NoteType.empty())
6524 OS << NoteType << '\n';
6525 else
6526 OS << "Unknown note type: (" << format_hex(Type, 10) << ")\n";
6527
6528 const typename ELFT::Half EMachine = this->Obj.getHeader().e_machine;
6529
6530 // Print the description, or fallback to printing raw bytes for unknown
6531 // owners/if we fail to pretty-print the contents.
6532 if (Name == "GNU") {
6533 if (printGNUNote<ELFT>(OS, Type, Descriptor, EMachine))
6534 return Error::success();
6535 } else if (Name == "FreeBSD") {
6536 if (std::optional<FreeBSDNote> N =
6537 getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
6538 OS << " " << N->Type << ": " << N->Value << '\n';
6539 return Error::success();
6540 }
6541 } else if (Name == "AMD") {
6542 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
6543 if (!N.Type.empty()) {
6544 OS << " " << N.Type << ":\n " << N.Value << '\n';
6545 return Error::success();
6546 }
6547 } else if (Name == "AMDGPU") {
6548 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
6549 if (!N.Type.empty()) {
6550 OS << " " << N.Type << ":\n " << N.Value << '\n';
6551 return Error::success();
6552 }
6553 } else if (Name == "LLVMOMPOFFLOAD") {
6554 if (printLLVMOMPOFFLOADNote<ELFT>(OS, Type, Descriptor))
6555 return Error::success();
6556 } else if (Name == "CORE") {
6557 if (Type == ELF::NT_FILE) {
6558 DataExtractor DescExtractor(Descriptor, ELFT::Endianness ==
6559 llvm::endianness::little);
6560 if (Expected<CoreNote> NoteOrErr =
6561 readCoreNote(Desc: DescExtractor, AddressSize: sizeof(Elf_Addr))) {
6562 printCoreNote<ELFT>(OS, *NoteOrErr);
6563 return Error::success();
6564 } else {
6565 return NoteOrErr.takeError();
6566 }
6567 }
6568 } else if (Name == "Android") {
6569 if (printAndroidNote(OS, Type, Descriptor))
6570 return Error::success();
6571 }
6572 if (!Descriptor.empty()) {
6573 OS << " description data:";
6574 for (uint8_t B : Descriptor)
6575 OS << " " << format(Fmt: "%02x", Vals: B);
6576 OS << '\n';
6577 }
6578 return Error::success();
6579 };
6580
6581 processNotesHelper(*this, /*StartNotesFn=*/PrintHeader,
6582 /*ProcessNoteFn=*/ProcessNote, /*FinishNotesFn=*/[]() {});
6583}
6584
6585template <class ELFT>
6586ArrayRef<uint8_t>
6587ELFDumper<ELFT>::getMemtagGlobalsSectionContents(uint64_t ExpectedAddr) {
6588 for (const typename ELFT::Shdr &Sec : cantFail(Obj.sections())) {
6589 if (Sec.sh_type != SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC)
6590 continue;
6591 if (Sec.sh_addr != ExpectedAddr) {
6592 reportUniqueWarning(
6593 "SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section was unexpectedly at 0x" +
6594 Twine::utohexstr(Val: Sec.sh_addr) +
6595 ", when DT_AARCH64_MEMTAG_GLOBALS says it should be at 0x" +
6596 Twine::utohexstr(Val: ExpectedAddr));
6597 return ArrayRef<uint8_t>();
6598 }
6599 Expected<ArrayRef<uint8_t>> Contents = Obj.getSectionContents(Sec);
6600 if (auto E = Contents.takeError()) {
6601 reportUniqueWarning(
6602 "couldn't get SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section contents: " +
6603 toString(E: std::move(E)));
6604 return ArrayRef<uint8_t>();
6605 }
6606 return Contents.get();
6607 }
6608 return ArrayRef<uint8_t>();
6609}
6610
6611// Reserve the lower three bits of the first byte of the step distance when
6612// encoding the memtag descriptors. Found to be the best overall size tradeoff
6613// when compiling Android T with full MTE globals enabled.
6614constexpr uint64_t MemtagStepVarintReservedBits = 3;
6615constexpr uint64_t MemtagGranuleSize = 16;
6616
6617template <typename ELFT> void ELFDumper<ELFT>::printMemtag() {
6618 if (Obj.getHeader().e_machine != EM_AARCH64) return;
6619 std::vector<std::pair<std::string, std::string>> DynamicEntries;
6620 uint64_t MemtagGlobalsSz = 0;
6621 uint64_t MemtagGlobals = 0;
6622 for (const typename ELFT::Dyn &Entry : dynamic_table()) {
6623 uintX_t Tag = Entry.getTag();
6624 switch (Tag) {
6625 case DT_AARCH64_MEMTAG_GLOBALSSZ:
6626 MemtagGlobalsSz = Entry.getVal();
6627 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6628 getDynamicEntry(Type: Tag, Value: Entry.getVal()));
6629 break;
6630 case DT_AARCH64_MEMTAG_GLOBALS:
6631 MemtagGlobals = Entry.getVal();
6632 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6633 getDynamicEntry(Type: Tag, Value: Entry.getVal()));
6634 break;
6635 case DT_AARCH64_MEMTAG_MODE:
6636 case DT_AARCH64_MEMTAG_HEAP:
6637 case DT_AARCH64_MEMTAG_STACK:
6638 DynamicEntries.emplace_back(Obj.getDynamicTagAsString(Tag),
6639 getDynamicEntry(Type: Tag, Value: Entry.getVal()));
6640 break;
6641 }
6642 }
6643
6644 ArrayRef<uint8_t> AndroidNoteDesc;
6645 auto FindAndroidNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
6646 if (Note.getName() == "Android" &&
6647 Note.getType() == ELF::NT_ANDROID_TYPE_MEMTAG)
6648 AndroidNoteDesc = Note.getDesc(4);
6649 return Error::success();
6650 };
6651
6652 processNotesHelper(
6653 *this,
6654 /*StartNotesFn=*/
6655 [](std::optional<StringRef>, const typename ELFT::Off,
6656 const typename ELFT::Addr, size_t) {},
6657 /*ProcessNoteFn=*/FindAndroidNote, /*FinishNotesFn=*/[]() {});
6658
6659 ArrayRef<uint8_t> Contents = getMemtagGlobalsSectionContents(ExpectedAddr: MemtagGlobals);
6660 if (Contents.size() != MemtagGlobalsSz) {
6661 reportUniqueWarning(
6662 "mismatch between DT_AARCH64_MEMTAG_GLOBALSSZ (0x" +
6663 Twine::utohexstr(Val: MemtagGlobalsSz) +
6664 ") and SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC section size (0x" +
6665 Twine::utohexstr(Val: Contents.size()) + ")");
6666 Contents = ArrayRef<uint8_t>();
6667 }
6668
6669 std::vector<std::pair<uint64_t, uint64_t>> GlobalDescriptors;
6670 uint64_t Address = 0;
6671 // See the AArch64 MemtagABI document for a description of encoding scheme:
6672 // https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#83encoding-of-sht_aarch64_memtag_globals_dynamic
6673 for (size_t I = 0; I < Contents.size();) {
6674 const char *Error = nullptr;
6675 unsigned DecodedBytes = 0;
6676 uint64_t Value = decodeULEB128(p: Contents.data() + I, n: &DecodedBytes,
6677 end: Contents.end(), error: &Error);
6678 I += DecodedBytes;
6679 if (Error) {
6680 reportUniqueWarning(
6681 "error decoding distance uleb, " + Twine(DecodedBytes) +
6682 " byte(s) into SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC: " + Twine(Error));
6683 GlobalDescriptors.clear();
6684 break;
6685 }
6686 uint64_t Distance = Value >> MemtagStepVarintReservedBits;
6687 uint64_t GranulesToTag = Value & ((1 << MemtagStepVarintReservedBits) - 1);
6688 if (GranulesToTag == 0) {
6689 GranulesToTag = decodeULEB128(p: Contents.data() + I, n: &DecodedBytes,
6690 end: Contents.end(), error: &Error) +
6691 1;
6692 I += DecodedBytes;
6693 if (Error) {
6694 reportUniqueWarning(
6695 "error decoding size-only uleb, " + Twine(DecodedBytes) +
6696 " byte(s) into SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC: " + Twine(Error));
6697 GlobalDescriptors.clear();
6698 break;
6699 }
6700 }
6701 Address += Distance * MemtagGranuleSize;
6702 GlobalDescriptors.emplace_back(args&: Address, args: GranulesToTag * MemtagGranuleSize);
6703 Address += GranulesToTag * MemtagGranuleSize;
6704 }
6705
6706 printMemtag(DynamicEntries, AndroidNoteDesc, GlobalDescriptors);
6707}
6708
6709template <typename ELFT>
6710void ELFDumper<ELFT>::printSFrameHeader(
6711 const SFrameParser<ELFT::Endianness> &Parser) {
6712 DictScope HeaderScope(W, "Header");
6713
6714 const sframe::Preamble<ELFT::Endianness> &Preamble = Parser.getPreamble();
6715 W.printHex("Magic", Preamble.Magic.value());
6716 W.printEnum("Version", Preamble.Version.value(), sframe::getVersions());
6717 W.printFlags("Flags", Preamble.Flags.value(), sframe::getFlags());
6718
6719 const sframe::Header<ELFT::Endianness> &Header = Parser.getHeader();
6720 W.printEnum("ABI", Header.ABIArch.value(), sframe::getABIs());
6721
6722 W.printNumber(("CFA fixed FP offset" +
6723 Twine(Parser.usesFixedFPOffset() ? "" : " (unused)"))
6724 .str(),
6725 Header.CFAFixedFPOffset.value());
6726
6727 W.printNumber(("CFA fixed RA offset" +
6728 Twine(Parser.usesFixedRAOffset() ? "" : " (unused)"))
6729 .str(),
6730 Header.CFAFixedRAOffset.value());
6731
6732 W.printNumber("Auxiliary header length", Header.AuxHdrLen.value());
6733 W.printNumber("Num FDEs", Header.NumFDEs.value());
6734 W.printNumber("Num FREs", Header.NumFREs.value());
6735 W.printNumber("FRE subsection length", Header.FRELen.value());
6736 W.printNumber("FDE subsection offset", Header.FDEOff.value());
6737 W.printNumber("FRE subsection offset", Header.FREOff.value());
6738
6739 if (Expected<ArrayRef<uint8_t>> Aux = Parser.getAuxHeader())
6740 W.printHexList("Auxiliary header", *Aux);
6741 else
6742 reportUniqueWarning(Aux.takeError());
6743}
6744
6745template <typename ELFT>
6746void ELFDumper<ELFT>::printSFrameFDEs(
6747 const SFrameParser<ELFT::Endianness> &Parser,
6748 ArrayRef<Relocation<ELFT>> Relocations, const Elf_Shdr *RelocSymTab) {
6749 typename SFrameParser<ELFT::Endianness>::FDERange FDEs;
6750 if (Error Err = Parser.fdes().moveInto(FDEs)) {
6751 reportUniqueWarning(std::move(Err));
6752 return;
6753 }
6754
6755 ListScope IndexScope(W, "Function Index");
6756 for (auto It = FDEs.begin(); It != FDEs.end(); ++It) {
6757 DictScope FDEScope(
6758 W,
6759 formatv("FuncDescEntry [{0}]", std::distance(FDEs.begin(), It)).str());
6760
6761 uint64_t FDEStartAddress =
6762 getAndPrintSFrameFDEStartAddress(Parser, FDE: It, Relocations, RelocSymTab);
6763 W.printHex("Size", It->Size);
6764 W.printHex("Start FRE Offset", It->StartFREOff);
6765 W.printNumber("Num FREs", It->NumFREs);
6766
6767 {
6768 DictScope InfoScope(W, "Info");
6769 W.printEnum("FRE Type", It->Info.getFREType(), sframe::getFRETypes());
6770 W.printEnum("FDE Type", It->Info.getFDEType(), sframe::getFDETypes());
6771 switch (Parser.getHeader().ABIArch) {
6772 case sframe::ABI::AArch64EndianBig:
6773 case sframe::ABI::AArch64EndianLittle:
6774 W.printEnum("PAuth Key",
6775 sframe::AArch64PAuthKey(It->Info.getPAuthKey()),
6776 sframe::getAArch64PAuthKeys());
6777 break;
6778 case sframe::ABI::AMD64EndianLittle:
6779 // unused
6780 break;
6781 }
6782
6783 W.printHex("Raw", It->Info.Info);
6784 }
6785
6786 W.printHex(
6787 ("Repetitive block size" +
6788 Twine(It->Info.getFDEType() == sframe::FDEType::PCMask ? ""
6789 : " (unused)"))
6790 .str(),
6791 It->RepSize);
6792
6793 W.printHex("Padding2", It->Padding2);
6794
6795 ListScope FREListScope(W, "FREs");
6796 Error Err = Error::success();
6797 for (const typename SFrameParser<ELFT::Endianness>::FrameRowEntry &FRE :
6798 Parser.fres(*It, Err)) {
6799 DictScope FREScope(W, "Frame Row Entry");
6800 W.printHex("Start Address",
6801 (It->Info.getFDEType() == sframe::FDEType::PCInc
6802 ? FDEStartAddress
6803 : 0) +
6804 FRE.StartAddress);
6805 W.printBoolean(Label: "Return Address Signed", Value: FRE.Info.isReturnAddressSigned());
6806 W.printEnum("Offset Size", FRE.Info.getOffsetSize(),
6807 sframe::getFREOffsets());
6808 W.printEnum("Base Register", FRE.Info.getBaseRegister(),
6809 sframe::getBaseRegisters());
6810 if (std::optional<int32_t> Off = Parser.getCFAOffset(FRE))
6811 W.printNumber("CFA Offset", *Off);
6812 if (std::optional<int32_t> Off = Parser.getRAOffset(FRE))
6813 W.printNumber("RA Offset", *Off);
6814 if (std::optional<int32_t> Off = Parser.getFPOffset(FRE))
6815 W.printNumber("FP Offset", *Off);
6816 if (ArrayRef<int32_t> Offs = Parser.getExtraOffsets(FRE); !Offs.empty())
6817 W.printList("Extra Offsets", Offs);
6818 }
6819 if (Err)
6820 reportUniqueWarning(std::move(Err));
6821 }
6822}
6823
6824template <typename ELFT>
6825uint64_t ELFDumper<ELFT>::getAndPrintSFrameFDEStartAddress(
6826 const SFrameParser<ELFT::Endianness> &Parser,
6827 const typename SFrameParser<ELFT::Endianness>::FDERange::iterator FDE,
6828 ArrayRef<Relocation<ELFT>> Relocations, const Elf_Shdr *RelocSymTab) {
6829 uint64_t Address = Parser.getAbsoluteStartAddress(FDE);
6830 uint64_t Offset = Parser.offsetOf(FDE);
6831
6832 auto Reloc = llvm::lower_bound(
6833 Relocations, Offset, [](auto R, uint64_t O) { return R.Offset < O; });
6834 if (Reloc == Relocations.end() || Reloc->Offset != Offset) {
6835 W.printHex("PC", Address);
6836 } else if (std::next(Reloc) != Relocations.end() &&
6837 std::next(Reloc)->Offset == Offset) {
6838 reportUniqueWarning(
6839 formatv(Fmt: "more than one relocation at offset {0:x+}", Vals&: Offset));
6840 W.printHex("PC", Address);
6841 } else if (Expected<RelSymbol<ELFT>> RelSym =
6842 getRelocationTarget(R: *Reloc, SymTab: RelocSymTab);
6843 !RelSym) {
6844 reportUniqueWarning(RelSym.takeError());
6845 W.printHex("PC", Address);
6846 } else {
6847 // Exactly one relocation at the given offset. Print it.
6848 DictScope PCScope(W, "PC");
6849 SmallString<32> RelocName;
6850 Obj.getRelocationTypeName(Reloc->Type, RelocName);
6851 W.printString("Relocation", RelocName);
6852 W.printString("Symbol Name", RelSym->Name);
6853 Address = FDE->StartAddress + Reloc->Addend.value_or(0);
6854 W.printHex("Start Address", Address);
6855 }
6856 return Address;
6857}
6858
6859template <typename ELFT>
6860void ELFDumper<ELFT>::printSectionsAsSFrame(ArrayRef<std::string> Sections) {
6861 constexpr endianness E = ELFT::Endianness;
6862
6863 for (object::SectionRef Section :
6864 getSectionRefsByNameOrIndex(Obj: ObjF, Sections)) {
6865 // Validity of sections names checked in getSectionRefsByNameOrIndex.
6866 StringRef SectionName = cantFail(ValOrErr: Section.getName());
6867
6868 DictScope SectionScope(W,
6869 formatv(Fmt: "SFrame section '{0}'", Vals&: SectionName).str());
6870
6871 StringRef SectionContent;
6872 if (Error Err = Section.getContents().moveInto(Value&: SectionContent)) {
6873 reportUniqueWarning(std::move(Err));
6874 continue;
6875 }
6876
6877 Expected<object::SFrameParser<E>> Parser = object::SFrameParser<E>::create(
6878 arrayRefFromStringRef(Input: SectionContent), Section.getAddress());
6879 if (!Parser) {
6880 reportUniqueWarning("invalid sframe section: " +
6881 toString(Parser.takeError()));
6882 continue;
6883 }
6884
6885 const Elf_Shdr *ELFSection = ObjF.getSection(Section.getRawDataRefImpl());
6886 MapVector<const Elf_Shdr *, const Elf_Shdr *> RelocationMap;
6887 if (Error Err = Obj.getSectionAndRelocations(
6888 [&](const Elf_Shdr &S) { return &S == ELFSection; })
6889 .moveInto(RelocationMap)) {
6890 reportUniqueWarning(std::move(Err));
6891 }
6892
6893 std::vector<Relocation<ELFT>> Relocations;
6894 const Elf_Shdr *RelocSymTab = nullptr;
6895 if (const Elf_Shdr *RelocSection = RelocationMap.lookup(ELFSection)) {
6896 forEachRelocationDo(Sec: *RelocSection,
6897 RelRelaFn: [&](const Relocation<ELFT> &R, unsigned Ndx,
6898 const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
6899 RelocSymTab = SymTab;
6900 Relocations.push_back(R);
6901 });
6902 llvm::stable_sort(Relocations, [](const auto &LHS, const auto &RHS) {
6903 return LHS.Offset < RHS.Offset;
6904 });
6905 }
6906
6907 printSFrameHeader(Parser: *Parser);
6908 printSFrameFDEs(Parser: *Parser, Relocations, RelocSymTab);
6909 }
6910}
6911
6912template <class ELFT> void GNUELFDumper<ELFT>::printELFLinkerOptions() {
6913 OS << "GNU output style is not supported for --elf-linker-options\n";
6914}
6915
6916template <class ELFT>
6917void ELFDumper<ELFT>::printDependentLibsHelper(
6918 function_ref<void(const Elf_Shdr &)> OnSectionStart,
6919 function_ref<void(StringRef, uint64_t)> OnLibEntry) {
6920 auto Warn = [this](unsigned SecNdx, StringRef Msg) {
6921 this->reportUniqueWarning("SHT_LLVM_DEPENDENT_LIBRARIES section at index " +
6922 Twine(SecNdx) + " is broken: " + Msg);
6923 };
6924
6925 unsigned I = -1;
6926 for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) {
6927 ++I;
6928 if (Shdr.sh_type != ELF::SHT_LLVM_DEPENDENT_LIBRARIES)
6929 continue;
6930
6931 OnSectionStart(Shdr);
6932
6933 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Shdr);
6934 if (!ContentsOrErr) {
6935 Warn(I, toString(E: ContentsOrErr.takeError()));
6936 continue;
6937 }
6938
6939 ArrayRef<uint8_t> Contents = *ContentsOrErr;
6940 if (!Contents.empty() && Contents.back() != 0) {
6941 Warn(I, "the content is not null-terminated");
6942 continue;
6943 }
6944
6945 for (const uint8_t *I = Contents.begin(), *E = Contents.end(); I < E;) {
6946 StringRef Lib((const char *)I);
6947 OnLibEntry(Lib, I - Contents.begin());
6948 I += Lib.size() + 1;
6949 }
6950 }
6951}
6952
6953template <class ELFT>
6954void ELFDumper<ELFT>::forEachRelocationDo(
6955 const Elf_Shdr &Sec,
6956 llvm::function_ref<void(const Relocation<ELFT> &, unsigned,
6957 const Elf_Shdr &, const Elf_Shdr *)>
6958 RelRelaFn) {
6959 auto Warn = [&](Error &&E,
6960 const Twine &Prefix = "unable to read relocations from") {
6961 this->reportUniqueWarning(Prefix + " " + describe(Sec) + ": " +
6962 toString(E: std::move(E)));
6963 };
6964
6965 // SHT_RELR/SHT_ANDROID_RELR/SHT_AARCH64_AUTH_RELR sections do not have an
6966 // associated symbol table. For them we should not treat the value of the
6967 // sh_link field as an index of a symbol table.
6968 const Elf_Shdr *SymTab;
6969 if (Sec.sh_type != ELF::SHT_RELR && Sec.sh_type != ELF::SHT_ANDROID_RELR &&
6970 !(Obj.getHeader().e_machine == EM_AARCH64 &&
6971 Sec.sh_type == ELF::SHT_AARCH64_AUTH_RELR)) {
6972 Expected<const Elf_Shdr *> SymTabOrErr = Obj.getSection(Sec.sh_link);
6973 if (!SymTabOrErr) {
6974 Warn(SymTabOrErr.takeError(), "unable to locate a symbol table for");
6975 return;
6976 }
6977 SymTab = *SymTabOrErr;
6978 }
6979
6980 unsigned RelNdx = 0;
6981 const bool IsMips64EL = this->Obj.isMips64EL();
6982 switch (Sec.sh_type) {
6983 case ELF::SHT_REL:
6984 if (Expected<Elf_Rel_Range> RangeOrErr = Obj.rels(Sec)) {
6985 for (const Elf_Rel &R : *RangeOrErr)
6986 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
6987 } else {
6988 Warn(RangeOrErr.takeError());
6989 }
6990 break;
6991 case ELF::SHT_RELA:
6992 if (Expected<Elf_Rela_Range> RangeOrErr = Obj.relas(Sec)) {
6993 for (const Elf_Rela &R : *RangeOrErr)
6994 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
6995 } else {
6996 Warn(RangeOrErr.takeError());
6997 }
6998 break;
6999 case ELF::SHT_AARCH64_AUTH_RELR:
7000 if (Obj.getHeader().e_machine != EM_AARCH64)
7001 break;
7002 [[fallthrough]];
7003 case ELF::SHT_RELR:
7004 case ELF::SHT_ANDROID_RELR: {
7005 Expected<Elf_Relr_Range> RangeOrErr = Obj.relrs(Sec);
7006 if (!RangeOrErr) {
7007 Warn(RangeOrErr.takeError());
7008 break;
7009 }
7010
7011 for (const Elf_Rel &R : Obj.decode_relrs(*RangeOrErr))
7012 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec,
7013 /*SymTab=*/nullptr);
7014 break;
7015 }
7016 case ELF::SHT_CREL: {
7017 if (auto RelsOrRelas = Obj.crels(Sec)) {
7018 for (const Elf_Rel &R : RelsOrRelas->first)
7019 RelRelaFn(Relocation<ELFT>(R, false), RelNdx++, Sec, SymTab);
7020 for (const Elf_Rela &R : RelsOrRelas->second)
7021 RelRelaFn(Relocation<ELFT>(R, false), RelNdx++, Sec, SymTab);
7022 } else {
7023 Warn(RelsOrRelas.takeError());
7024 }
7025 break;
7026 }
7027 case ELF::SHT_ANDROID_REL:
7028 case ELF::SHT_ANDROID_RELA:
7029 if (Expected<std::vector<Elf_Rela>> RelasOrErr = Obj.android_relas(Sec)) {
7030 for (const Elf_Rela &R : *RelasOrErr)
7031 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab);
7032 } else {
7033 Warn(RelasOrErr.takeError());
7034 }
7035 break;
7036 }
7037}
7038
7039template <class ELFT>
7040StringRef ELFDumper<ELFT>::getPrintableSectionName(const Elf_Shdr &Sec) const {
7041 StringRef Name = "<?>";
7042 if (Expected<StringRef> SecNameOrErr =
7043 Obj.getSectionName(Sec, this->WarningHandler))
7044 Name = *SecNameOrErr;
7045 else
7046 this->reportUniqueWarning("unable to get the name of " + describe(Sec) +
7047 ": " + toString(E: SecNameOrErr.takeError()));
7048 return Name;
7049}
7050
7051template <class ELFT> void GNUELFDumper<ELFT>::printDependentLibs() {
7052 bool SectionStarted = false;
7053 struct NameOffset {
7054 StringRef Name;
7055 uint64_t Offset;
7056 };
7057 std::vector<NameOffset> SecEntries;
7058 NameOffset Current;
7059 auto PrintSection = [&]() {
7060 OS << "Dependent libraries section " << Current.Name << " at offset "
7061 << format_hex(Current.Offset, 1) << " contains " << SecEntries.size()
7062 << " entries:\n";
7063 for (NameOffset Entry : SecEntries)
7064 OS << " [" << format("%6" PRIx64, Entry.Offset) << "] " << Entry.Name
7065 << "\n";
7066 OS << "\n";
7067 SecEntries.clear();
7068 };
7069
7070 auto OnSectionStart = [&](const Elf_Shdr &Shdr) {
7071 if (SectionStarted)
7072 PrintSection();
7073 SectionStarted = true;
7074 Current.Offset = Shdr.sh_offset;
7075 Current.Name = this->getPrintableSectionName(Shdr);
7076 };
7077 auto OnLibEntry = [&](StringRef Lib, uint64_t Offset) {
7078 SecEntries.push_back(NameOffset{Lib, Offset});
7079 };
7080
7081 this->printDependentLibsHelper(OnSectionStart, OnLibEntry);
7082 if (SectionStarted)
7083 PrintSection();
7084}
7085
7086template <class ELFT>
7087SmallVector<uint32_t> ELFDumper<ELFT>::getSymbolIndexesForFunctionAddress(
7088 uint64_t SymValue, std::optional<const Elf_Shdr *> FunctionSec) {
7089 SmallVector<uint32_t> SymbolIndexes;
7090 if (!this->AddressToIndexMap) {
7091 // Populate the address to index map upon the first invocation of this
7092 // function.
7093 this->AddressToIndexMap.emplace();
7094 if (this->DotSymtabSec) {
7095 if (Expected<Elf_Sym_Range> SymsOrError =
7096 Obj.symbols(this->DotSymtabSec)) {
7097 uint32_t Index = (uint32_t)-1;
7098 for (const Elf_Sym &Sym : *SymsOrError) {
7099 ++Index;
7100
7101 if (Sym.st_shndx == ELF::SHN_UNDEF || Sym.getType() != ELF::STT_FUNC)
7102 continue;
7103
7104 Expected<uint64_t> SymAddrOrErr =
7105 ObjF.toSymbolRef(this->DotSymtabSec, Index).getAddress();
7106 if (!SymAddrOrErr) {
7107 std::string Name = this->getStaticSymbolName(Index);
7108 reportUniqueWarning("unable to get address of symbol '" + Name +
7109 "': " + toString(E: SymAddrOrErr.takeError()));
7110 return SymbolIndexes;
7111 }
7112
7113 (*this->AddressToIndexMap)[*SymAddrOrErr].push_back(x: Index);
7114 }
7115 } else {
7116 reportUniqueWarning("unable to read the symbol table: " +
7117 toString(SymsOrError.takeError()));
7118 }
7119 }
7120 }
7121
7122 auto Symbols = this->AddressToIndexMap->find(Val: SymValue);
7123 if (Symbols == this->AddressToIndexMap->end())
7124 return SymbolIndexes;
7125
7126 for (uint32_t Index : Symbols->second) {
7127 // Check if the symbol is in the right section. FunctionSec == None
7128 // means "any section".
7129 if (FunctionSec) {
7130 const Elf_Sym &Sym = *cantFail(Obj.getSymbol(this->DotSymtabSec, Index));
7131 if (Expected<const Elf_Shdr *> SecOrErr =
7132 Obj.getSection(Sym, this->DotSymtabSec,
7133 this->getShndxTable(Symtab: this->DotSymtabSec))) {
7134 if (*FunctionSec != *SecOrErr)
7135 continue;
7136 } else {
7137 std::string Name = this->getStaticSymbolName(Index);
7138 // Note: it is impossible to trigger this error currently, it is
7139 // untested.
7140 reportUniqueWarning("unable to get section of symbol '" + Name +
7141 "': " + toString(SecOrErr.takeError()));
7142 return SymbolIndexes;
7143 }
7144 }
7145
7146 SymbolIndexes.push_back(Elt: Index);
7147 }
7148
7149 return SymbolIndexes;
7150}
7151
7152template <class ELFT>
7153bool ELFDumper<ELFT>::printFunctionStackSize(
7154 uint64_t SymValue, std::optional<const Elf_Shdr *> FunctionSec,
7155 const Elf_Shdr &StackSizeSec, DataExtractor Data, uint64_t *Offset) {
7156 SmallVector<uint32_t> FuncSymIndexes =
7157 this->getSymbolIndexesForFunctionAddress(SymValue, FunctionSec);
7158 if (FuncSymIndexes.empty())
7159 reportUniqueWarning(
7160 "could not identify function symbol for stack size entry in " +
7161 describe(Sec: StackSizeSec));
7162
7163 // Extract the size. The expectation is that Offset is pointing to the right
7164 // place, i.e. past the function address.
7165 Error Err = Error::success();
7166 uint64_t StackSize = Data.getULEB128(offset_ptr: Offset, Err: &Err);
7167 if (Err) {
7168 reportUniqueWarning("could not extract a valid stack size from " +
7169 describe(Sec: StackSizeSec) + ": " +
7170 toString(E: std::move(Err)));
7171 return false;
7172 }
7173
7174 if (FuncSymIndexes.empty()) {
7175 printStackSizeEntry(Size: StackSize, FuncNames: {"?"});
7176 } else {
7177 SmallVector<std::string> FuncSymNames;
7178 for (uint32_t Index : FuncSymIndexes)
7179 FuncSymNames.push_back(this->getStaticSymbolName(Index));
7180 printStackSizeEntry(Size: StackSize, FuncNames: FuncSymNames);
7181 }
7182
7183 return true;
7184}
7185
7186template <class ELFT>
7187void GNUELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
7188 ArrayRef<std::string> FuncNames) {
7189 OS.PadToColumn(NewCol: 2);
7190 OS << format_decimal(N: Size, Width: 11);
7191 OS.PadToColumn(NewCol: 18);
7192
7193 OS << join(Begin: FuncNames.begin(), End: FuncNames.end(), Separator: ", ") << "\n";
7194}
7195
7196template <class ELFT>
7197void ELFDumper<ELFT>::printStackSize(const Relocation<ELFT> &R,
7198 const Elf_Shdr &RelocSec, unsigned Ndx,
7199 const Elf_Shdr *SymTab,
7200 const Elf_Shdr *FunctionSec,
7201 const Elf_Shdr &StackSizeSec,
7202 const RelocationResolver &Resolver,
7203 DataExtractor Data) {
7204 // This function ignores potentially erroneous input, unless it is directly
7205 // related to stack size reporting.
7206 const Elf_Sym *Sym = nullptr;
7207 Expected<RelSymbol<ELFT>> TargetOrErr = this->getRelocationTarget(R, SymTab);
7208 if (!TargetOrErr)
7209 reportUniqueWarning("unable to get the target of relocation with index " +
7210 Twine(Ndx) + " in " + describe(Sec: RelocSec) + ": " +
7211 toString(TargetOrErr.takeError()));
7212 else
7213 Sym = TargetOrErr->Sym;
7214
7215 uint64_t RelocSymValue = 0;
7216 if (Sym) {
7217 Expected<const Elf_Shdr *> SectionOrErr =
7218 this->Obj.getSection(*Sym, SymTab, this->getShndxTable(Symtab: SymTab));
7219 if (!SectionOrErr) {
7220 reportUniqueWarning(
7221 "cannot identify the section for relocation symbol '" +
7222 (*TargetOrErr).Name + "': " + toString(SectionOrErr.takeError()));
7223 } else if (*SectionOrErr != FunctionSec) {
7224 reportUniqueWarning("relocation symbol '" + (*TargetOrErr).Name +
7225 "' is not in the expected section");
7226 // Pretend that the symbol is in the correct section and report its
7227 // stack size anyway.
7228 FunctionSec = *SectionOrErr;
7229 }
7230
7231 RelocSymValue = Sym->st_value;
7232 }
7233
7234 uint64_t Offset = R.Offset;
7235 if (!Data.isValidOffsetForDataOfSize(offset: Offset, length: sizeof(Elf_Addr) + 1)) {
7236 reportUniqueWarning("found invalid relocation offset (0x" +
7237 Twine::utohexstr(Val: Offset) + ") into " +
7238 describe(Sec: StackSizeSec) +
7239 " while trying to extract a stack size entry");
7240 return;
7241 }
7242
7243 uint64_t SymValue = Resolver(R.Type, Offset, RelocSymValue,
7244 Data.getUnsigned(offset_ptr: &Offset, byte_size: sizeof(Elf_Addr)),
7245 R.Addend.value_or(0));
7246 this->printFunctionStackSize(SymValue, FunctionSec, StackSizeSec, Data,
7247 Offset: &Offset);
7248}
7249
7250template <class ELFT>
7251void ELFDumper<ELFT>::printNonRelocatableStackSizes(
7252 std::function<void()> PrintHeader) {
7253 // This function ignores potentially erroneous input, unless it is directly
7254 // related to stack size reporting.
7255 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) {
7256 if (this->getPrintableSectionName(Sec) != ".stack_sizes")
7257 continue;
7258 PrintHeader();
7259 ArrayRef<uint8_t> Contents =
7260 unwrapOrError(this->FileName, Obj.getSectionContents(Sec));
7261 DataExtractor Data(Contents, Obj.isLE());
7262 uint64_t Offset = 0;
7263 while (Offset < Contents.size()) {
7264 // The function address is followed by a ULEB representing the stack
7265 // size. Check for an extra byte before we try to process the entry.
7266 if (!Data.isValidOffsetForDataOfSize(offset: Offset, length: sizeof(Elf_Addr) + 1)) {
7267 reportUniqueWarning(
7268 describe(Sec) +
7269 " ended while trying to extract a stack size entry");
7270 break;
7271 }
7272 uint64_t SymValue = Data.getUnsigned(offset_ptr: &Offset, byte_size: sizeof(Elf_Addr));
7273 if (!printFunctionStackSize(SymValue, /*FunctionSec=*/std::nullopt, StackSizeSec: Sec,
7274 Data, Offset: &Offset))
7275 break;
7276 }
7277 }
7278}
7279
7280template <class ELFT>
7281void ELFDumper<ELFT>::printRelocatableStackSizes(
7282 std::function<void()> PrintHeader) {
7283 // Build a map between stack size sections and their corresponding relocation
7284 // sections.
7285 auto IsMatch = [&](const Elf_Shdr &Sec) -> bool {
7286 StringRef SectionName;
7287 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec))
7288 SectionName = *NameOrErr;
7289 else
7290 consumeError(Err: NameOrErr.takeError());
7291
7292 return SectionName == ".stack_sizes";
7293 };
7294
7295 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>>
7296 StackSizeRelocMapOrErr = Obj.getSectionAndRelocations(IsMatch);
7297 if (!StackSizeRelocMapOrErr) {
7298 reportUniqueWarning("unable to get stack size map section(s): " +
7299 toString(StackSizeRelocMapOrErr.takeError()));
7300 return;
7301 }
7302
7303 for (const auto &StackSizeMapEntry : *StackSizeRelocMapOrErr) {
7304 PrintHeader();
7305 const Elf_Shdr *StackSizesELFSec = StackSizeMapEntry.first;
7306 const Elf_Shdr *RelocSec = StackSizeMapEntry.second;
7307
7308 // Warn about stack size sections without a relocation section.
7309 if (!RelocSec) {
7310 reportWarning(createError(".stack_sizes (" + describe(Sec: *StackSizesELFSec) +
7311 ") does not have a corresponding "
7312 "relocation section"),
7313 FileName);
7314 continue;
7315 }
7316
7317 // We might end up with relocations in CREL here. If we do, report a
7318 // warning since we do not currently support them.
7319 if (RelocSec->sh_type == ELF::SHT_CREL) {
7320 reportWarning(createError(".stack_sizes (" + describe(Sec: *StackSizesELFSec) +
7321 ") has a corresponding CREL relocation "
7322 "section, which is not currently supported"),
7323 FileName);
7324 continue;
7325 }
7326
7327 // A .stack_sizes section header's sh_link field is supposed to point
7328 // to the section that contains the functions whose stack sizes are
7329 // described in it.
7330 const Elf_Shdr *FunctionSec = unwrapOrError(
7331 this->FileName, Obj.getSection(StackSizesELFSec->sh_link));
7332
7333 SupportsRelocation IsSupportedFn;
7334 RelocationResolver Resolver;
7335 std::tie(args&: IsSupportedFn, args&: Resolver) = getRelocationResolver(this->ObjF);
7336 ArrayRef<uint8_t> Contents =
7337 unwrapOrError(this->FileName, Obj.getSectionContents(*StackSizesELFSec));
7338 DataExtractor Data(Contents, Obj.isLE());
7339
7340 forEachRelocationDo(
7341 Sec: *RelocSec, RelRelaFn: [&](const Relocation<ELFT> &R, unsigned Ndx,
7342 const Elf_Shdr &Sec, const Elf_Shdr *SymTab) {
7343 if (!IsSupportedFn || !IsSupportedFn(R.Type)) {
7344 reportUniqueWarning(
7345 describe(Sec: *RelocSec) +
7346 " contains an unsupported relocation with index " + Twine(Ndx) +
7347 ": " + Obj.getRelocationTypeName(R.Type));
7348 return;
7349 }
7350
7351 this->printStackSize(R, RelocSec: *RelocSec, Ndx, SymTab, FunctionSec,
7352 StackSizeSec: *StackSizesELFSec, Resolver, Data);
7353 });
7354 }
7355}
7356
7357template <class ELFT>
7358void GNUELFDumper<ELFT>::printStackSizes() {
7359 bool HeaderHasBeenPrinted = false;
7360 auto PrintHeader = [&]() {
7361 if (HeaderHasBeenPrinted)
7362 return;
7363 OS << "\nStack Sizes:\n";
7364 OS.PadToColumn(NewCol: 9);
7365 OS << "Size";
7366 OS.PadToColumn(NewCol: 18);
7367 OS << "Functions\n";
7368 HeaderHasBeenPrinted = true;
7369 };
7370
7371 // For non-relocatable objects, look directly for sections whose name starts
7372 // with .stack_sizes and process the contents.
7373 if (this->Obj.getHeader().e_type == ELF::ET_REL)
7374 this->printRelocatableStackSizes(PrintHeader);
7375 else
7376 this->printNonRelocatableStackSizes(PrintHeader);
7377}
7378
7379template <class ELFT>
7380void GNUELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
7381 size_t Bias = ELFT::Is64Bits ? 8 : 0;
7382 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
7383 OS.PadToColumn(NewCol: 2);
7384 OS << format_hex_no_prefix(Parser.getGotAddress(E), 8 + Bias);
7385 OS.PadToColumn(NewCol: 11 + Bias);
7386 OS << format_decimal(Parser.getGotOffset(E), 6) << "(gp)";
7387 OS.PadToColumn(NewCol: 22 + Bias);
7388 OS << format_hex_no_prefix(*E, 8 + Bias);
7389 OS.PadToColumn(NewCol: 31 + 2 * Bias);
7390 OS << Purpose << "\n";
7391 };
7392
7393 OS << (Parser.IsStatic ? "Static GOT:\n" : "Primary GOT:\n");
7394 OS << " Canonical gp value: "
7395 << format_hex_no_prefix(Parser.getGp(), 8 + Bias) << "\n\n";
7396
7397 OS << " Reserved entries:\n";
7398 if (ELFT::Is64Bits)
7399 OS << " Address Access Initial Purpose\n";
7400 else
7401 OS << " Address Access Initial Purpose\n";
7402 PrintEntry(Parser.getGotLazyResolver(), "Lazy resolver");
7403 if (Parser.getGotModulePointer())
7404 PrintEntry(Parser.getGotModulePointer(), "Module pointer (GNU extension)");
7405
7406 if (!Parser.getLocalEntries().empty()) {
7407 OS << "\n";
7408 OS << " Local entries:\n";
7409 if (ELFT::Is64Bits)
7410 OS << " Address Access Initial\n";
7411 else
7412 OS << " Address Access Initial\n";
7413 for (auto &E : Parser.getLocalEntries())
7414 PrintEntry(&E, "");
7415 }
7416
7417 if (Parser.IsStatic)
7418 return;
7419
7420 if (!Parser.getGlobalEntries().empty()) {
7421 OS << "\n";
7422 OS << " Global entries:\n";
7423 if (ELFT::Is64Bits)
7424 OS << " Address Access Initial Sym.Val."
7425 << " Type Ndx Name\n";
7426 else
7427 OS << " Address Access Initial Sym.Val. Type Ndx Name\n";
7428
7429 DataRegion<Elf_Word> ShndxTable(
7430 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
7431 for (auto &E : Parser.getGlobalEntries()) {
7432 const Elf_Sym &Sym = *Parser.getGotSym(&E);
7433 const Elf_Sym &FirstSym = this->dynamic_symbols()[0];
7434 std::string SymName = this->getFullSymbolName(
7435 Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
7436
7437 OS.PadToColumn(NewCol: 2);
7438 OS << to_string(format_hex_no_prefix(Parser.getGotAddress(&E), 8 + Bias));
7439 OS.PadToColumn(NewCol: 11 + Bias);
7440 OS << to_string(format_decimal(Parser.getGotOffset(&E), 6)) + "(gp)";
7441 OS.PadToColumn(NewCol: 22 + Bias);
7442 OS << to_string(format_hex_no_prefix(E, 8 + Bias));
7443 OS.PadToColumn(NewCol: 31 + 2 * Bias);
7444 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
7445 OS.PadToColumn(NewCol: 40 + 3 * Bias);
7446 OS << getElfSymbolTypes().toStringOrHex(Sym.getType(), 1);
7447 OS.PadToColumn(NewCol: 48 + 3 * Bias);
7448 OS << getSymbolSectionNdx(Symbol: Sym, SymIndex: &Sym - this->dynamic_symbols().begin(),
7449 ShndxTable);
7450 OS.PadToColumn(NewCol: 52 + 3 * Bias);
7451 OS << SymName << "\n";
7452 }
7453 }
7454
7455 if (!Parser.getOtherEntries().empty())
7456 OS << "\n Number of TLS and multi-GOT entries "
7457 << Parser.getOtherEntries().size() << "\n";
7458}
7459
7460template <class ELFT>
7461void GNUELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
7462 size_t Bias = ELFT::Is64Bits ? 8 : 0;
7463 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) {
7464 OS.PadToColumn(NewCol: 2);
7465 OS << format_hex_no_prefix(Parser.getPltAddress(E), 8 + Bias);
7466 OS.PadToColumn(NewCol: 11 + Bias);
7467 OS << format_hex_no_prefix(*E, 8 + Bias);
7468 OS.PadToColumn(NewCol: 20 + 2 * Bias);
7469 OS << Purpose << "\n";
7470 };
7471
7472 OS << "PLT GOT:\n\n";
7473
7474 OS << " Reserved entries:\n";
7475 OS << " Address Initial Purpose\n";
7476 PrintEntry(Parser.getPltLazyResolver(), "PLT lazy resolver");
7477 if (Parser.getPltModulePointer())
7478 PrintEntry(Parser.getPltModulePointer(), "Module pointer");
7479
7480 if (!Parser.getPltEntries().empty()) {
7481 OS << "\n";
7482 OS << " Entries:\n";
7483 OS << " Address Initial Sym.Val. Type Ndx Name\n";
7484 DataRegion<Elf_Word> ShndxTable(
7485 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
7486 for (auto &E : Parser.getPltEntries()) {
7487 const Elf_Sym &Sym = *Parser.getPltSym(&E);
7488 const Elf_Sym &FirstSym = *cantFail(
7489 this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
7490 std::string SymName = this->getFullSymbolName(
7491 Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false);
7492
7493 OS.PadToColumn(NewCol: 2);
7494 OS << to_string(format_hex_no_prefix(Parser.getPltAddress(&E), 8 + Bias));
7495 OS.PadToColumn(NewCol: 11 + Bias);
7496 OS << to_string(format_hex_no_prefix(E, 8 + Bias));
7497 OS.PadToColumn(NewCol: 20 + 2 * Bias);
7498 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias));
7499 OS.PadToColumn(NewCol: 29 + 3 * Bias);
7500 OS << getElfSymbolTypes().toStringOrHex(Sym.getType(), 1);
7501 OS.PadToColumn(NewCol: 37 + 3 * Bias);
7502 OS << getSymbolSectionNdx(Symbol: Sym, SymIndex: &Sym - this->dynamic_symbols().begin(),
7503 ShndxTable);
7504 OS.PadToColumn(NewCol: 41 + 3 * Bias);
7505 OS << SymName << "\n";
7506 }
7507 }
7508}
7509
7510template <class ELFT>
7511Expected<const Elf_Mips_ABIFlags<ELFT> *>
7512getMipsAbiFlagsSection(const ELFDumper<ELFT> &Dumper) {
7513 const typename ELFT::Shdr *Sec = Dumper.findSectionByName(".MIPS.abiflags");
7514 if (Sec == nullptr)
7515 return nullptr;
7516
7517 constexpr StringRef ErrPrefix = "unable to read the .MIPS.abiflags section: ";
7518 Expected<ArrayRef<uint8_t>> DataOrErr =
7519 Dumper.getElfObject().getELFFile().getSectionContents(*Sec);
7520 if (!DataOrErr)
7521 return createError(Err: ErrPrefix + toString(E: DataOrErr.takeError()));
7522
7523 if (DataOrErr->size() != sizeof(Elf_Mips_ABIFlags<ELFT>))
7524 return createError(Err: ErrPrefix + "it has a wrong size (" +
7525 Twine(DataOrErr->size()) + ")");
7526 return reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(DataOrErr->data());
7527}
7528
7529template <class ELFT> void GNUELFDumper<ELFT>::printMipsABIFlags() {
7530 const Elf_Mips_ABIFlags<ELFT> *Flags = nullptr;
7531 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
7532 getMipsAbiFlagsSection(*this))
7533 Flags = *SecOrErr;
7534 else
7535 this->reportUniqueWarning(SecOrErr.takeError());
7536 if (!Flags)
7537 return;
7538
7539 OS << "MIPS ABI Flags Version: " << Flags->version << "\n\n";
7540 OS << "ISA: MIPS" << int(Flags->isa_level);
7541 if (Flags->isa_rev > 1)
7542 OS << "r" << int(Flags->isa_rev);
7543 OS << "\n";
7544 OS << "GPR size: " << getMipsRegisterSize(Flags->gpr_size) << "\n";
7545 OS << "CPR1 size: " << getMipsRegisterSize(Flags->cpr1_size) << "\n";
7546 OS << "CPR2 size: " << getMipsRegisterSize(Flags->cpr2_size) << "\n";
7547 OS << "FP ABI: " << EnumStrings(ElfMipsFpABIType).toStringOrHex(Flags->fp_abi)
7548 << "\n";
7549 OS << "ISA Extension: "
7550 << EnumStrings(ElfMipsISAExtType).toStringOrHex(Flags->isa_ext) << "\n";
7551 if (Flags->ases == 0)
7552 OS << "ASEs: None\n";
7553 else
7554 // FIXME: Print each flag on a separate line.
7555 OS << "ASEs: " << printFlags(Flags->ases, EnumStrings(ElfMipsASEFlags))
7556 << "\n";
7557 OS << "FLAGS 1: " << format_hex_no_prefix(Flags->flags1, 8, false) << "\n";
7558 OS << "FLAGS 2: " << format_hex_no_prefix(Flags->flags2, 8, false) << "\n";
7559 OS << "\n";
7560}
7561
7562template <class ELFT> void LLVMELFDumper<ELFT>::printFileHeaders() {
7563 const Elf_Ehdr &E = this->Obj.getHeader();
7564 {
7565 DictScope D(W, "ElfHeader");
7566 {
7567 DictScope D(W, "Ident");
7568 W.printBinary(Label: "Magic",
7569 Value: ArrayRef<unsigned char>(E.e_ident).slice(N: ELF::EI_MAG0, M: 4));
7570 W.printEnum("Class", E.e_ident[ELF::EI_CLASS], EnumStrings(ElfClass));
7571 W.printEnum("DataEncoding", E.e_ident[ELF::EI_DATA],
7572 EnumStrings(ElfDataEncoding));
7573 W.printNumber("FileVersion", E.e_ident[ELF::EI_VERSION]);
7574
7575 auto OSABI = EnumStrings(ElfOSABI);
7576 if (E.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH &&
7577 E.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) {
7578 switch (E.e_machine) {
7579 case ELF::EM_AMDGPU:
7580 OSABI = EnumStrings(AMDGPUElfOSABI);
7581 break;
7582 case ELF::EM_ARM:
7583 OSABI = EnumStrings(ARMElfOSABI);
7584 break;
7585 case ELF::EM_TI_C6000:
7586 OSABI = EnumStrings(C6000ElfOSABI);
7587 break;
7588 }
7589 }
7590 W.printEnum("OS/ABI", E.e_ident[ELF::EI_OSABI], OSABI);
7591 W.printNumber("ABIVersion", E.e_ident[ELF::EI_ABIVERSION]);
7592 W.printBinary(Label: "Unused",
7593 Value: ArrayRef<unsigned char>(E.e_ident).slice(N: ELF::EI_PAD));
7594 }
7595
7596 std::string TypeStr;
7597 if (StringRef Name = EnumStrings(ElfObjectFileType).toString(E.e_type);
7598 !Name.empty()) {
7599 TypeStr = Name.str();
7600 } else {
7601 if (E.e_type >= ET_LOPROC)
7602 TypeStr = "Processor Specific";
7603 else if (E.e_type >= ET_LOOS)
7604 TypeStr = "OS Specific";
7605 else
7606 TypeStr = "Unknown";
7607 }
7608 W.printString("Type", TypeStr + " (0x" +
7609 utohexstr(E.e_type, /*LowerCase=*/true) + ")");
7610
7611 W.printEnum("Machine", E.e_machine, EnumStrings(ElfMachineType));
7612 W.printNumber("Version", E.e_version);
7613 W.printHex("Entry", E.e_entry);
7614 W.printHex("ProgramHeaderOffset", E.e_phoff);
7615 W.printHex("SectionHeaderOffset", E.e_shoff);
7616 if (E.e_machine == EM_MIPS)
7617 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderMipsFlags),
7618 unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI),
7619 unsigned(ELF::EF_MIPS_MACH));
7620 else if (E.e_machine == EM_AMDGPU) {
7621 switch (E.e_ident[ELF::EI_ABIVERSION]) {
7622 default:
7623 W.printHex("Flags", E.e_flags);
7624 break;
7625 case 0:
7626 // ELFOSABI_AMDGPU_PAL, ELFOSABI_AMDGPU_MESA3D support *_V3 flags.
7627 [[fallthrough]];
7628 case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
7629 W.printFlags("Flags", E.e_flags,
7630 EnumStrings(ElfHeaderAMDGPUFlagsABIVersion3),
7631 unsigned(ELF::EF_AMDGPU_MACH));
7632 break;
7633 case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
7634 case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
7635 W.printFlags("Flags", E.e_flags,
7636 EnumStrings(ElfHeaderAMDGPUFlagsABIVersion4),
7637 unsigned(ELF::EF_AMDGPU_MACH),
7638 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
7639 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4));
7640 break;
7641 case ELF::ELFABIVERSION_AMDGPU_HSA_V6: {
7642 std::optional<FlagEntry> VerFlagEntry;
7643 // The string needs to remain alive from the moment we create a
7644 // FlagEntry until printFlags is done.
7645 std::string FlagStr;
7646 if (auto VersionFlag = E.e_flags & ELF::EF_AMDGPU_GENERIC_VERSION) {
7647 unsigned Version =
7648 VersionFlag >> ELF::EF_AMDGPU_GENERIC_VERSION_OFFSET;
7649 FlagStr = "EF_AMDGPU_GENERIC_VERSION_V" + std::to_string(val: Version);
7650 VerFlagEntry = FlagEntry(FlagStr, VersionFlag);
7651 }
7652 W.printFlags(
7653 "Flags", E.e_flags, EnumStrings(ElfHeaderAMDGPUFlagsABIVersion4),
7654 unsigned(ELF::EF_AMDGPU_MACH),
7655 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4),
7656 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4),
7657 VerFlagEntry ? ArrayRef(*VerFlagEntry) : ArrayRef<FlagEntry>());
7658 break;
7659 }
7660 }
7661 } else if (E.e_machine == EM_RISCV)
7662 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderRISCVFlags),
7663 unsigned(ELF::EF_RISCV_FLOAT_ABI));
7664 else if (E.e_machine == EM_SPARC32PLUS || E.e_machine == EM_SPARCV9)
7665 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderSPARCFlags),
7666 unsigned(ELF::EF_SPARCV9_MM));
7667 else if (E.e_machine == EM_AVR)
7668 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderAVRFlags),
7669 unsigned(ELF::EF_AVR_ARCH_MASK));
7670 else if (E.e_machine == EM_LOONGARCH)
7671 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderLoongArchFlags),
7672 unsigned(ELF::EF_LOONGARCH_ABI_MODIFIER_MASK),
7673 unsigned(ELF::EF_LOONGARCH_OBJABI_MASK));
7674 else if (E.e_machine == EM_XTENSA)
7675 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderXtensaFlags),
7676 unsigned(ELF::EF_XTENSA_MACH));
7677 else if (E.e_machine == EM_CUDA)
7678 W.printFlags("Flags", E.e_flags, EnumStrings(ElfHeaderNVPTXFlags),
7679 unsigned(ELF::EF_CUDA_SM));
7680 else
7681 W.printFlags("Flags", E.e_flags);
7682 W.printNumber("HeaderSize", E.e_ehsize);
7683 W.printNumber("ProgramHeaderEntrySize", E.e_phentsize);
7684 W.printString("ProgramHeaderCount", this->getProgramHeadersNumString());
7685 W.printNumber("SectionHeaderEntrySize", E.e_shentsize);
7686 W.printString("SectionHeaderCount",
7687 getSectionHeadersNumString(this->Obj, this->FileName));
7688 W.printString("StringTableSectionIndex",
7689 getSectionHeaderTableIndexString(this->Obj, this->FileName));
7690 }
7691}
7692
7693template <class ELFT> void LLVMELFDumper<ELFT>::printGroupSections() {
7694 DictScope Lists(W, "Groups");
7695 std::vector<GroupSection> V = this->getGroups();
7696 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(Groups: V);
7697 for (const GroupSection &G : V) {
7698 DictScope D(W, "Group");
7699 W.printNumber(Label: "Name", Str: G.Name, Value: G.ShName);
7700 W.printNumber(Label: "Index", Value: G.Index);
7701 W.printNumber(Label: "Link", Value: G.Link);
7702 W.printNumber(Label: "Info", Value: G.Info);
7703 W.printHex(Label: "Type", Str: getGroupType(Flag: G.Type), Value: G.Type);
7704 W.printString(Label: "Signature", Value: G.Signature);
7705
7706 ListScope L(W, getGroupSectionHeaderName());
7707 for (const GroupMember &GM : G.Members) {
7708 const GroupSection *MainGroup = Map[GM.Index];
7709 if (MainGroup != &G)
7710 this->reportUniqueWarning(
7711 "section with index " + Twine(GM.Index) +
7712 ", included in the group section with index " +
7713 Twine(MainGroup->Index) +
7714 ", was also found in the group section with index " +
7715 Twine(G.Index));
7716 printSectionGroupMembers(Name: GM.Name, Idx: GM.Index);
7717 }
7718 }
7719
7720 if (V.empty())
7721 printEmptyGroupMessage();
7722}
7723
7724template <class ELFT>
7725std::string LLVMELFDumper<ELFT>::getGroupSectionHeaderName() const {
7726 return "Section(s) in group";
7727}
7728
7729template <class ELFT>
7730void LLVMELFDumper<ELFT>::printSectionGroupMembers(StringRef Name,
7731 uint64_t Idx) const {
7732 W.startLine() << Name << " (" << Idx << ")\n";
7733}
7734
7735template <class ELFT> void LLVMELFDumper<ELFT>::printRelocations() {
7736 ListScope D(W, "Relocations");
7737
7738 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
7739 if (!isRelocationSec<ELFT>(Sec, this->Obj.getHeader()))
7740 continue;
7741
7742 StringRef Name = this->getPrintableSectionName(Sec);
7743 unsigned SecNdx = &Sec - &cantFail(this->Obj.sections()).front();
7744 printRelocationSectionInfo(Sec, Name, SecNdx);
7745 }
7746}
7747
7748template <class ELFT>
7749void LLVMELFDumper<ELFT>::printExpandedRelRelaReloc(const Relocation<ELFT> &R,
7750 StringRef SymbolName,
7751 StringRef RelocName) {
7752 DictScope Group(W, "Relocation");
7753 W.printHex("Offset", R.Offset);
7754 W.printNumber("Type", RelocName, R.Type);
7755 W.printNumber("Symbol", !SymbolName.empty() ? SymbolName : "-", R.Symbol);
7756 if (R.Addend)
7757 W.printHex("Addend", (uintX_t)*R.Addend);
7758}
7759
7760template <class ELFT>
7761void LLVMELFDumper<ELFT>::printDefaultRelRelaReloc(const Relocation<ELFT> &R,
7762 StringRef SymbolName,
7763 StringRef RelocName) {
7764 raw_ostream &OS = W.startLine();
7765 OS << W.hex(R.Offset) << " " << RelocName << " "
7766 << (!SymbolName.empty() ? SymbolName : "-");
7767 if (R.Addend)
7768 OS << " " << W.hex((uintX_t)*R.Addend);
7769 OS << "\n";
7770}
7771
7772template <class ELFT>
7773void LLVMELFDumper<ELFT>::printRelocationSectionInfo(const Elf_Shdr &Sec,
7774 StringRef Name,
7775 const unsigned SecNdx) {
7776 DictScope D(W, (Twine("Section (") + Twine(SecNdx) + ") " + Name).str());
7777 this->printRelocationsHelper(Sec);
7778}
7779
7780template <class ELFT> void LLVMELFDumper<ELFT>::printEmptyGroupMessage() const {
7781 W.startLine() << "There are no group sections in the file.\n";
7782}
7783
7784template <class ELFT>
7785void LLVMELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R,
7786 const RelSymbol<ELFT> &RelSym) {
7787 StringRef SymbolName = RelSym.Name;
7788 if (RelSym.Sym && RelSym.Name.empty())
7789 SymbolName = "<null>";
7790 SmallString<32> RelocName;
7791 StringRef RelocTypeName = this->getRelocTypeName(R.Type, RelocName);
7792
7793 if (opts::ExpandRelocs) {
7794 printExpandedRelRelaReloc(R, SymbolName, RelocName: RelocTypeName);
7795 } else {
7796 printDefaultRelRelaReloc(R, SymbolName, RelocName: RelocTypeName);
7797 }
7798}
7799
7800template <class ELFT> void LLVMELFDumper<ELFT>::printSectionHeaders() {
7801 ListScope SectionsD(W, "Sections");
7802
7803 int SectionIndex = -1;
7804 auto FlagsList =
7805 getSectionFlagsForTarget(this->Obj.getHeader().e_ident[ELF::EI_OSABI],
7806 this->Obj.getHeader().e_machine);
7807 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) {
7808 DictScope SectionD(W, "Section");
7809 W.printNumber(Label: "Index", Value: ++SectionIndex);
7810 W.printNumber("Name", this->getPrintableSectionName(Sec), Sec.sh_name);
7811 W.printHex("Type",
7812 object::getELFSectionTypeName(Machine: this->Obj.getHeader().e_machine,
7813 Type: Sec.sh_type),
7814 Sec.sh_type);
7815 SmallVector<FlagEntry> SetFlags;
7816 for (const auto *Flag : FlagsList)
7817 if ((Sec.sh_flags & Flag->value()) == Flag->value())
7818 SetFlags.emplace_back(Flag->name(), Flag->value());
7819 W.printFlags("Flags", Sec.sh_flags, SetFlags);
7820 W.printHex("Address", Sec.sh_addr);
7821 W.printHex("Offset", Sec.sh_offset);
7822 W.printNumber("Size", Sec.sh_size);
7823 W.printNumber("Link", Sec.sh_link);
7824 W.printNumber("Info", Sec.sh_info);
7825 W.printNumber("AddressAlignment", Sec.sh_addralign);
7826 W.printNumber("EntrySize", Sec.sh_entsize);
7827
7828 if (opts::SectionRelocations) {
7829 ListScope D(W, "Relocations");
7830 this->printRelocationsHelper(Sec);
7831 }
7832
7833 if (opts::SectionSymbols) {
7834 ListScope D(W, "Symbols");
7835 if (this->DotSymtabSec) {
7836 StringRef StrTable = unwrapOrError(
7837 this->FileName,
7838 this->Obj.getStringTableForSymtab(*this->DotSymtabSec));
7839 ArrayRef<Elf_Word> ShndxTable = this->getShndxTable(this->DotSymtabSec);
7840
7841 typename ELFT::SymRange Symbols = unwrapOrError(
7842 this->FileName, this->Obj.symbols(this->DotSymtabSec));
7843 for (const Elf_Sym &Sym : Symbols) {
7844 const Elf_Shdr *SymSec = unwrapOrError(
7845 this->FileName,
7846 this->Obj.getSection(Sym, this->DotSymtabSec, ShndxTable));
7847 if (SymSec == &Sec)
7848 printSymbol(Symbol: Sym, SymIndex: &Sym - &Symbols[0], ShndxTable, StrTable, IsDynamic: false,
7849 /*NonVisibilityBitsUsed=*/false,
7850 /*ExtraSymInfo=*/false);
7851 }
7852 }
7853 }
7854
7855 if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) {
7856 ArrayRef<uint8_t> Data =
7857 unwrapOrError(this->FileName, this->Obj.getSectionContents(Sec));
7858 W.printBinaryBlock(
7859 Label: "SectionData",
7860 Value: StringRef(reinterpret_cast<const char *>(Data.data()), Data.size()));
7861 }
7862 }
7863}
7864
7865template <class ELFT>
7866void LLVMELFDumper<ELFT>::printSymbolSection(
7867 const Elf_Sym &Symbol, unsigned SymIndex,
7868 DataRegion<Elf_Word> ShndxTable) const {
7869 auto GetSectionSpecialType = [&]() -> std::optional<StringRef> {
7870 if (Symbol.isUndefined())
7871 return StringRef("Undefined");
7872 if (Symbol.isProcessorSpecific())
7873 return StringRef("Processor Specific");
7874 if (Symbol.isOSSpecific())
7875 return StringRef("Operating System Specific");
7876 if (Symbol.isAbsolute())
7877 return StringRef("Absolute");
7878 if (Symbol.isCommon())
7879 return StringRef("Common");
7880 if (Symbol.isReserved() && Symbol.st_shndx != SHN_XINDEX)
7881 return StringRef("Reserved");
7882 return std::nullopt;
7883 };
7884
7885 if (std::optional<StringRef> Type = GetSectionSpecialType()) {
7886 W.printHex("Section", *Type, Symbol.st_shndx);
7887 return;
7888 }
7889
7890 Expected<unsigned> SectionIndex =
7891 this->getSymbolSectionIndex(Symbol, SymIndex, ShndxTable);
7892 if (!SectionIndex) {
7893 assert(Symbol.st_shndx == SHN_XINDEX &&
7894 "getSymbolSectionIndex should only fail due to an invalid "
7895 "SHT_SYMTAB_SHNDX table/reference");
7896 this->reportUniqueWarning(SectionIndex.takeError());
7897 W.printHex(Label: "Section", Str: "Reserved", Value: SHN_XINDEX);
7898 return;
7899 }
7900
7901 Expected<StringRef> SectionName =
7902 this->getSymbolSectionName(Symbol, *SectionIndex);
7903 if (!SectionName) {
7904 // Don't report an invalid section name if the section headers are missing.
7905 // In such situations, all sections will be "invalid".
7906 if (!this->ObjF.sections().empty())
7907 this->reportUniqueWarning(SectionName.takeError());
7908 else
7909 consumeError(Err: SectionName.takeError());
7910 W.printHex(Label: "Section", Str: "<?>", Value: *SectionIndex);
7911 } else {
7912 W.printHex(Label: "Section", Str: *SectionName, Value: *SectionIndex);
7913 }
7914}
7915
7916template <class ELFT>
7917void LLVMELFDumper<ELFT>::printSymbolOtherField(const Elf_Sym &Symbol) const {
7918 auto SymOtherFlags =
7919 this->getOtherFlagsFromSymbol(this->Obj.getHeader(), Symbol);
7920 SmallVector<FlagEntry> SetFlags;
7921 unsigned EnumMask = 0x3u;
7922 for (const auto *Flag : SymOtherFlags) {
7923 if (Flag->value() & EnumMask) {
7924 if ((Symbol.st_other & EnumMask) == Flag->value())
7925 SetFlags.emplace_back(Flag->name(), Flag->value());
7926 } else if (Flag->value()) {
7927 if ((Symbol.st_other & Flag->value()) == Flag->value())
7928 SetFlags.emplace_back(Flag->name(), Flag->value());
7929 }
7930 }
7931 W.printFlags("Other", Symbol.st_other, SetFlags);
7932}
7933
7934template <class ELFT>
7935void LLVMELFDumper<ELFT>::printZeroSymbolOtherField(
7936 const Elf_Sym &Symbol) const {
7937 assert(Symbol.st_other == 0 && "non-zero Other Field");
7938 // Usually st_other flag is zero. Do not pollute the output
7939 // by flags enumeration in that case.
7940 W.printNumber(Label: "Other", Value: 0);
7941}
7942
7943template <class ELFT>
7944void LLVMELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex,
7945 DataRegion<Elf_Word> ShndxTable,
7946 std::optional<StringRef> StrTable,
7947 bool IsDynamic,
7948 bool /*NonVisibilityBitsUsed*/,
7949 bool /*ExtraSymInfo*/) const {
7950 std::string FullSymbolName = this->getFullSymbolName(
7951 Symbol, SymIndex, ShndxTable, StrTable, IsDynamic);
7952 unsigned char SymbolType = Symbol.getType();
7953
7954 DictScope D(W, "Symbol");
7955 W.printNumber("Name", FullSymbolName, Symbol.st_name);
7956 W.printHex("Value", Symbol.st_value);
7957 W.printNumber("Size", Symbol.st_size);
7958 W.printEnum("Binding", Symbol.getBinding(), EnumStrings(ElfSymbolBindings));
7959 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU &&
7960 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS)
7961 W.printEnum(Label: "Type", Value: SymbolType, EnumValues: EnumStrings(AMDGPUSymbolTypes));
7962 else
7963 W.printEnum(Label: "Type", Value: SymbolType, EnumValues: getElfSymbolTypes());
7964 if (Symbol.st_other == 0)
7965 printZeroSymbolOtherField(Symbol);
7966 else
7967 printSymbolOtherField(Symbol);
7968 printSymbolSection(Symbol, SymIndex, ShndxTable);
7969}
7970
7971template <class ELFT>
7972void LLVMELFDumper<ELFT>::printSymbols(bool PrintSymbols,
7973 bool PrintDynamicSymbols,
7974 bool ExtraSymInfo) {
7975 if (PrintSymbols) {
7976 ListScope Group(W, "Symbols");
7977 this->printSymbolsHelper(false, ExtraSymInfo);
7978 }
7979 if (PrintDynamicSymbols) {
7980 ListScope Group(W, "DynamicSymbols");
7981 this->printSymbolsHelper(true, ExtraSymInfo);
7982 }
7983}
7984
7985template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicTable() {
7986 Elf_Dyn_Range Table = this->dynamic_table();
7987 if (Table.empty())
7988 return;
7989
7990 W.startLine() << "DynamicSection [ (" << Table.size() << " entries)\n";
7991
7992 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table);
7993 // The "Name/Value" column should be indented from the "Type" column by N
7994 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing
7995 // space (1) = -3.
7996 W.startLine() << " Tag" << std::string(ELFT::Is64Bits ? 16 : 8, ' ')
7997 << "Type" << std::string(MaxTagSize - 3, ' ') << "Name/Value\n";
7998
7999 std::string ValueFmt = "%-" + std::to_string(val: MaxTagSize) + "s ";
8000 for (auto Entry : Table) {
8001 uintX_t Tag = Entry.getTag();
8002 std::string Value = this->getDynamicEntry(Tag, Entry.getVal());
8003 W.startLine() << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10, true)
8004 << " "
8005 << format(ValueFmt.c_str(),
8006 this->Obj.getDynamicTagAsString(Tag).c_str())
8007 << Value << "\n";
8008 }
8009 W.startLine() << "]\n";
8010}
8011
8012template <class ELFT>
8013void JSONELFDumper<ELFT>::printAuxillaryDynamicTableEntryInfo(
8014 const Elf_Dyn &Entry) {
8015 auto FormatFlags = [this, Value = Entry.getVal()](auto Flags) {
8016 ListScope L(this->W, "Flags");
8017 for (const auto &Flag : Flags) {
8018 if (Flag.value() != 0 && (Value & Flag.value()) == Flag.value())
8019 this->W.printString(Flag.name());
8020 }
8021 };
8022 switch (Entry.getTag()) {
8023 case DT_SONAME:
8024 this->W.printString("Name", this->getDynamicString(Entry.getVal()));
8025 break;
8026 case DT_AUXILIARY:
8027 case DT_FILTER:
8028 case DT_NEEDED:
8029 this->W.printString("Library", this->getDynamicString(Entry.getVal()));
8030 break;
8031 case DT_USED:
8032 this->W.printString("Object", this->getDynamicString(Entry.getVal()));
8033 break;
8034 case DT_RPATH:
8035 case DT_RUNPATH: {
8036 StringRef Value = this->getDynamicString(Entry.getVal());
8037 ListScope L(this->W, "Path");
8038 while (!Value.empty()) {
8039 auto [Front, Back] = Value.split(Separator: ':');
8040 this->W.printString(Front);
8041 Value = Back;
8042 }
8043 break;
8044 }
8045 case DT_FLAGS:
8046 FormatFlags(EnumStrings(ElfDynamicDTFlags));
8047 break;
8048 case DT_FLAGS_1:
8049 FormatFlags(EnumStrings(ElfDynamicDTFlags1));
8050 break;
8051 default:
8052 return;
8053 }
8054}
8055
8056template <class ELFT> void JSONELFDumper<ELFT>::printDynamicTable() {
8057 Elf_Dyn_Range Table = this->dynamic_table();
8058 ListScope L(this->W, "DynamicSection");
8059 for (const auto &Entry : Table) {
8060 DictScope D(this->W);
8061 uintX_t Tag = Entry.getTag();
8062 this->W.printHex("Tag", Tag);
8063 this->W.printString("Type", this->Obj.getDynamicTagAsString(Tag));
8064 this->W.printHex("Value", Entry.getVal());
8065 this->printAuxillaryDynamicTableEntryInfo(Entry);
8066 }
8067}
8068
8069template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicRelocations() {
8070 W.startLine() << "Dynamic Relocations {\n";
8071 W.indent();
8072 this->printDynamicRelocationsHelper();
8073 W.unindent();
8074 W.startLine() << "}\n";
8075}
8076
8077template <class ELFT>
8078void LLVMELFDumper<ELFT>::printProgramHeaders(
8079 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) {
8080 if (PrintProgramHeaders)
8081 printProgramHeaders();
8082 if (PrintSectionMapping == cl::boolOrDefault::BOU_TRUE)
8083 printSectionMapping();
8084}
8085
8086template <class ELFT> void LLVMELFDumper<ELFT>::printProgramHeaders() {
8087 ListScope L(W, "ProgramHeaders");
8088
8089 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers();
8090 if (!PhdrsOrErr) {
8091 this->reportUniqueWarning("unable to dump program headers: " +
8092 toString(PhdrsOrErr.takeError()));
8093 return;
8094 }
8095
8096 for (const Elf_Phdr &Phdr : *PhdrsOrErr) {
8097 DictScope P(W, "ProgramHeader");
8098 StringRef Type =
8099 segmentTypeToString(this->Obj.getHeader().e_machine, Phdr.p_type);
8100
8101 W.printHex("Type", Type.empty() ? "Unknown" : Type, Phdr.p_type);
8102 W.printHex("Offset", Phdr.p_offset);
8103 W.printHex("VirtualAddress", Phdr.p_vaddr);
8104 W.printHex("PhysicalAddress", Phdr.p_paddr);
8105 W.printNumber("FileSize", Phdr.p_filesz);
8106 W.printNumber("MemSize", Phdr.p_memsz);
8107 W.printFlags("Flags", Phdr.p_flags, EnumStrings(ElfSegmentFlags));
8108 W.printNumber("Alignment", Phdr.p_align);
8109 }
8110}
8111
8112template <class ELFT>
8113void LLVMELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) {
8114 ListScope SS(W, "VersionSymbols");
8115 if (!Sec)
8116 return;
8117
8118 StringRef StrTable;
8119 ArrayRef<Elf_Sym> Syms;
8120 const Elf_Shdr *SymTabSec;
8121 Expected<ArrayRef<Elf_Versym>> VerTableOrErr =
8122 this->getVersionTable(*Sec, &Syms, &StrTable, &SymTabSec);
8123 if (!VerTableOrErr) {
8124 this->reportUniqueWarning(VerTableOrErr.takeError());
8125 return;
8126 }
8127
8128 if (StrTable.empty() || Syms.empty() || Syms.size() != VerTableOrErr->size())
8129 return;
8130
8131 ArrayRef<Elf_Word> ShNdxTable = this->getShndxTable(SymTabSec);
8132 for (size_t I = 0, E = Syms.size(); I < E; ++I) {
8133 DictScope S(W, "Symbol");
8134 W.printNumber("Version", (*VerTableOrErr)[I].vs_index & VERSYM_VERSION);
8135 W.printString("Name",
8136 this->getFullSymbolName(Syms[I], I, ShNdxTable, StrTable,
8137 /*IsDynamic=*/true));
8138 }
8139}
8140
8141constexpr EnumStringDef<unsigned, 2> SymVersionFlagsDefs[] = {
8142 {.Names: {"Base", "BASE"}, .Value: VER_FLG_BASE},
8143 {.Names: {"Weak", "WEAK"}, .Value: VER_FLG_WEAK},
8144 {.Names: {"Info", "INFO"}, .Value: VER_FLG_INFO},
8145};
8146constexpr auto SymVersionFlags = BUILD_ENUM_STRINGS(SymVersionFlagsDefs);
8147
8148template <class ELFT>
8149void LLVMELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) {
8150 ListScope SD(W, "VersionDefinitions");
8151 if (!Sec)
8152 return;
8153
8154 Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec);
8155 if (!V) {
8156 this->reportUniqueWarning(V.takeError());
8157 return;
8158 }
8159
8160 for (const VerDef &D : *V) {
8161 DictScope Def(W, "Definition");
8162 W.printNumber(Label: "Version", Value: D.Version);
8163 W.printFlags(Label: "Flags", Value: D.Flags, Flags: EnumStrings(SymVersionFlags));
8164 W.printNumber(Label: "Index", Value: D.Ndx);
8165 W.printNumber(Label: "Hash", Value: D.Hash);
8166 W.printString(Label: "Name", Value: D.Name);
8167 W.printList(
8168 "Predecessors", D.AuxV,
8169 [](raw_ostream &OS, const VerdAux &Aux) { OS << Aux.Name.c_str(); });
8170 }
8171}
8172
8173template <class ELFT>
8174void LLVMELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) {
8175 ListScope SD(W, "VersionRequirements");
8176 if (!Sec)
8177 return;
8178
8179 Expected<std::vector<VerNeed>> V =
8180 this->Obj.getVersionDependencies(*Sec, this->WarningHandler);
8181 if (!V) {
8182 this->reportUniqueWarning(V.takeError());
8183 return;
8184 }
8185
8186 for (const VerNeed &VN : *V) {
8187 DictScope Entry(W, "Dependency");
8188 W.printNumber(Label: "Version", Value: VN.Version);
8189 W.printNumber(Label: "Count", Value: VN.Cnt);
8190 W.printString(Label: "FileName", Value: VN.File.c_str());
8191
8192 ListScope L(W, "Entries");
8193 for (const VernAux &Aux : VN.AuxV) {
8194 DictScope Entry(W, "Entry");
8195 W.printNumber(Label: "Hash", Value: Aux.Hash);
8196 W.printFlags(Label: "Flags", Value: Aux.Flags, Flags: EnumStrings(SymVersionFlags));
8197 W.printNumber(Label: "Index", Value: Aux.Other);
8198 W.printString(Label: "Name", Value: Aux.Name.c_str());
8199 }
8200 }
8201}
8202
8203template <class ELFT>
8204void LLVMELFDumper<ELFT>::printHashHistogramStats(size_t NBucket,
8205 size_t MaxChain,
8206 size_t TotalSyms,
8207 ArrayRef<size_t> Count,
8208 bool IsGnu) const {
8209 StringRef HistName = IsGnu ? "GnuHashHistogram" : "HashHistogram";
8210 StringRef BucketName = IsGnu ? "Bucket" : "Chain";
8211 StringRef ListName = IsGnu ? "Buckets" : "Chains";
8212 DictScope Outer(W, HistName);
8213 W.printNumber(Label: "TotalBuckets", Value: NBucket);
8214 ListScope Buckets(W, ListName);
8215 size_t CumulativeNonZero = 0;
8216 for (size_t I = 0; I < MaxChain; ++I) {
8217 CumulativeNonZero += Count[I] * I;
8218 DictScope Bucket(W, BucketName);
8219 W.printNumber(Label: "Length", Value: I);
8220 W.printNumber(Label: "Count", Value: Count[I]);
8221 W.printNumber(Label: "Percentage", Value: (float)(Count[I] * 100.0) / NBucket);
8222 W.printNumber(Label: "Coverage", Value: (float)(CumulativeNonZero * 100.0) / TotalSyms);
8223 }
8224}
8225
8226// Returns true if rel/rela section exists, and populates SymbolIndices.
8227// Otherwise returns false.
8228template <class ELFT>
8229static bool getSymbolIndices(const typename ELFT::Shdr *CGRelSection,
8230 const ELFFile<ELFT> &Obj,
8231 const LLVMELFDumper<ELFT> *Dumper,
8232 SmallVector<uint32_t, 128> &SymbolIndices) {
8233 if (!CGRelSection) {
8234 Dumper->reportUniqueWarning(
8235 "relocation section for a call graph section doesn't exist");
8236 return false;
8237 }
8238
8239 if (CGRelSection->sh_type == SHT_REL) {
8240 typename ELFT::RelRange CGProfileRel;
8241 Expected<typename ELFT::RelRange> CGProfileRelOrError =
8242 Obj.rels(*CGRelSection);
8243 if (!CGProfileRelOrError) {
8244 Dumper->reportUniqueWarning("unable to load relocations for "
8245 "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
8246 toString(CGProfileRelOrError.takeError()));
8247 return false;
8248 }
8249
8250 CGProfileRel = *CGProfileRelOrError;
8251 for (const typename ELFT::Rel &Rel : CGProfileRel)
8252 SymbolIndices.push_back(Elt: Rel.getSymbol(Obj.isMips64EL()));
8253 } else {
8254 // MC unconditionally produces SHT_REL, but GNU strip/objcopy may convert
8255 // the format to SHT_RELA
8256 // (https://sourceware.org/bugzilla/show_bug.cgi?id=28035)
8257 typename ELFT::RelaRange CGProfileRela;
8258 Expected<typename ELFT::RelaRange> CGProfileRelaOrError =
8259 Obj.relas(*CGRelSection);
8260 if (!CGProfileRelaOrError) {
8261 Dumper->reportUniqueWarning("unable to load relocations for "
8262 "SHT_LLVM_CALL_GRAPH_PROFILE section: " +
8263 toString(CGProfileRelaOrError.takeError()));
8264 return false;
8265 }
8266
8267 CGProfileRela = *CGProfileRelaOrError;
8268 for (const typename ELFT::Rela &Rela : CGProfileRela)
8269 SymbolIndices.push_back(Elt: Rela.getSymbol(Obj.isMips64EL()));
8270 }
8271
8272 return true;
8273}
8274
8275template <class ELFT> void LLVMELFDumper<ELFT>::printCGProfile() {
8276 auto IsMatch = [](const Elf_Shdr &Sec) -> bool {
8277 return Sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE;
8278 };
8279
8280 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SecToRelocMapOrErr =
8281 this->Obj.getSectionAndRelocations(IsMatch);
8282 if (!SecToRelocMapOrErr) {
8283 this->reportUniqueWarning("unable to get CG Profile section(s): " +
8284 toString(SecToRelocMapOrErr.takeError()));
8285 return;
8286 }
8287
8288 for (const auto &CGMapEntry : *SecToRelocMapOrErr) {
8289 const Elf_Shdr *CGSection = CGMapEntry.first;
8290 const Elf_Shdr *CGRelSection = CGMapEntry.second;
8291
8292 Expected<ArrayRef<Elf_CGProfile>> CGProfileOrErr =
8293 this->Obj.template getSectionContentsAsArray<Elf_CGProfile>(*CGSection);
8294 if (!CGProfileOrErr) {
8295 this->reportUniqueWarning(
8296 "unable to load the SHT_LLVM_CALL_GRAPH_PROFILE section: " +
8297 toString(CGProfileOrErr.takeError()));
8298 return;
8299 }
8300
8301 SmallVector<uint32_t, 128> SymbolIndices;
8302 bool UseReloc =
8303 getSymbolIndices<ELFT>(CGRelSection, this->Obj, this, SymbolIndices);
8304 if (UseReloc && SymbolIndices.size() != CGProfileOrErr->size() * 2) {
8305 this->reportUniqueWarning(
8306 "number of from/to pairs does not match number of frequencies");
8307 UseReloc = false;
8308 }
8309
8310 ListScope L(W, "CGProfile");
8311 for (uint32_t I = 0, Size = CGProfileOrErr->size(); I != Size; ++I) {
8312 const Elf_CGProfile &CGPE = (*CGProfileOrErr)[I];
8313 DictScope D(W, "CGProfileEntry");
8314 if (UseReloc) {
8315 uint32_t From = SymbolIndices[I * 2];
8316 uint32_t To = SymbolIndices[I * 2 + 1];
8317 W.printNumber("From", this->getStaticSymbolName(From), From);
8318 W.printNumber("To", this->getStaticSymbolName(To), To);
8319 }
8320 W.printNumber("Weight", CGPE.cgp_weight);
8321 }
8322 }
8323}
8324
8325template <class ELFT> void LLVMELFDumper<ELFT>::printCallGraphInfo() {
8326 // Call graph section is of type SHT_LLVM_CALL_GRAPH. Typically named
8327 // ".llvm.callgraph". First fetch the section by its type.
8328 using Elf_Shdr = typename ELFT::Shdr;
8329 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> MapOrErr =
8330 this->Obj.getSectionAndRelocations([](const Elf_Shdr &Sec) {
8331 return Sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH;
8332 });
8333 if (!MapOrErr) {
8334 reportWarning(createError("unable to read SHT_LLVM_CALL_GRAPH section: " +
8335 toString(MapOrErr.takeError())),
8336 this->FileName);
8337 return;
8338 }
8339 if (MapOrErr->empty()) {
8340 reportWarning(createError(Err: "no SHT_LLVM_CALL_GRAPH section found"),
8341 this->FileName);
8342 return;
8343 }
8344
8345 std::unique_ptr<ListScope> CGI;
8346 for (const auto &CGMapEntry : *MapOrErr) {
8347 const Elf_Shdr *CGSection = CGMapEntry.first;
8348 const Elf_Shdr *CGRelSection = CGMapEntry.second;
8349
8350 SmallVector<FunctionCallGraphInfo, 16> FuncCGInfos =
8351 this->processCallGraphSection(CGSection);
8352 if (FuncCGInfos.empty())
8353 continue;
8354
8355 std::vector<Relocation<ELFT>> Relocations;
8356 const Elf_Shdr *RelocSymTab = nullptr;
8357 if (this->Obj.getHeader().e_type == ELF::ET_REL) {
8358 if (CGRelSection) {
8359 Expected<const typename ELFT::Shdr *> SymtabOrErr =
8360 this->Obj.getSection(CGRelSection->sh_link);
8361 if (!SymtabOrErr) {
8362 reportWarning(createError("invalid section linked to " +
8363 this->describe(*CGRelSection) + ": " +
8364 toString(SymtabOrErr.takeError())),
8365 this->FileName);
8366 return;
8367 }
8368 RelocSymTab = *SymtabOrErr;
8369 this->forEachRelocationDo(*CGRelSection, [&](const auto &R, ...) {
8370 Relocations.push_back(R);
8371 });
8372 llvm::stable_sort(Relocations, [](const auto &LHS, const auto &RHS) {
8373 return LHS.Offset < RHS.Offset;
8374 });
8375 }
8376 }
8377
8378 auto GetFunctionNames = [&](uint64_t FuncAddr) {
8379 SmallVector<uint32_t> FuncSymIndexes =
8380 this->getSymbolIndexesForFunctionAddress(FuncAddr, std::nullopt);
8381 SmallVector<std::string> FuncSymNames;
8382 FuncSymNames.reserve(N: FuncSymIndexes.size());
8383 for (uint32_t Index : FuncSymIndexes)
8384 FuncSymNames.push_back(this->getStaticSymbolName(Index));
8385 return FuncSymNames;
8386 };
8387
8388 auto PrintNonRelocatableFuncSymbol = [&](uint64_t FuncEntryPC) {
8389 SmallVector<std::string> FuncSymNames = GetFunctionNames(FuncEntryPC);
8390 if (!FuncSymNames.empty())
8391 W.printList(Label: "Names", List: FuncSymNames);
8392 W.printHex(Label: "Address", Value: FuncEntryPC);
8393 };
8394
8395 auto PrintRelocatableFuncSymbol = [&](uint64_t RelocOffset) {
8396 auto R = llvm::find_if(Relocations, [&](const Relocation<ELFT> &R) {
8397 return R.Offset == RelocOffset;
8398 });
8399 if (R == Relocations.end()) {
8400 this->reportUniqueWarning("missing relocation for symbol at offset " +
8401 Twine(RelocOffset));
8402 return;
8403 }
8404 Expected<RelSymbol<ELFT>> RelSymOrErr =
8405 this->getRelocationTarget(*R, RelocSymTab);
8406 if (!RelSymOrErr) {
8407 this->reportUniqueWarning(RelSymOrErr.takeError());
8408 return;
8409 }
8410 W.printString("Name", RelSymOrErr->Name);
8411 };
8412
8413 auto PrintFunc = [&](uint64_t FuncPC) {
8414 uint64_t FuncEntryPC = FuncPC;
8415 // In ARM thumb mode the LSB of the function pointer is set to 1. Since
8416 // this detail is unnecessary in call graph reconstruction, we are
8417 // clearing this bit to facilitate tooling.
8418 if (this->Obj.getHeader().e_machine == ELF::EM_ARM)
8419 FuncEntryPC = FuncPC & ~1;
8420 if (this->Obj.getHeader().e_type == ELF::ET_REL)
8421 PrintRelocatableFuncSymbol(FuncEntryPC);
8422 else
8423 PrintNonRelocatableFuncSymbol(FuncEntryPC);
8424 };
8425 if (!CGI)
8426 CGI = std::make_unique<ListScope>(args&: W, args: "CallGraph");
8427 for (const FunctionCallGraphInfo &CGInfo : FuncCGInfos) {
8428 DictScope D(W, "Function");
8429 PrintFunc(CGInfo.FunctionAddress);
8430 W.printNumber(Label: "Version", Value: CGInfo.FormatVersionNumber);
8431 W.printBoolean(Label: "IsIndirectTarget", Value: CGInfo.IsIndirectTarget);
8432 W.printHex(Label: "TypeID", Value: CGInfo.FunctionTypeID);
8433 W.printNumber(Label: "NumDirectCallees", Value: CGInfo.DirectCallees.size());
8434 {
8435 ListScope DCs(W, "DirectCallees");
8436 for (uint64_t CalleePC : CGInfo.DirectCallees) {
8437 DictScope D(W);
8438 PrintFunc(CalleePC);
8439 }
8440 }
8441 W.printNumber(Label: "NumIndirectTargetTypeIDs", Value: CGInfo.IndirectTypeIDs.size());
8442 SmallVector<uint64_t, 4> IndirectTypeIDsList(
8443 CGInfo.IndirectTypeIDs.begin(), CGInfo.IndirectTypeIDs.end());
8444 W.printHexList(Label: "IndirectTypeIDs", List: ArrayRef(IndirectTypeIDsList));
8445 }
8446 }
8447}
8448
8449template <class ELFT>
8450void LLVMELFDumper<ELFT>::printBBAddrMaps(bool PrettyPGOAnalysis) {
8451 bool IsRelocatable = this->Obj.getHeader().e_type == ELF::ET_REL;
8452 using Elf_Shdr = typename ELFT::Shdr;
8453 auto IsMatch = [](const Elf_Shdr &Sec) -> bool {
8454 return Sec.sh_type == ELF::SHT_LLVM_BB_ADDR_MAP;
8455 };
8456 Expected<MapVector<const Elf_Shdr *, const Elf_Shdr *>> SecRelocMapOrErr =
8457 this->Obj.getSectionAndRelocations(IsMatch);
8458 if (!SecRelocMapOrErr) {
8459 this->reportUniqueWarning(
8460 "failed to get SHT_LLVM_BB_ADDR_MAP section(s): " +
8461 toString(SecRelocMapOrErr.takeError()));
8462 return;
8463 }
8464 for (auto const &[Sec, RelocSec] : *SecRelocMapOrErr) {
8465 std::optional<const Elf_Shdr *> FunctionSec;
8466 if (IsRelocatable)
8467 FunctionSec =
8468 unwrapOrError(this->FileName, this->Obj.getSection(Sec->sh_link));
8469 ListScope L(W, "BBAddrMap");
8470 if (IsRelocatable && !RelocSec) {
8471 this->reportUniqueWarning("unable to get relocation section for " +
8472 this->describe(*Sec));
8473 continue;
8474 }
8475 std::vector<PGOAnalysisMap> PGOAnalyses;
8476 Expected<std::vector<BBAddrMap>> BBAddrMapOrErr =
8477 this->Obj.decodeBBAddrMap(*Sec, RelocSec, &PGOAnalyses);
8478 if (!BBAddrMapOrErr) {
8479 this->reportUniqueWarning("unable to dump BB addr map section: " +
8480 toString(E: BBAddrMapOrErr.takeError()));
8481 continue;
8482 }
8483 for (const auto &[AM, PAM] : zip_equal(t&: *BBAddrMapOrErr, u&: PGOAnalyses)) {
8484 DictScope D(W, "Function");
8485 W.printHex(Label: "At", Value: AM.getFunctionAddress());
8486 SmallVector<uint32_t> FuncSymIndex =
8487 this->getSymbolIndexesForFunctionAddress(AM.getFunctionAddress(),
8488 FunctionSec);
8489 std::string FuncName = "<?>";
8490 if (FuncSymIndex.empty())
8491 this->reportUniqueWarning(
8492 "could not identify function symbol for address (0x" +
8493 Twine::utohexstr(Val: AM.getFunctionAddress()) + ") in " +
8494 this->describe(*Sec));
8495 else
8496 FuncName = this->getStaticSymbolName(FuncSymIndex.front());
8497 W.printString(Label: "Name", Value: FuncName);
8498 {
8499 ListScope BBRL(W, "BB Ranges");
8500 for (const BBAddrMap::BBRangeEntry &BBR : AM.BBRanges) {
8501 DictScope BBRD(W);
8502 W.printHex(Label: "Base Address", Value: BBR.BaseAddress);
8503 ListScope BBEL(W, "BB Entries");
8504 for (const BBAddrMap::BBEntry &BBE : BBR.BBEntries) {
8505 DictScope BBED(W);
8506 W.printNumber(Label: "ID", Value: BBE.ID);
8507 W.printHex(Label: "Offset", Value: BBE.Offset);
8508 if (!BBE.CallsiteEndOffsets.empty())
8509 W.printList(Label: "Callsite End Offsets", List: BBE.CallsiteEndOffsets);
8510 if (PAM.FeatEnable.BBHash)
8511 W.printHex(Label: "Hash", Value: BBE.Hash);
8512 W.printHex(Label: "Size", Value: BBE.Size);
8513 W.printBoolean(Label: "HasReturn", Value: BBE.hasReturn());
8514 W.printBoolean(Label: "HasTailCall", Value: BBE.hasTailCall());
8515 W.printBoolean(Label: "IsEHPad", Value: BBE.isEHPad());
8516 W.printBoolean(Label: "CanFallThrough", Value: BBE.canFallThrough());
8517 W.printBoolean(Label: "HasIndirectBranch", Value: BBE.hasIndirectBranch());
8518 }
8519 }
8520 }
8521
8522 if (PAM.FeatEnable.hasPGOAnalysis()) {
8523 DictScope PD(W, "PGO analyses");
8524
8525 if (PAM.FeatEnable.FuncEntryCount)
8526 W.printNumber(Label: "FuncEntryCount", Value: PAM.FuncEntryCount);
8527
8528 if (PAM.FeatEnable.hasPGOAnalysisBBData()) {
8529 ListScope L(W, "PGO BB entries");
8530 for (const PGOAnalysisMap::PGOBBEntry &PBBE : PAM.BBEntries) {
8531 DictScope L(W);
8532
8533 if (PAM.FeatEnable.BBFreq) {
8534 if (PrettyPGOAnalysis) {
8535 std::string BlockFreqStr;
8536 raw_string_ostream SS(BlockFreqStr);
8537 printRelativeBlockFreq(OS&: SS, EntryFreq: PAM.BBEntries.front().BlockFreq,
8538 Freq: PBBE.BlockFreq);
8539 W.printString(Label: "Frequency", Value: BlockFreqStr);
8540 } else {
8541 W.printNumber(Label: "Frequency", Value: PBBE.BlockFreq.getFrequency());
8542 }
8543 if (PAM.FeatEnable.PostLinkCfg)
8544 W.printNumber(Label: "PostLink Frequency", Value: PBBE.PostLinkBlockFreq);
8545 }
8546
8547 if (PAM.FeatEnable.BrProb) {
8548 ListScope L(W, "Successors");
8549 for (const auto &Succ : PBBE.Successors) {
8550 DictScope L(W);
8551 W.printNumber(Label: "ID", Value: Succ.ID);
8552 if (PrettyPGOAnalysis) {
8553 W.printObject(Label: "Probability", Value: Succ.Prob);
8554 } else {
8555 W.printHex(Label: "Probability", Value: Succ.Prob.getNumerator());
8556 }
8557 if (PAM.FeatEnable.PostLinkCfg)
8558 W.printNumber(Label: "PostLink Probability", Value: Succ.PostLinkFreq);
8559 }
8560 }
8561 }
8562 }
8563 }
8564 }
8565 }
8566}
8567
8568template <class ELFT> void LLVMELFDumper<ELFT>::printAddrsig() {
8569 ListScope L(W, "Addrsig");
8570 if (!this->DotAddrsigSec)
8571 return;
8572
8573 Expected<std::vector<uint64_t>> SymsOrErr =
8574 decodeAddrsigSection(this->Obj, *this->DotAddrsigSec);
8575 if (!SymsOrErr) {
8576 this->reportUniqueWarning(SymsOrErr.takeError());
8577 return;
8578 }
8579
8580 for (uint64_t Sym : *SymsOrErr)
8581 W.printNumber("Sym", this->getStaticSymbolName(Sym), Sym);
8582}
8583
8584template <typename ELFT>
8585static bool printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
8586 ScopedPrinter &W,
8587 typename ELFT::Half EMachine) {
8588 // Return true if we were able to pretty-print the note, false otherwise.
8589 switch (NoteType) {
8590 default:
8591 return false;
8592 case ELF::NT_GNU_ABI_TAG: {
8593 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc);
8594 if (!AbiTag.IsValid) {
8595 W.printString(Label: "ABI", Value: "<corrupt GNU_ABI_TAG>");
8596 return false;
8597 } else {
8598 W.printString(Label: "OS", Value: AbiTag.OSName);
8599 W.printString(Label: "ABI", Value: AbiTag.ABI);
8600 }
8601 break;
8602 }
8603 case ELF::NT_GNU_BUILD_ID: {
8604 W.printString(Label: "Build ID", Value: getGNUBuildId(Desc));
8605 break;
8606 }
8607 case ELF::NT_GNU_GOLD_VERSION:
8608 W.printString(Label: "Version", Value: getDescAsStringRef(Desc));
8609 break;
8610 case ELF::NT_GNU_PROPERTY_TYPE_0:
8611 ListScope D(W, "Property");
8612 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc, EMachine))
8613 W.printString(Value: Property);
8614 break;
8615 }
8616 return true;
8617}
8618
8619static bool printAndroidNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc,
8620 ScopedPrinter &W) {
8621 // Return true if we were able to pretty-print the note, false otherwise.
8622 AndroidNoteProperties Props = getAndroidNoteProperties(NoteType, Desc);
8623 if (Props.empty())
8624 return false;
8625 for (const auto &KV : Props)
8626 W.printString(Label: KV.first, Value: KV.second);
8627 return true;
8628}
8629
8630template <class ELFT>
8631void LLVMELFDumper<ELFT>::printMemtag(
8632 const ArrayRef<std::pair<std::string, std::string>> DynamicEntries,
8633 const ArrayRef<uint8_t> AndroidNoteDesc,
8634 const ArrayRef<std::pair<uint64_t, uint64_t>> Descriptors) {
8635 {
8636 ListScope L(W, "Memtag Dynamic Entries:");
8637 if (DynamicEntries.empty())
8638 W.printString(Value: "< none found >");
8639 for (const auto &DynamicEntryKV : DynamicEntries)
8640 W.printString(Label: DynamicEntryKV.first, Value: DynamicEntryKV.second);
8641 }
8642
8643 if (!AndroidNoteDesc.empty()) {
8644 ListScope L(W, "Memtag Android Note:");
8645 printAndroidNoteLLVMStyle(NoteType: ELF::NT_ANDROID_TYPE_MEMTAG, Desc: AndroidNoteDesc, W);
8646 }
8647
8648 if (Descriptors.empty())
8649 return;
8650
8651 {
8652 ListScope L(W, "Memtag Global Descriptors:");
8653 for (const auto &[Addr, BytesToTag] : Descriptors) {
8654 W.printHex(Label: "0x" + utohexstr(X: Addr, /*LowerCase=*/true), Value: BytesToTag);
8655 }
8656 }
8657}
8658
8659template <typename ELFT>
8660static bool printLLVMOMPOFFLOADNoteLLVMStyle(uint32_t NoteType,
8661 ArrayRef<uint8_t> Desc,
8662 ScopedPrinter &W) {
8663 switch (NoteType) {
8664 default:
8665 return false;
8666 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION:
8667 W.printString(Label: "Version", Value: getDescAsStringRef(Desc));
8668 break;
8669 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER:
8670 W.printString(Label: "Producer", Value: getDescAsStringRef(Desc));
8671 break;
8672 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION:
8673 W.printString(Label: "Producer version", Value: getDescAsStringRef(Desc));
8674 break;
8675 }
8676 return true;
8677}
8678
8679static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) {
8680 W.printNumber(Label: "Page Size", Value: Note.PageSize);
8681 ListScope D(W, "Mappings");
8682 for (const CoreFileMapping &Mapping : Note.Mappings) {
8683 DictScope D(W);
8684 W.printHex(Label: "Start", Value: Mapping.Start);
8685 W.printHex(Label: "End", Value: Mapping.End);
8686 W.printHex(Label: "Offset", Value: Mapping.Offset);
8687 W.printString(Label: "Filename", Value: Mapping.Filename);
8688 }
8689}
8690
8691template <class ELFT> void LLVMELFDumper<ELFT>::printNotes() {
8692 ListScope L(W, "NoteSections");
8693
8694 std::unique_ptr<DictScope> NoteSectionScope;
8695 std::unique_ptr<ListScope> NotesScope;
8696 size_t Align = 0;
8697 auto StartNotes = [&](std::optional<StringRef> SecName,
8698 const typename ELFT::Off Offset,
8699 const typename ELFT::Addr Size, size_t Al) {
8700 Align = std::max<size_t>(a: Al, b: 4);
8701 NoteSectionScope = std::make_unique<DictScope>(args&: W, args: "NoteSection");
8702 W.printString(Label: "Name", Value: SecName ? *SecName : "<?>");
8703 W.printHex("Offset", Offset);
8704 W.printHex("Size", Size);
8705 NotesScope = std::make_unique<ListScope>(args&: W, args: "Notes");
8706 };
8707
8708 auto EndNotes = [&] {
8709 NotesScope.reset();
8710 NoteSectionScope.reset();
8711 };
8712
8713 auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error {
8714 DictScope D2(W);
8715 StringRef Name = Note.getName();
8716 ArrayRef<uint8_t> Descriptor = Note.getDesc(Align);
8717 Elf_Word Type = Note.getType();
8718
8719 // Print the note owner/type.
8720 W.printString(Label: "Owner", Value: Name);
8721 W.printHex(Label: "Data size", Value: Descriptor.size());
8722
8723 StringRef NoteType =
8724 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type);
8725 if (!NoteType.empty())
8726 W.printString(Label: "Type", Value: NoteType);
8727 else
8728 W.printString("Type",
8729 "Unknown (" + to_string(format_hex(Type, 10)) + ")");
8730
8731 const typename ELFT::Half EMachine = this->Obj.getHeader().e_machine;
8732 // Print the description, or fallback to printing raw bytes for unknown
8733 // owners/if we fail to pretty-print the contents.
8734 if (Name == "GNU") {
8735 if (printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W, EMachine))
8736 return Error::success();
8737 } else if (Name == "FreeBSD") {
8738 if (std::optional<FreeBSDNote> N =
8739 getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) {
8740 W.printString(Label: N->Type, Value: N->Value);
8741 return Error::success();
8742 }
8743 } else if (Name == "AMD") {
8744 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor);
8745 if (!N.Type.empty()) {
8746 W.printString(Label: N.Type, Value: N.Value);
8747 return Error::success();
8748 }
8749 } else if (Name == "AMDGPU") {
8750 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor);
8751 if (!N.Type.empty()) {
8752 W.printString(Label: N.Type, Value: N.Value);
8753 return Error::success();
8754 }
8755 } else if (Name == "LLVMOMPOFFLOAD") {
8756 if (printLLVMOMPOFFLOADNoteLLVMStyle<ELFT>(Type, Descriptor, W))
8757 return Error::success();
8758 } else if (Name == "CORE") {
8759 if (Type == ELF::NT_FILE) {
8760 DataExtractor DescExtractor(Descriptor, ELFT::Endianness ==
8761 llvm::endianness::little);
8762 if (Expected<CoreNote> N =
8763 readCoreNote(Desc: DescExtractor, AddressSize: sizeof(Elf_Addr))) {
8764 printCoreNoteLLVMStyle(Note: *N, W);
8765 return Error::success();
8766 } else {
8767 return N.takeError();
8768 }
8769 }
8770 } else if (Name == "Android") {
8771 if (printAndroidNoteLLVMStyle(Type, Descriptor, W))
8772 return Error::success();
8773 }
8774 if (!Descriptor.empty()) {
8775 W.printBinaryBlock(Label: "Description data", Value: Descriptor);
8776 }
8777 return Error::success();
8778 };
8779
8780 processNotesHelper(*this, /*StartNotesFn=*/StartNotes,
8781 /*ProcessNoteFn=*/ProcessNote, /*FinishNotesFn=*/EndNotes);
8782}
8783
8784template <class ELFT> void LLVMELFDumper<ELFT>::printELFLinkerOptions() {
8785 ListScope L(W, "LinkerOptions");
8786
8787 unsigned I = -1;
8788 for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) {
8789 ++I;
8790 if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS)
8791 continue;
8792
8793 Expected<ArrayRef<uint8_t>> ContentsOrErr =
8794 this->Obj.getSectionContents(Shdr);
8795 if (!ContentsOrErr) {
8796 this->reportUniqueWarning("unable to read the content of the "
8797 "SHT_LLVM_LINKER_OPTIONS section: " +
8798 toString(E: ContentsOrErr.takeError()));
8799 continue;
8800 }
8801 if (ContentsOrErr->empty())
8802 continue;
8803
8804 if (ContentsOrErr->back() != 0) {
8805 this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " +
8806 Twine(I) +
8807 " is broken: the "
8808 "content is not null-terminated");
8809 continue;
8810 }
8811
8812 SmallVector<StringRef, 16> Strings;
8813 toStringRef(Input: ContentsOrErr->drop_back()).split(A&: Strings, Separator: '\0');
8814 if (Strings.size() % 2 != 0) {
8815 this->reportUniqueWarning(
8816 "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) +
8817 " is broken: an incomplete "
8818 "key-value pair was found. The last possible key was: \"" +
8819 Strings.back() + "\"");
8820 continue;
8821 }
8822
8823 for (size_t I = 0; I < Strings.size(); I += 2)
8824 W.printString(Label: Strings[I], Value: Strings[I + 1]);
8825 }
8826}
8827
8828template <class ELFT> void LLVMELFDumper<ELFT>::printDependentLibs() {
8829 ListScope L(W, "DependentLibs");
8830 this->printDependentLibsHelper(
8831 [](const Elf_Shdr &) {},
8832 [this](StringRef Lib, uint64_t) { W.printString(Value: Lib); });
8833}
8834
8835template <class ELFT> void LLVMELFDumper<ELFT>::printStackSizes() {
8836 ListScope L(W, "StackSizes");
8837 if (this->Obj.getHeader().e_type == ELF::ET_REL)
8838 this->printRelocatableStackSizes([]() {});
8839 else
8840 this->printNonRelocatableStackSizes([]() {});
8841}
8842
8843template <class ELFT>
8844void LLVMELFDumper<ELFT>::printStackSizeEntry(uint64_t Size,
8845 ArrayRef<std::string> FuncNames) {
8846 DictScope D(W, "Entry");
8847 W.printList(Label: "Functions", List: FuncNames);
8848 W.printHex(Label: "Size", Value: Size);
8849}
8850
8851template <class ELFT>
8852void LLVMELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) {
8853 auto PrintEntry = [&](const Elf_Addr *E) {
8854 W.printHex("Address", Parser.getGotAddress(E));
8855 W.printNumber("Access", Parser.getGotOffset(E));
8856 W.printHex("Initial", *E);
8857 };
8858
8859 DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT");
8860
8861 W.printHex("Canonical gp value", Parser.getGp());
8862 {
8863 ListScope RS(W, "Reserved entries");
8864 {
8865 DictScope D(W, "Entry");
8866 PrintEntry(Parser.getGotLazyResolver());
8867 W.printString(Label: "Purpose", Value: StringRef("Lazy resolver"));
8868 }
8869
8870 if (Parser.getGotModulePointer()) {
8871 DictScope D(W, "Entry");
8872 PrintEntry(Parser.getGotModulePointer());
8873 W.printString(Label: "Purpose", Value: StringRef("Module pointer (GNU extension)"));
8874 }
8875 }
8876 {
8877 ListScope LS(W, "Local entries");
8878 for (auto &E : Parser.getLocalEntries()) {
8879 DictScope D(W, "Entry");
8880 PrintEntry(&E);
8881 }
8882 }
8883
8884 if (Parser.IsStatic)
8885 return;
8886
8887 {
8888 ListScope GS(W, "Global entries");
8889 for (auto &E : Parser.getGlobalEntries()) {
8890 DictScope D(W, "Entry");
8891
8892 PrintEntry(&E);
8893
8894 const Elf_Sym &Sym = *Parser.getGotSym(&E);
8895 W.printHex("Value", Sym.st_value);
8896 W.printEnum("Type", Sym.getType(), getElfSymbolTypes());
8897
8898 const unsigned SymIndex = &Sym - this->dynamic_symbols().begin();
8899 DataRegion<Elf_Word> ShndxTable(
8900 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
8901 printSymbolSection(Symbol: Sym, SymIndex, ShndxTable);
8902
8903 std::string SymName = this->getFullSymbolName(
8904 Sym, SymIndex, ShndxTable, this->DynamicStringTable, true);
8905 W.printNumber("Name", SymName, Sym.st_name);
8906 }
8907 }
8908
8909 W.printNumber(Label: "Number of TLS and multi-GOT entries",
8910 Value: uint64_t(Parser.getOtherEntries().size()));
8911}
8912
8913template <class ELFT>
8914void LLVMELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) {
8915 auto PrintEntry = [&](const Elf_Addr *E) {
8916 W.printHex("Address", Parser.getPltAddress(E));
8917 W.printHex("Initial", *E);
8918 };
8919
8920 DictScope GS(W, "PLT GOT");
8921
8922 {
8923 ListScope RS(W, "Reserved entries");
8924 {
8925 DictScope D(W, "Entry");
8926 PrintEntry(Parser.getPltLazyResolver());
8927 W.printString(Label: "Purpose", Value: StringRef("PLT lazy resolver"));
8928 }
8929
8930 if (auto E = Parser.getPltModulePointer()) {
8931 DictScope D(W, "Entry");
8932 PrintEntry(E);
8933 W.printString(Label: "Purpose", Value: StringRef("Module pointer"));
8934 }
8935 }
8936 {
8937 ListScope LS(W, "Entries");
8938 DataRegion<Elf_Word> ShndxTable(
8939 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end());
8940 for (auto &E : Parser.getPltEntries()) {
8941 DictScope D(W, "Entry");
8942 PrintEntry(&E);
8943
8944 const Elf_Sym &Sym = *Parser.getPltSym(&E);
8945 W.printHex("Value", Sym.st_value);
8946 W.printEnum("Type", Sym.getType(), getElfSymbolTypes());
8947 printSymbolSection(Symbol: Sym, SymIndex: &Sym - this->dynamic_symbols().begin(),
8948 ShndxTable);
8949
8950 const Elf_Sym *FirstSym = cantFail(
8951 this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0));
8952 std::string SymName = this->getFullSymbolName(
8953 Sym, &Sym - FirstSym, ShndxTable, Parser.getPltStrTable(), true);
8954 W.printNumber("Name", SymName, Sym.st_name);
8955 }
8956 }
8957}
8958
8959template <class ELFT> void LLVMELFDumper<ELFT>::printMipsABIFlags() {
8960 const Elf_Mips_ABIFlags<ELFT> *Flags;
8961 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr =
8962 getMipsAbiFlagsSection(*this)) {
8963 Flags = *SecOrErr;
8964 if (!Flags) {
8965 W.startLine() << "There is no .MIPS.abiflags section in the file.\n";
8966 return;
8967 }
8968 } else {
8969 this->reportUniqueWarning(SecOrErr.takeError());
8970 return;
8971 }
8972
8973 raw_ostream &OS = W.getOStream();
8974 DictScope GS(W, "MIPS ABI Flags");
8975
8976 W.printNumber("Version", Flags->version);
8977 W.startLine() << "ISA: ";
8978 if (Flags->isa_rev <= 1)
8979 OS << format("MIPS%u", Flags->isa_level);
8980 else
8981 OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev);
8982 OS << "\n";
8983 W.printEnum("ISA Extension", Flags->isa_ext, EnumStrings(ElfMipsISAExtType));
8984 W.printFlags("ASEs", Flags->ases, EnumStrings(ElfMipsASEFlags));
8985 W.printEnum("FP ABI", Flags->fp_abi, EnumStrings(ElfMipsFpABIType));
8986 W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size));
8987 W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size));
8988 W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size));
8989 W.printFlags("Flags 1", Flags->flags1, EnumStrings(ElfMipsFlags1));
8990 W.printHex("Flags 2", Flags->flags2);
8991}
8992
8993template <class ELFT>
8994void JSONELFDumper<ELFT>::printFileSummary(StringRef FileStr, ObjectFile &Obj,
8995 ArrayRef<std::string> InputFilenames,
8996 const Archive *A) {
8997 FileScope = std::make_unique<DictScope>(this->W);
8998 DictScope D(this->W, "FileSummary");
8999 this->W.printString("File", FileStr);
9000 this->W.printString("Format", Obj.getFileFormatName());
9001 this->W.printString("Arch", Triple::getArchTypeName(Kind: Obj.getArch()));
9002 this->W.printString(
9003 "AddressSize",
9004 std::string(formatv(Fmt: "{0}bit", Vals: 8 * Obj.getBytesInAddress())));
9005 this->printLoadName();
9006}
9007
9008template <class ELFT>
9009void JSONELFDumper<ELFT>::printZeroSymbolOtherField(
9010 const Elf_Sym &Symbol) const {
9011 // We want the JSON format to be uniform, since it is machine readable, so
9012 // always print the `Other` field the same way.
9013 this->printSymbolOtherField(Symbol);
9014}
9015
9016template <class ELFT>
9017void JSONELFDumper<ELFT>::printDefaultRelRelaReloc(const Relocation<ELFT> &R,
9018 StringRef SymbolName,
9019 StringRef RelocName) {
9020 this->printExpandedRelRelaReloc(R, SymbolName, RelocName);
9021}
9022
9023template <class ELFT>
9024void JSONELFDumper<ELFT>::printRelocationSectionInfo(const Elf_Shdr &Sec,
9025 StringRef Name,
9026 const unsigned SecNdx) {
9027 DictScope Group(this->W);
9028 this->W.printNumber("SectionIndex", SecNdx);
9029 ListScope D(this->W, "Relocs");
9030 this->printRelocationsHelper(Sec);
9031}
9032
9033template <class ELFT>
9034std::string JSONELFDumper<ELFT>::getGroupSectionHeaderName() const {
9035 return "GroupSections";
9036}
9037
9038template <class ELFT>
9039void JSONELFDumper<ELFT>::printSectionGroupMembers(StringRef Name,
9040 uint64_t Idx) const {
9041 DictScope Grp(this->W);
9042 this->W.printString("Name", Name);
9043 this->W.printNumber("Index", Idx);
9044}
9045
9046template <class ELFT> void JSONELFDumper<ELFT>::printEmptyGroupMessage() const {
9047 // JSON output does not need to print anything for empty groups
9048}
9049