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