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