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