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