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