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