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