Debian Codegraph @

llvm/tools/llvm-readobj/ELFDumper.cpp

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