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

source code of llvm/tools/llvm-readobj/ELFDumper.cpp