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