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