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