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 printAddrsig() override; 554 void printNotes() override; 555 void printELFLinkerOptions() override; 556 void printStackSizes() override; 557 558 private: 559 void printHashHistogram(const Elf_Hash &HashTable); 560 void printGnuHashHistogram(const Elf_GnuHash &GnuHashTable); 561 void printHashTableSymbols(const Elf_Hash &HashTable); 562 void printGnuHashTableSymbols(const Elf_GnuHash &GnuHashTable); 563 564 struct Field { 565 std::string Str; 566 unsigned Column; 567 568 Field(StringRef S, unsigned Col) : Str(std::string(S)), Column(Col) {} 569 Field(unsigned Col) : Column(Col) {} 570 }; 571 572 template <typename T, typename TEnum> 573 std::string printEnum(T Value, ArrayRef<EnumEntry<TEnum>> EnumValues) const { 574 for (const EnumEntry<TEnum> &EnumItem : EnumValues) 575 if (EnumItem.Value == Value) 576 return std::string(EnumItem.AltName); 577 return to_hexString(Value, false); 578 } 579 580 template <typename T, typename TEnum> 581 std::string printFlags(T Value, ArrayRef<EnumEntry<TEnum>> EnumValues, 582 TEnum EnumMask1 = {}, TEnum EnumMask2 = {}, 583 TEnum EnumMask3 = {}) const { 584 std::string Str; 585 for (const EnumEntry<TEnum> &Flag : EnumValues) { 586 if (Flag.Value == 0) 587 continue; 588 589 TEnum EnumMask{}; 590 if (Flag.Value & EnumMask1) 591 EnumMask = EnumMask1; 592 else if (Flag.Value & EnumMask2) 593 EnumMask = EnumMask2; 594 else if (Flag.Value & EnumMask3) 595 EnumMask = EnumMask3; 596 bool IsEnum = (Flag.Value & EnumMask) != 0; 597 if ((!IsEnum && (Value & Flag.Value) == Flag.Value) || 598 (IsEnum && (Value & EnumMask) == Flag.Value)) { 599 if (!Str.empty()) 600 Str += ", "; 601 Str += Flag.AltName; 602 } 603 } 604 return Str; 605 } 606 607 formatted_raw_ostream &printField(struct Field F) const { 608 if (F.Column != 0) 609 OS.PadToColumn(F.Column); 610 OS << F.Str; 611 OS.flush(); 612 return OS; 613 } 614 void printHashedSymbol(const Elf_Sym *Sym, unsigned SymIndex, 615 DataRegion<Elf_Word> ShndxTable, StringRef StrTable, 616 uint32_t Bucket); 617 void printRelrReloc(const Elf_Relr &R) override; 618 void printRelRelaReloc(const Relocation<ELFT> &R, 619 const RelSymbol<ELFT> &RelSym) override; 620 void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex, 621 DataRegion<Elf_Word> ShndxTable, 622 Optional<StringRef> StrTable, bool IsDynamic, 623 bool NonVisibilityBitsUsed) const override; 624 void printDynamicRelocHeader(unsigned Type, StringRef Name, 625 const DynRegionInfo &Reg) override; 626 627 std::string getSymbolSectionNdx(const Elf_Sym &Symbol, unsigned SymIndex, 628 DataRegion<Elf_Word> ShndxTable) const; 629 void printProgramHeaders() override; 630 void printSectionMapping() override; 631 void printGNUVersionSectionProlog(const typename ELFT::Shdr &Sec, 632 const Twine &Label, unsigned EntriesNum); 633 634 void printStackSizeEntry(uint64_t Size, StringRef FuncName) override; 635 636 void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override; 637 void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override; 638 void printMipsABIFlags() override; 639 }; 640 641 template <typename ELFT> class LLVMELFDumper : public ELFDumper<ELFT> { 642 public: 643 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT) 644 645 LLVMELFDumper(const object::ELFObjectFile<ELFT> &ObjF, ScopedPrinter &Writer) 646 : ELFDumper<ELFT>(ObjF, Writer), W(Writer) {} 647 648 void printFileHeaders() override; 649 void printGroupSections() override; 650 void printRelocations() override; 651 void printSectionHeaders() override; 652 void printSymbols(bool PrintSymbols, bool PrintDynamicSymbols) override; 653 void printDependentLibs() override; 654 void printDynamicTable() override; 655 void printDynamicRelocations() override; 656 void printProgramHeaders(bool PrintProgramHeaders, 657 cl::boolOrDefault PrintSectionMapping) override; 658 void printVersionSymbolSection(const Elf_Shdr *Sec) override; 659 void printVersionDefinitionSection(const Elf_Shdr *Sec) override; 660 void printVersionDependencySection(const Elf_Shdr *Sec) override; 661 void printHashHistograms() override; 662 void printCGProfile() override; 663 void printAddrsig() override; 664 void printNotes() override; 665 void printELFLinkerOptions() override; 666 void printStackSizes() override; 667 668 private: 669 void printRelrReloc(const Elf_Relr &R) override; 670 void printRelRelaReloc(const Relocation<ELFT> &R, 671 const RelSymbol<ELFT> &RelSym) override; 672 673 void printSymbolSection(const Elf_Sym &Symbol, unsigned SymIndex, 674 DataRegion<Elf_Word> ShndxTable) const; 675 void printSymbol(const Elf_Sym &Symbol, unsigned SymIndex, 676 DataRegion<Elf_Word> ShndxTable, 677 Optional<StringRef> StrTable, bool IsDynamic, 678 bool /*NonVisibilityBitsUsed*/) const override; 679 void printProgramHeaders() override; 680 void printSectionMapping() override {} 681 void printStackSizeEntry(uint64_t Size, StringRef FuncName) override; 682 683 void printMipsGOT(const MipsGOTParser<ELFT> &Parser) override; 684 void printMipsPLT(const MipsGOTParser<ELFT> &Parser) override; 685 void printMipsABIFlags() override; 686 687 ScopedPrinter &W; 688 }; 689 690 } // end anonymous namespace 691 692 namespace llvm { 693 694 template <class ELFT> 695 static std::unique_ptr<ObjDumper> 696 createELFDumper(const ELFObjectFile<ELFT> &Obj, ScopedPrinter &Writer) { 697 if (opts::Output == opts::GNU) 698 return std::make_unique<GNUELFDumper<ELFT>>(Obj, Writer); 699 return std::make_unique<LLVMELFDumper<ELFT>>(Obj, Writer); 700 } 701 702 std::unique_ptr<ObjDumper> createELFDumper(const object::ELFObjectFileBase &Obj, 703 ScopedPrinter &Writer) { 704 // Little-endian 32-bit 705 if (const ELF32LEObjectFile *ELFObj = dyn_cast<ELF32LEObjectFile>(&Obj)) 706 return createELFDumper(*ELFObj, Writer); 707 708 // Big-endian 32-bit 709 if (const ELF32BEObjectFile *ELFObj = dyn_cast<ELF32BEObjectFile>(&Obj)) 710 return createELFDumper(*ELFObj, Writer); 711 712 // Little-endian 64-bit 713 if (const ELF64LEObjectFile *ELFObj = dyn_cast<ELF64LEObjectFile>(&Obj)) 714 return createELFDumper(*ELFObj, Writer); 715 716 // Big-endian 64-bit 717 return createELFDumper(*cast<ELF64BEObjectFile>(&Obj), Writer); 718 } 719 720 } // end namespace llvm 721 722 template <class ELFT> 723 Expected<SmallVector<Optional<VersionEntry>, 0> *> 724 ELFDumper<ELFT>::getVersionMap() const { 725 // If the VersionMap has already been loaded or if there is no dynamic symtab 726 // or version table, there is nothing to do. 727 if (!VersionMap.empty() || !DynSymRegion || !SymbolVersionSection) 728 return &VersionMap; 729 730 Expected<SmallVector<Optional<VersionEntry>, 0>> MapOrErr = 731 Obj.loadVersionMap(SymbolVersionNeedSection, SymbolVersionDefSection); 732 if (MapOrErr) 733 VersionMap = *MapOrErr; 734 else 735 return MapOrErr.takeError(); 736 737 return &VersionMap; 738 } 739 740 template <typename ELFT> 741 Expected<StringRef> ELFDumper<ELFT>::getSymbolVersion(const Elf_Sym &Sym, 742 bool &IsDefault) const { 743 // This is a dynamic symbol. Look in the GNU symbol version table. 744 if (!SymbolVersionSection) { 745 // No version table. 746 IsDefault = false; 747 return ""; 748 } 749 750 assert(DynSymRegion && "DynSymRegion has not been initialised"); 751 // Determine the position in the symbol table of this entry. 752 size_t EntryIndex = (reinterpret_cast<uintptr_t>(&Sym) - 753 reinterpret_cast<uintptr_t>(DynSymRegion->Addr)) / 754 sizeof(Elf_Sym); 755 756 // Get the corresponding version index entry. 757 Expected<const Elf_Versym *> EntryOrErr = 758 Obj.template getEntry<Elf_Versym>(*SymbolVersionSection, EntryIndex); 759 if (!EntryOrErr) 760 return EntryOrErr.takeError(); 761 762 unsigned Version = (*EntryOrErr)->vs_index; 763 if (Version == VER_NDX_LOCAL || Version == VER_NDX_GLOBAL) { 764 IsDefault = false; 765 return ""; 766 } 767 768 Expected<SmallVector<Optional<VersionEntry>, 0> *> MapOrErr = 769 getVersionMap(); 770 if (!MapOrErr) 771 return MapOrErr.takeError(); 772 773 return Obj.getSymbolVersionByIndex(Version, IsDefault, **MapOrErr, 774 Sym.st_shndx == ELF::SHN_UNDEF); 775 } 776 777 template <typename ELFT> 778 Expected<RelSymbol<ELFT>> 779 ELFDumper<ELFT>::getRelocationTarget(const Relocation<ELFT> &R, 780 const Elf_Shdr *SymTab) const { 781 if (R.Symbol == 0) 782 return RelSymbol<ELFT>(nullptr, ""); 783 784 Expected<const Elf_Sym *> SymOrErr = 785 Obj.template getEntry<Elf_Sym>(*SymTab, R.Symbol); 786 if (!SymOrErr) 787 return createError("unable to read an entry with index " + Twine(R.Symbol) + 788 " from " + describe(*SymTab) + ": " + 789 toString(SymOrErr.takeError())); 790 const Elf_Sym *Sym = *SymOrErr; 791 if (!Sym) 792 return RelSymbol<ELFT>(nullptr, ""); 793 794 Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(*SymTab); 795 if (!StrTableOrErr) 796 return StrTableOrErr.takeError(); 797 798 const Elf_Sym *FirstSym = 799 cantFail(Obj.template getEntry<Elf_Sym>(*SymTab, 0)); 800 std::string SymbolName = 801 getFullSymbolName(*Sym, Sym - FirstSym, getShndxTable(SymTab), 802 *StrTableOrErr, SymTab->sh_type == SHT_DYNSYM); 803 return RelSymbol<ELFT>(Sym, SymbolName); 804 } 805 806 template <typename ELFT> 807 ArrayRef<typename ELFT::Word> 808 ELFDumper<ELFT>::getShndxTable(const Elf_Shdr *Symtab) const { 809 if (Symtab) { 810 auto It = ShndxTables.find(Symtab); 811 if (It != ShndxTables.end()) 812 return It->second; 813 } 814 return {}; 815 } 816 817 static std::string maybeDemangle(StringRef Name) { 818 return opts::Demangle ? demangle(std::string(Name)) : Name.str(); 819 } 820 821 template <typename ELFT> 822 std::string ELFDumper<ELFT>::getStaticSymbolName(uint32_t Index) const { 823 auto Warn = [&](Error E) -> std::string { 824 reportUniqueWarning("unable to read the name of symbol with index " + 825 Twine(Index) + ": " + toString(std::move(E))); 826 return "<?>"; 827 }; 828 829 Expected<const typename ELFT::Sym *> SymOrErr = 830 Obj.getSymbol(DotSymtabSec, Index); 831 if (!SymOrErr) 832 return Warn(SymOrErr.takeError()); 833 834 Expected<StringRef> StrTabOrErr = Obj.getStringTableForSymtab(*DotSymtabSec); 835 if (!StrTabOrErr) 836 return Warn(StrTabOrErr.takeError()); 837 838 Expected<StringRef> NameOrErr = (*SymOrErr)->getName(*StrTabOrErr); 839 if (!NameOrErr) 840 return Warn(NameOrErr.takeError()); 841 return maybeDemangle(*NameOrErr); 842 } 843 844 template <typename ELFT> 845 std::string ELFDumper<ELFT>::getFullSymbolName(const Elf_Sym &Symbol, 846 unsigned SymIndex, 847 DataRegion<Elf_Word> ShndxTable, 848 Optional<StringRef> StrTable, 849 bool IsDynamic) const { 850 if (!StrTable) 851 return "<?>"; 852 853 std::string SymbolName; 854 if (Expected<StringRef> NameOrErr = Symbol.getName(*StrTable)) { 855 SymbolName = maybeDemangle(*NameOrErr); 856 } else { 857 reportUniqueWarning(NameOrErr.takeError()); 858 return "<?>"; 859 } 860 861 if (SymbolName.empty() && Symbol.getType() == ELF::STT_SECTION) { 862 Expected<unsigned> SectionIndex = 863 getSymbolSectionIndex(Symbol, SymIndex, ShndxTable); 864 if (!SectionIndex) { 865 reportUniqueWarning(SectionIndex.takeError()); 866 return "<?>"; 867 } 868 Expected<StringRef> NameOrErr = getSymbolSectionName(Symbol, *SectionIndex); 869 if (!NameOrErr) { 870 reportUniqueWarning(NameOrErr.takeError()); 871 return ("<section " + Twine(*SectionIndex) + ">").str(); 872 } 873 return std::string(*NameOrErr); 874 } 875 876 if (!IsDynamic) 877 return SymbolName; 878 879 bool IsDefault; 880 Expected<StringRef> VersionOrErr = getSymbolVersion(Symbol, IsDefault); 881 if (!VersionOrErr) { 882 reportUniqueWarning(VersionOrErr.takeError()); 883 return SymbolName + "@<corrupt>"; 884 } 885 886 if (!VersionOrErr->empty()) { 887 SymbolName += (IsDefault ? "@@" : "@"); 888 SymbolName += *VersionOrErr; 889 } 890 return SymbolName; 891 } 892 893 template <typename ELFT> 894 Expected<unsigned> 895 ELFDumper<ELFT>::getSymbolSectionIndex(const Elf_Sym &Symbol, unsigned SymIndex, 896 DataRegion<Elf_Word> ShndxTable) const { 897 unsigned Ndx = Symbol.st_shndx; 898 if (Ndx == SHN_XINDEX) 899 return object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, 900 ShndxTable); 901 if (Ndx != SHN_UNDEF && Ndx < SHN_LORESERVE) 902 return Ndx; 903 904 auto CreateErr = [&](const Twine &Name, Optional<unsigned> Offset = None) { 905 std::string Desc; 906 if (Offset) 907 Desc = (Name + "+0x" + Twine::utohexstr(*Offset)).str(); 908 else 909 Desc = Name.str(); 910 return createError( 911 "unable to get section index for symbol with st_shndx = 0x" + 912 Twine::utohexstr(Ndx) + " (" + Desc + ")"); 913 }; 914 915 if (Ndx >= ELF::SHN_LOPROC && Ndx <= ELF::SHN_HIPROC) 916 return CreateErr("SHN_LOPROC", Ndx - ELF::SHN_LOPROC); 917 if (Ndx >= ELF::SHN_LOOS && Ndx <= ELF::SHN_HIOS) 918 return CreateErr("SHN_LOOS", Ndx - ELF::SHN_LOOS); 919 if (Ndx == ELF::SHN_UNDEF) 920 return CreateErr("SHN_UNDEF"); 921 if (Ndx == ELF::SHN_ABS) 922 return CreateErr("SHN_ABS"); 923 if (Ndx == ELF::SHN_COMMON) 924 return CreateErr("SHN_COMMON"); 925 return CreateErr("SHN_LORESERVE", Ndx - SHN_LORESERVE); 926 } 927 928 template <typename ELFT> 929 Expected<StringRef> 930 ELFDumper<ELFT>::getSymbolSectionName(const Elf_Sym &Symbol, 931 unsigned SectionIndex) const { 932 Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(SectionIndex); 933 if (!SecOrErr) 934 return SecOrErr.takeError(); 935 return Obj.getSectionName(**SecOrErr); 936 } 937 938 template <class ELFO> 939 static const typename ELFO::Elf_Shdr * 940 findNotEmptySectionByAddress(const ELFO &Obj, StringRef FileName, 941 uint64_t Addr) { 942 for (const typename ELFO::Elf_Shdr &Shdr : cantFail(Obj.sections())) 943 if (Shdr.sh_addr == Addr && Shdr.sh_size > 0) 944 return &Shdr; 945 return nullptr; 946 } 947 948 static const EnumEntry<unsigned> ElfClass[] = { 949 {"None", "none", ELF::ELFCLASSNONE}, 950 {"32-bit", "ELF32", ELF::ELFCLASS32}, 951 {"64-bit", "ELF64", ELF::ELFCLASS64}, 952 }; 953 954 static const EnumEntry<unsigned> ElfDataEncoding[] = { 955 {"None", "none", ELF::ELFDATANONE}, 956 {"LittleEndian", "2's complement, little endian", ELF::ELFDATA2LSB}, 957 {"BigEndian", "2's complement, big endian", ELF::ELFDATA2MSB}, 958 }; 959 960 static const EnumEntry<unsigned> ElfObjectFileType[] = { 961 {"None", "NONE (none)", ELF::ET_NONE}, 962 {"Relocatable", "REL (Relocatable file)", ELF::ET_REL}, 963 {"Executable", "EXEC (Executable file)", ELF::ET_EXEC}, 964 {"SharedObject", "DYN (Shared object file)", ELF::ET_DYN}, 965 {"Core", "CORE (Core file)", ELF::ET_CORE}, 966 }; 967 968 static const EnumEntry<unsigned> ElfOSABI[] = { 969 {"SystemV", "UNIX - System V", ELF::ELFOSABI_NONE}, 970 {"HPUX", "UNIX - HP-UX", ELF::ELFOSABI_HPUX}, 971 {"NetBSD", "UNIX - NetBSD", ELF::ELFOSABI_NETBSD}, 972 {"GNU/Linux", "UNIX - GNU", ELF::ELFOSABI_LINUX}, 973 {"GNU/Hurd", "GNU/Hurd", ELF::ELFOSABI_HURD}, 974 {"Solaris", "UNIX - Solaris", ELF::ELFOSABI_SOLARIS}, 975 {"AIX", "UNIX - AIX", ELF::ELFOSABI_AIX}, 976 {"IRIX", "UNIX - IRIX", ELF::ELFOSABI_IRIX}, 977 {"FreeBSD", "UNIX - FreeBSD", ELF::ELFOSABI_FREEBSD}, 978 {"TRU64", "UNIX - TRU64", ELF::ELFOSABI_TRU64}, 979 {"Modesto", "Novell - Modesto", ELF::ELFOSABI_MODESTO}, 980 {"OpenBSD", "UNIX - OpenBSD", ELF::ELFOSABI_OPENBSD}, 981 {"OpenVMS", "VMS - OpenVMS", ELF::ELFOSABI_OPENVMS}, 982 {"NSK", "HP - Non-Stop Kernel", ELF::ELFOSABI_NSK}, 983 {"AROS", "AROS", ELF::ELFOSABI_AROS}, 984 {"FenixOS", "FenixOS", ELF::ELFOSABI_FENIXOS}, 985 {"CloudABI", "CloudABI", ELF::ELFOSABI_CLOUDABI}, 986 {"Standalone", "Standalone App", ELF::ELFOSABI_STANDALONE} 987 }; 988 989 static const EnumEntry<unsigned> AMDGPUElfOSABI[] = { 990 {"AMDGPU_HSA", "AMDGPU - HSA", ELF::ELFOSABI_AMDGPU_HSA}, 991 {"AMDGPU_PAL", "AMDGPU - PAL", ELF::ELFOSABI_AMDGPU_PAL}, 992 {"AMDGPU_MESA3D", "AMDGPU - MESA3D", ELF::ELFOSABI_AMDGPU_MESA3D} 993 }; 994 995 static const EnumEntry<unsigned> ARMElfOSABI[] = { 996 {"ARM", "ARM", ELF::ELFOSABI_ARM} 997 }; 998 999 static const EnumEntry<unsigned> C6000ElfOSABI[] = { 1000 {"C6000_ELFABI", "Bare-metal C6000", ELF::ELFOSABI_C6000_ELFABI}, 1001 {"C6000_LINUX", "Linux C6000", ELF::ELFOSABI_C6000_LINUX} 1002 }; 1003 1004 static const EnumEntry<unsigned> ElfMachineType[] = { 1005 ENUM_ENT(EM_NONE, "None"), 1006 ENUM_ENT(EM_M32, "WE32100"), 1007 ENUM_ENT(EM_SPARC, "Sparc"), 1008 ENUM_ENT(EM_386, "Intel 80386"), 1009 ENUM_ENT(EM_68K, "MC68000"), 1010 ENUM_ENT(EM_88K, "MC88000"), 1011 ENUM_ENT(EM_IAMCU, "EM_IAMCU"), 1012 ENUM_ENT(EM_860, "Intel 80860"), 1013 ENUM_ENT(EM_MIPS, "MIPS R3000"), 1014 ENUM_ENT(EM_S370, "IBM System/370"), 1015 ENUM_ENT(EM_MIPS_RS3_LE, "MIPS R3000 little-endian"), 1016 ENUM_ENT(EM_PARISC, "HPPA"), 1017 ENUM_ENT(EM_VPP500, "Fujitsu VPP500"), 1018 ENUM_ENT(EM_SPARC32PLUS, "Sparc v8+"), 1019 ENUM_ENT(EM_960, "Intel 80960"), 1020 ENUM_ENT(EM_PPC, "PowerPC"), 1021 ENUM_ENT(EM_PPC64, "PowerPC64"), 1022 ENUM_ENT(EM_S390, "IBM S/390"), 1023 ENUM_ENT(EM_SPU, "SPU"), 1024 ENUM_ENT(EM_V800, "NEC V800 series"), 1025 ENUM_ENT(EM_FR20, "Fujistsu FR20"), 1026 ENUM_ENT(EM_RH32, "TRW RH-32"), 1027 ENUM_ENT(EM_RCE, "Motorola RCE"), 1028 ENUM_ENT(EM_ARM, "ARM"), 1029 ENUM_ENT(EM_ALPHA, "EM_ALPHA"), 1030 ENUM_ENT(EM_SH, "Hitachi SH"), 1031 ENUM_ENT(EM_SPARCV9, "Sparc v9"), 1032 ENUM_ENT(EM_TRICORE, "Siemens Tricore"), 1033 ENUM_ENT(EM_ARC, "ARC"), 1034 ENUM_ENT(EM_H8_300, "Hitachi H8/300"), 1035 ENUM_ENT(EM_H8_300H, "Hitachi H8/300H"), 1036 ENUM_ENT(EM_H8S, "Hitachi H8S"), 1037 ENUM_ENT(EM_H8_500, "Hitachi H8/500"), 1038 ENUM_ENT(EM_IA_64, "Intel IA-64"), 1039 ENUM_ENT(EM_MIPS_X, "Stanford MIPS-X"), 1040 ENUM_ENT(EM_COLDFIRE, "Motorola Coldfire"), 1041 ENUM_ENT(EM_68HC12, "Motorola MC68HC12 Microcontroller"), 1042 ENUM_ENT(EM_MMA, "Fujitsu Multimedia Accelerator"), 1043 ENUM_ENT(EM_PCP, "Siemens PCP"), 1044 ENUM_ENT(EM_NCPU, "Sony nCPU embedded RISC processor"), 1045 ENUM_ENT(EM_NDR1, "Denso NDR1 microprocesspr"), 1046 ENUM_ENT(EM_STARCORE, "Motorola Star*Core processor"), 1047 ENUM_ENT(EM_ME16, "Toyota ME16 processor"), 1048 ENUM_ENT(EM_ST100, "STMicroelectronics ST100 processor"), 1049 ENUM_ENT(EM_TINYJ, "Advanced Logic Corp. TinyJ embedded processor"), 1050 ENUM_ENT(EM_X86_64, "Advanced Micro Devices X86-64"), 1051 ENUM_ENT(EM_PDSP, "Sony DSP processor"), 1052 ENUM_ENT(EM_PDP10, "Digital Equipment Corp. PDP-10"), 1053 ENUM_ENT(EM_PDP11, "Digital Equipment Corp. PDP-11"), 1054 ENUM_ENT(EM_FX66, "Siemens FX66 microcontroller"), 1055 ENUM_ENT(EM_ST9PLUS, "STMicroelectronics ST9+ 8/16 bit microcontroller"), 1056 ENUM_ENT(EM_ST7, "STMicroelectronics ST7 8-bit microcontroller"), 1057 ENUM_ENT(EM_68HC16, "Motorola MC68HC16 Microcontroller"), 1058 ENUM_ENT(EM_68HC11, "Motorola MC68HC11 Microcontroller"), 1059 ENUM_ENT(EM_68HC08, "Motorola MC68HC08 Microcontroller"), 1060 ENUM_ENT(EM_68HC05, "Motorola MC68HC05 Microcontroller"), 1061 ENUM_ENT(EM_SVX, "Silicon Graphics SVx"), 1062 ENUM_ENT(EM_ST19, "STMicroelectronics ST19 8-bit microcontroller"), 1063 ENUM_ENT(EM_VAX, "Digital VAX"), 1064 ENUM_ENT(EM_CRIS, "Axis Communications 32-bit embedded processor"), 1065 ENUM_ENT(EM_JAVELIN, "Infineon Technologies 32-bit embedded cpu"), 1066 ENUM_ENT(EM_FIREPATH, "Element 14 64-bit DSP processor"), 1067 ENUM_ENT(EM_ZSP, "LSI Logic's 16-bit DSP processor"), 1068 ENUM_ENT(EM_MMIX, "Donald Knuth's educational 64-bit processor"), 1069 ENUM_ENT(EM_HUANY, "Harvard Universitys's machine-independent object format"), 1070 ENUM_ENT(EM_PRISM, "Vitesse Prism"), 1071 ENUM_ENT(EM_AVR, "Atmel AVR 8-bit microcontroller"), 1072 ENUM_ENT(EM_FR30, "Fujitsu FR30"), 1073 ENUM_ENT(EM_D10V, "Mitsubishi D10V"), 1074 ENUM_ENT(EM_D30V, "Mitsubishi D30V"), 1075 ENUM_ENT(EM_V850, "NEC v850"), 1076 ENUM_ENT(EM_M32R, "Renesas M32R (formerly Mitsubishi M32r)"), 1077 ENUM_ENT(EM_MN10300, "Matsushita MN10300"), 1078 ENUM_ENT(EM_MN10200, "Matsushita MN10200"), 1079 ENUM_ENT(EM_PJ, "picoJava"), 1080 ENUM_ENT(EM_OPENRISC, "OpenRISC 32-bit embedded processor"), 1081 ENUM_ENT(EM_ARC_COMPACT, "EM_ARC_COMPACT"), 1082 ENUM_ENT(EM_XTENSA, "Tensilica Xtensa Processor"), 1083 ENUM_ENT(EM_VIDEOCORE, "Alphamosaic VideoCore processor"), 1084 ENUM_ENT(EM_TMM_GPP, "Thompson Multimedia General Purpose Processor"), 1085 ENUM_ENT(EM_NS32K, "National Semiconductor 32000 series"), 1086 ENUM_ENT(EM_TPC, "Tenor Network TPC processor"), 1087 ENUM_ENT(EM_SNP1K, "EM_SNP1K"), 1088 ENUM_ENT(EM_ST200, "STMicroelectronics ST200 microcontroller"), 1089 ENUM_ENT(EM_IP2K, "Ubicom IP2xxx 8-bit microcontrollers"), 1090 ENUM_ENT(EM_MAX, "MAX Processor"), 1091 ENUM_ENT(EM_CR, "National Semiconductor CompactRISC"), 1092 ENUM_ENT(EM_F2MC16, "Fujitsu F2MC16"), 1093 ENUM_ENT(EM_MSP430, "Texas Instruments msp430 microcontroller"), 1094 ENUM_ENT(EM_BLACKFIN, "Analog Devices Blackfin"), 1095 ENUM_ENT(EM_SE_C33, "S1C33 Family of Seiko Epson processors"), 1096 ENUM_ENT(EM_SEP, "Sharp embedded microprocessor"), 1097 ENUM_ENT(EM_ARCA, "Arca RISC microprocessor"), 1098 ENUM_ENT(EM_UNICORE, "Unicore"), 1099 ENUM_ENT(EM_EXCESS, "eXcess 16/32/64-bit configurable embedded CPU"), 1100 ENUM_ENT(EM_DXP, "Icera Semiconductor Inc. Deep Execution Processor"), 1101 ENUM_ENT(EM_ALTERA_NIOS2, "Altera Nios"), 1102 ENUM_ENT(EM_CRX, "National Semiconductor CRX microprocessor"), 1103 ENUM_ENT(EM_XGATE, "Motorola XGATE embedded processor"), 1104 ENUM_ENT(EM_C166, "Infineon Technologies xc16x"), 1105 ENUM_ENT(EM_M16C, "Renesas M16C"), 1106 ENUM_ENT(EM_DSPIC30F, "Microchip Technology dsPIC30F Digital Signal Controller"), 1107 ENUM_ENT(EM_CE, "Freescale Communication Engine RISC core"), 1108 ENUM_ENT(EM_M32C, "Renesas M32C"), 1109 ENUM_ENT(EM_TSK3000, "Altium TSK3000 core"), 1110 ENUM_ENT(EM_RS08, "Freescale RS08 embedded processor"), 1111 ENUM_ENT(EM_SHARC, "EM_SHARC"), 1112 ENUM_ENT(EM_ECOG2, "Cyan Technology eCOG2 microprocessor"), 1113 ENUM_ENT(EM_SCORE7, "SUNPLUS S+Core"), 1114 ENUM_ENT(EM_DSP24, "New Japan Radio (NJR) 24-bit DSP Processor"), 1115 ENUM_ENT(EM_VIDEOCORE3, "Broadcom VideoCore III processor"), 1116 ENUM_ENT(EM_LATTICEMICO32, "Lattice Mico32"), 1117 ENUM_ENT(EM_SE_C17, "Seiko Epson C17 family"), 1118 ENUM_ENT(EM_TI_C6000, "Texas Instruments TMS320C6000 DSP family"), 1119 ENUM_ENT(EM_TI_C2000, "Texas Instruments TMS320C2000 DSP family"), 1120 ENUM_ENT(EM_TI_C5500, "Texas Instruments TMS320C55x DSP family"), 1121 ENUM_ENT(EM_MMDSP_PLUS, "STMicroelectronics 64bit VLIW Data Signal Processor"), 1122 ENUM_ENT(EM_CYPRESS_M8C, "Cypress M8C microprocessor"), 1123 ENUM_ENT(EM_R32C, "Renesas R32C series microprocessors"), 1124 ENUM_ENT(EM_TRIMEDIA, "NXP Semiconductors TriMedia architecture family"), 1125 ENUM_ENT(EM_HEXAGON, "Qualcomm Hexagon"), 1126 ENUM_ENT(EM_8051, "Intel 8051 and variants"), 1127 ENUM_ENT(EM_STXP7X, "STMicroelectronics STxP7x family"), 1128 ENUM_ENT(EM_NDS32, "Andes Technology compact code size embedded RISC processor family"), 1129 ENUM_ENT(EM_ECOG1, "Cyan Technology eCOG1 microprocessor"), 1130 // FIXME: Following EM_ECOG1X definitions is dead code since EM_ECOG1X has 1131 // an identical number to EM_ECOG1. 1132 ENUM_ENT(EM_ECOG1X, "Cyan Technology eCOG1X family"), 1133 ENUM_ENT(EM_MAXQ30, "Dallas Semiconductor MAXQ30 Core microcontrollers"), 1134 ENUM_ENT(EM_XIMO16, "New Japan Radio (NJR) 16-bit DSP Processor"), 1135 ENUM_ENT(EM_MANIK, "M2000 Reconfigurable RISC Microprocessor"), 1136 ENUM_ENT(EM_CRAYNV2, "Cray Inc. NV2 vector architecture"), 1137 ENUM_ENT(EM_RX, "Renesas RX"), 1138 ENUM_ENT(EM_METAG, "Imagination Technologies Meta processor architecture"), 1139 ENUM_ENT(EM_MCST_ELBRUS, "MCST Elbrus general purpose hardware architecture"), 1140 ENUM_ENT(EM_ECOG16, "Cyan Technology eCOG16 family"), 1141 ENUM_ENT(EM_CR16, "Xilinx MicroBlaze"), 1142 ENUM_ENT(EM_ETPU, "Freescale Extended Time Processing Unit"), 1143 ENUM_ENT(EM_SLE9X, "Infineon Technologies SLE9X core"), 1144 ENUM_ENT(EM_L10M, "EM_L10M"), 1145 ENUM_ENT(EM_K10M, "EM_K10M"), 1146 ENUM_ENT(EM_AARCH64, "AArch64"), 1147 ENUM_ENT(EM_AVR32, "Atmel Corporation 32-bit microprocessor family"), 1148 ENUM_ENT(EM_STM8, "STMicroeletronics STM8 8-bit microcontroller"), 1149 ENUM_ENT(EM_TILE64, "Tilera TILE64 multicore architecture family"), 1150 ENUM_ENT(EM_TILEPRO, "Tilera TILEPro multicore architecture family"), 1151 ENUM_ENT(EM_CUDA, "NVIDIA CUDA architecture"), 1152 ENUM_ENT(EM_TILEGX, "Tilera TILE-Gx multicore architecture family"), 1153 ENUM_ENT(EM_CLOUDSHIELD, "EM_CLOUDSHIELD"), 1154 ENUM_ENT(EM_COREA_1ST, "EM_COREA_1ST"), 1155 ENUM_ENT(EM_COREA_2ND, "EM_COREA_2ND"), 1156 ENUM_ENT(EM_ARC_COMPACT2, "EM_ARC_COMPACT2"), 1157 ENUM_ENT(EM_OPEN8, "EM_OPEN8"), 1158 ENUM_ENT(EM_RL78, "Renesas RL78"), 1159 ENUM_ENT(EM_VIDEOCORE5, "Broadcom VideoCore V processor"), 1160 ENUM_ENT(EM_78KOR, "EM_78KOR"), 1161 ENUM_ENT(EM_56800EX, "EM_56800EX"), 1162 ENUM_ENT(EM_AMDGPU, "EM_AMDGPU"), 1163 ENUM_ENT(EM_RISCV, "RISC-V"), 1164 ENUM_ENT(EM_LANAI, "EM_LANAI"), 1165 ENUM_ENT(EM_BPF, "EM_BPF"), 1166 ENUM_ENT(EM_VE, "NEC SX-Aurora Vector Engine"), 1167 }; 1168 1169 static const EnumEntry<unsigned> ElfSymbolBindings[] = { 1170 {"Local", "LOCAL", ELF::STB_LOCAL}, 1171 {"Global", "GLOBAL", ELF::STB_GLOBAL}, 1172 {"Weak", "WEAK", ELF::STB_WEAK}, 1173 {"Unique", "UNIQUE", ELF::STB_GNU_UNIQUE}}; 1174 1175 static const EnumEntry<unsigned> ElfSymbolVisibilities[] = { 1176 {"DEFAULT", "DEFAULT", ELF::STV_DEFAULT}, 1177 {"INTERNAL", "INTERNAL", ELF::STV_INTERNAL}, 1178 {"HIDDEN", "HIDDEN", ELF::STV_HIDDEN}, 1179 {"PROTECTED", "PROTECTED", ELF::STV_PROTECTED}}; 1180 1181 static const EnumEntry<unsigned> AMDGPUSymbolTypes[] = { 1182 { "AMDGPU_HSA_KERNEL", ELF::STT_AMDGPU_HSA_KERNEL } 1183 }; 1184 1185 static const char *getGroupType(uint32_t Flag) { 1186 if (Flag & ELF::GRP_COMDAT) 1187 return "COMDAT"; 1188 else 1189 return "(unknown)"; 1190 } 1191 1192 static const EnumEntry<unsigned> ElfSectionFlags[] = { 1193 ENUM_ENT(SHF_WRITE, "W"), 1194 ENUM_ENT(SHF_ALLOC, "A"), 1195 ENUM_ENT(SHF_EXECINSTR, "X"), 1196 ENUM_ENT(SHF_MERGE, "M"), 1197 ENUM_ENT(SHF_STRINGS, "S"), 1198 ENUM_ENT(SHF_INFO_LINK, "I"), 1199 ENUM_ENT(SHF_LINK_ORDER, "L"), 1200 ENUM_ENT(SHF_OS_NONCONFORMING, "O"), 1201 ENUM_ENT(SHF_GROUP, "G"), 1202 ENUM_ENT(SHF_TLS, "T"), 1203 ENUM_ENT(SHF_COMPRESSED, "C"), 1204 ENUM_ENT(SHF_GNU_RETAIN, "R"), 1205 ENUM_ENT(SHF_EXCLUDE, "E"), 1206 }; 1207 1208 static const EnumEntry<unsigned> ElfXCoreSectionFlags[] = { 1209 ENUM_ENT(XCORE_SHF_CP_SECTION, ""), 1210 ENUM_ENT(XCORE_SHF_DP_SECTION, "") 1211 }; 1212 1213 static const EnumEntry<unsigned> ElfARMSectionFlags[] = { 1214 ENUM_ENT(SHF_ARM_PURECODE, "y") 1215 }; 1216 1217 static const EnumEntry<unsigned> ElfHexagonSectionFlags[] = { 1218 ENUM_ENT(SHF_HEX_GPREL, "") 1219 }; 1220 1221 static const EnumEntry<unsigned> ElfMipsSectionFlags[] = { 1222 ENUM_ENT(SHF_MIPS_NODUPES, ""), 1223 ENUM_ENT(SHF_MIPS_NAMES, ""), 1224 ENUM_ENT(SHF_MIPS_LOCAL, ""), 1225 ENUM_ENT(SHF_MIPS_NOSTRIP, ""), 1226 ENUM_ENT(SHF_MIPS_GPREL, ""), 1227 ENUM_ENT(SHF_MIPS_MERGE, ""), 1228 ENUM_ENT(SHF_MIPS_ADDR, ""), 1229 ENUM_ENT(SHF_MIPS_STRING, "") 1230 }; 1231 1232 static const EnumEntry<unsigned> ElfX86_64SectionFlags[] = { 1233 ENUM_ENT(SHF_X86_64_LARGE, "l") 1234 }; 1235 1236 static std::vector<EnumEntry<unsigned>> 1237 getSectionFlagsForTarget(unsigned EMachine) { 1238 std::vector<EnumEntry<unsigned>> Ret(std::begin(ElfSectionFlags), 1239 std::end(ElfSectionFlags)); 1240 switch (EMachine) { 1241 case EM_ARM: 1242 Ret.insert(Ret.end(), std::begin(ElfARMSectionFlags), 1243 std::end(ElfARMSectionFlags)); 1244 break; 1245 case EM_HEXAGON: 1246 Ret.insert(Ret.end(), std::begin(ElfHexagonSectionFlags), 1247 std::end(ElfHexagonSectionFlags)); 1248 break; 1249 case EM_MIPS: 1250 Ret.insert(Ret.end(), std::begin(ElfMipsSectionFlags), 1251 std::end(ElfMipsSectionFlags)); 1252 break; 1253 case EM_X86_64: 1254 Ret.insert(Ret.end(), std::begin(ElfX86_64SectionFlags), 1255 std::end(ElfX86_64SectionFlags)); 1256 break; 1257 case EM_XCORE: 1258 Ret.insert(Ret.end(), std::begin(ElfXCoreSectionFlags), 1259 std::end(ElfXCoreSectionFlags)); 1260 break; 1261 default: 1262 break; 1263 } 1264 return Ret; 1265 } 1266 1267 static std::string getGNUFlags(unsigned EMachine, uint64_t Flags) { 1268 // Here we are trying to build the flags string in the same way as GNU does. 1269 // It is not that straightforward. Imagine we have sh_flags == 0x90000000. 1270 // SHF_EXCLUDE ("E") has a value of 0x80000000 and SHF_MASKPROC is 0xf0000000. 1271 // GNU readelf will not print "E" or "Ep" in this case, but will print just 1272 // "p". It only will print "E" when no other processor flag is set. 1273 std::string Str; 1274 bool HasUnknownFlag = false; 1275 bool HasOSFlag = false; 1276 bool HasProcFlag = false; 1277 std::vector<EnumEntry<unsigned>> FlagsList = 1278 getSectionFlagsForTarget(EMachine); 1279 while (Flags) { 1280 // Take the least significant bit as a flag. 1281 uint64_t Flag = Flags & -Flags; 1282 Flags -= Flag; 1283 1284 // Find the flag in the known flags list. 1285 auto I = llvm::find_if(FlagsList, [=](const EnumEntry<unsigned> &E) { 1286 // Flags with empty names are not printed in GNU style output. 1287 return E.Value == Flag && !E.AltName.empty(); 1288 }); 1289 if (I != FlagsList.end()) { 1290 Str += I->AltName; 1291 continue; 1292 } 1293 1294 // If we did not find a matching regular flag, then we deal with an OS 1295 // specific flag, processor specific flag or an unknown flag. 1296 if (Flag & ELF::SHF_MASKOS) { 1297 HasOSFlag = true; 1298 Flags &= ~ELF::SHF_MASKOS; 1299 } else if (Flag & ELF::SHF_MASKPROC) { 1300 HasProcFlag = true; 1301 // Mask off all the processor-specific bits. This removes the SHF_EXCLUDE 1302 // bit if set so that it doesn't also get printed. 1303 Flags &= ~ELF::SHF_MASKPROC; 1304 } else { 1305 HasUnknownFlag = true; 1306 } 1307 } 1308 1309 // "o", "p" and "x" are printed last. 1310 if (HasOSFlag) 1311 Str += "o"; 1312 if (HasProcFlag) 1313 Str += "p"; 1314 if (HasUnknownFlag) 1315 Str += "x"; 1316 return Str; 1317 } 1318 1319 static StringRef segmentTypeToString(unsigned Arch, unsigned Type) { 1320 // Check potentially overlapped processor-specific program header type. 1321 switch (Arch) { 1322 case ELF::EM_ARM: 1323 switch (Type) { LLVM_READOBJ_ENUM_CASE(ELF, PT_ARM_EXIDX); } 1324 break; 1325 case ELF::EM_MIPS: 1326 case ELF::EM_MIPS_RS3_LE: 1327 switch (Type) { 1328 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_REGINFO); 1329 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_RTPROC); 1330 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_OPTIONS); 1331 LLVM_READOBJ_ENUM_CASE(ELF, PT_MIPS_ABIFLAGS); 1332 } 1333 break; 1334 } 1335 1336 switch (Type) { 1337 LLVM_READOBJ_ENUM_CASE(ELF, PT_NULL); 1338 LLVM_READOBJ_ENUM_CASE(ELF, PT_LOAD); 1339 LLVM_READOBJ_ENUM_CASE(ELF, PT_DYNAMIC); 1340 LLVM_READOBJ_ENUM_CASE(ELF, PT_INTERP); 1341 LLVM_READOBJ_ENUM_CASE(ELF, PT_NOTE); 1342 LLVM_READOBJ_ENUM_CASE(ELF, PT_SHLIB); 1343 LLVM_READOBJ_ENUM_CASE(ELF, PT_PHDR); 1344 LLVM_READOBJ_ENUM_CASE(ELF, PT_TLS); 1345 1346 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_EH_FRAME); 1347 LLVM_READOBJ_ENUM_CASE(ELF, PT_SUNW_UNWIND); 1348 1349 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_STACK); 1350 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_RELRO); 1351 LLVM_READOBJ_ENUM_CASE(ELF, PT_GNU_PROPERTY); 1352 1353 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_RANDOMIZE); 1354 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_WXNEEDED); 1355 LLVM_READOBJ_ENUM_CASE(ELF, PT_OPENBSD_BOOTDATA); 1356 default: 1357 return ""; 1358 } 1359 } 1360 1361 static std::string getGNUPtType(unsigned Arch, unsigned Type) { 1362 StringRef Seg = segmentTypeToString(Arch, Type); 1363 if (Seg.empty()) 1364 return std::string("<unknown>: ") + to_string(format_hex(Type, 1)); 1365 1366 // E.g. "PT_ARM_EXIDX" -> "EXIDX". 1367 if (Seg.startswith("PT_ARM_")) 1368 return Seg.drop_front(7).str(); 1369 1370 // E.g. "PT_MIPS_REGINFO" -> "REGINFO". 1371 if (Seg.startswith("PT_MIPS_")) 1372 return Seg.drop_front(8).str(); 1373 1374 // E.g. "PT_LOAD" -> "LOAD". 1375 assert(Seg.startswith("PT_")); 1376 return Seg.drop_front(3).str(); 1377 } 1378 1379 static const EnumEntry<unsigned> ElfSegmentFlags[] = { 1380 LLVM_READOBJ_ENUM_ENT(ELF, PF_X), 1381 LLVM_READOBJ_ENUM_ENT(ELF, PF_W), 1382 LLVM_READOBJ_ENUM_ENT(ELF, PF_R) 1383 }; 1384 1385 static const EnumEntry<unsigned> ElfHeaderMipsFlags[] = { 1386 ENUM_ENT(EF_MIPS_NOREORDER, "noreorder"), 1387 ENUM_ENT(EF_MIPS_PIC, "pic"), 1388 ENUM_ENT(EF_MIPS_CPIC, "cpic"), 1389 ENUM_ENT(EF_MIPS_ABI2, "abi2"), 1390 ENUM_ENT(EF_MIPS_32BITMODE, "32bitmode"), 1391 ENUM_ENT(EF_MIPS_FP64, "fp64"), 1392 ENUM_ENT(EF_MIPS_NAN2008, "nan2008"), 1393 ENUM_ENT(EF_MIPS_ABI_O32, "o32"), 1394 ENUM_ENT(EF_MIPS_ABI_O64, "o64"), 1395 ENUM_ENT(EF_MIPS_ABI_EABI32, "eabi32"), 1396 ENUM_ENT(EF_MIPS_ABI_EABI64, "eabi64"), 1397 ENUM_ENT(EF_MIPS_MACH_3900, "3900"), 1398 ENUM_ENT(EF_MIPS_MACH_4010, "4010"), 1399 ENUM_ENT(EF_MIPS_MACH_4100, "4100"), 1400 ENUM_ENT(EF_MIPS_MACH_4650, "4650"), 1401 ENUM_ENT(EF_MIPS_MACH_4120, "4120"), 1402 ENUM_ENT(EF_MIPS_MACH_4111, "4111"), 1403 ENUM_ENT(EF_MIPS_MACH_SB1, "sb1"), 1404 ENUM_ENT(EF_MIPS_MACH_OCTEON, "octeon"), 1405 ENUM_ENT(EF_MIPS_MACH_XLR, "xlr"), 1406 ENUM_ENT(EF_MIPS_MACH_OCTEON2, "octeon2"), 1407 ENUM_ENT(EF_MIPS_MACH_OCTEON3, "octeon3"), 1408 ENUM_ENT(EF_MIPS_MACH_5400, "5400"), 1409 ENUM_ENT(EF_MIPS_MACH_5900, "5900"), 1410 ENUM_ENT(EF_MIPS_MACH_5500, "5500"), 1411 ENUM_ENT(EF_MIPS_MACH_9000, "9000"), 1412 ENUM_ENT(EF_MIPS_MACH_LS2E, "loongson-2e"), 1413 ENUM_ENT(EF_MIPS_MACH_LS2F, "loongson-2f"), 1414 ENUM_ENT(EF_MIPS_MACH_LS3A, "loongson-3a"), 1415 ENUM_ENT(EF_MIPS_MICROMIPS, "micromips"), 1416 ENUM_ENT(EF_MIPS_ARCH_ASE_M16, "mips16"), 1417 ENUM_ENT(EF_MIPS_ARCH_ASE_MDMX, "mdmx"), 1418 ENUM_ENT(EF_MIPS_ARCH_1, "mips1"), 1419 ENUM_ENT(EF_MIPS_ARCH_2, "mips2"), 1420 ENUM_ENT(EF_MIPS_ARCH_3, "mips3"), 1421 ENUM_ENT(EF_MIPS_ARCH_4, "mips4"), 1422 ENUM_ENT(EF_MIPS_ARCH_5, "mips5"), 1423 ENUM_ENT(EF_MIPS_ARCH_32, "mips32"), 1424 ENUM_ENT(EF_MIPS_ARCH_64, "mips64"), 1425 ENUM_ENT(EF_MIPS_ARCH_32R2, "mips32r2"), 1426 ENUM_ENT(EF_MIPS_ARCH_64R2, "mips64r2"), 1427 ENUM_ENT(EF_MIPS_ARCH_32R6, "mips32r6"), 1428 ENUM_ENT(EF_MIPS_ARCH_64R6, "mips64r6") 1429 }; 1430 1431 static const EnumEntry<unsigned> ElfHeaderAMDGPUFlags[] = { 1432 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_NONE), 1433 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R600), 1434 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_R630), 1435 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RS880), 1436 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV670), 1437 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV710), 1438 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV730), 1439 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_RV770), 1440 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CEDAR), 1441 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CYPRESS), 1442 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_JUNIPER), 1443 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_REDWOOD), 1444 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_SUMO), 1445 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_BARTS), 1446 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAICOS), 1447 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_CAYMAN), 1448 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_R600_TURKS), 1449 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX600), 1450 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX601), 1451 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX602), 1452 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX700), 1453 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX701), 1454 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX702), 1455 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX703), 1456 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX704), 1457 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX705), 1458 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX801), 1459 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX802), 1460 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX803), 1461 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX805), 1462 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX810), 1463 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX900), 1464 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX902), 1465 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX904), 1466 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX906), 1467 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX908), 1468 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX909), 1469 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX90C), 1470 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1010), 1471 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1011), 1472 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1012), 1473 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1030), 1474 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1031), 1475 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1032), 1476 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_MACH_AMDGCN_GFX1033), 1477 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_XNACK), 1478 LLVM_READOBJ_ENUM_ENT(ELF, EF_AMDGPU_SRAM_ECC) 1479 }; 1480 1481 static const EnumEntry<unsigned> ElfHeaderRISCVFlags[] = { 1482 ENUM_ENT(EF_RISCV_RVC, "RVC"), 1483 ENUM_ENT(EF_RISCV_FLOAT_ABI_SINGLE, "single-float ABI"), 1484 ENUM_ENT(EF_RISCV_FLOAT_ABI_DOUBLE, "double-float ABI"), 1485 ENUM_ENT(EF_RISCV_FLOAT_ABI_QUAD, "quad-float ABI"), 1486 ENUM_ENT(EF_RISCV_RVE, "RVE") 1487 }; 1488 1489 static const EnumEntry<unsigned> ElfSymOtherFlags[] = { 1490 LLVM_READOBJ_ENUM_ENT(ELF, STV_INTERNAL), 1491 LLVM_READOBJ_ENUM_ENT(ELF, STV_HIDDEN), 1492 LLVM_READOBJ_ENUM_ENT(ELF, STV_PROTECTED) 1493 }; 1494 1495 static const EnumEntry<unsigned> ElfMipsSymOtherFlags[] = { 1496 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL), 1497 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT), 1498 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PIC), 1499 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MICROMIPS) 1500 }; 1501 1502 static const EnumEntry<unsigned> ElfAArch64SymOtherFlags[] = { 1503 LLVM_READOBJ_ENUM_ENT(ELF, STO_AARCH64_VARIANT_PCS) 1504 }; 1505 1506 static const EnumEntry<unsigned> ElfMips16SymOtherFlags[] = { 1507 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL), 1508 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT), 1509 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MIPS16) 1510 }; 1511 1512 static const char *getElfMipsOptionsOdkType(unsigned Odk) { 1513 switch (Odk) { 1514 LLVM_READOBJ_ENUM_CASE(ELF, ODK_NULL); 1515 LLVM_READOBJ_ENUM_CASE(ELF, ODK_REGINFO); 1516 LLVM_READOBJ_ENUM_CASE(ELF, ODK_EXCEPTIONS); 1517 LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAD); 1518 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWPATCH); 1519 LLVM_READOBJ_ENUM_CASE(ELF, ODK_FILL); 1520 LLVM_READOBJ_ENUM_CASE(ELF, ODK_TAGS); 1521 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWAND); 1522 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWOR); 1523 LLVM_READOBJ_ENUM_CASE(ELF, ODK_GP_GROUP); 1524 LLVM_READOBJ_ENUM_CASE(ELF, ODK_IDENT); 1525 LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAGESIZE); 1526 default: 1527 return "Unknown"; 1528 } 1529 } 1530 1531 template <typename ELFT> 1532 std::pair<const typename ELFT::Phdr *, const typename ELFT::Shdr *> 1533 ELFDumper<ELFT>::findDynamic() { 1534 // Try to locate the PT_DYNAMIC header. 1535 const Elf_Phdr *DynamicPhdr = nullptr; 1536 if (Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = Obj.program_headers()) { 1537 for (const Elf_Phdr &Phdr : *PhdrsOrErr) { 1538 if (Phdr.p_type != ELF::PT_DYNAMIC) 1539 continue; 1540 DynamicPhdr = &Phdr; 1541 break; 1542 } 1543 } else { 1544 reportUniqueWarning( 1545 "unable to read program headers to locate the PT_DYNAMIC segment: " + 1546 toString(PhdrsOrErr.takeError())); 1547 } 1548 1549 // Try to locate the .dynamic section in the sections header table. 1550 const Elf_Shdr *DynamicSec = nullptr; 1551 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) { 1552 if (Sec.sh_type != ELF::SHT_DYNAMIC) 1553 continue; 1554 DynamicSec = &Sec; 1555 break; 1556 } 1557 1558 if (DynamicPhdr && ((DynamicPhdr->p_offset + DynamicPhdr->p_filesz > 1559 ObjF.getMemoryBufferRef().getBufferSize()) || 1560 (DynamicPhdr->p_offset + DynamicPhdr->p_filesz < 1561 DynamicPhdr->p_offset))) { 1562 reportUniqueWarning( 1563 "PT_DYNAMIC segment offset (0x" + 1564 Twine::utohexstr(DynamicPhdr->p_offset) + ") + file size (0x" + 1565 Twine::utohexstr(DynamicPhdr->p_filesz) + 1566 ") exceeds the size of the file (0x" + 1567 Twine::utohexstr(ObjF.getMemoryBufferRef().getBufferSize()) + ")"); 1568 // Don't use the broken dynamic header. 1569 DynamicPhdr = nullptr; 1570 } 1571 1572 if (DynamicPhdr && DynamicSec) { 1573 if (DynamicSec->sh_addr + DynamicSec->sh_size > 1574 DynamicPhdr->p_vaddr + DynamicPhdr->p_memsz || 1575 DynamicSec->sh_addr < DynamicPhdr->p_vaddr) 1576 reportUniqueWarning(describe(*DynamicSec) + 1577 " is not contained within the " 1578 "PT_DYNAMIC segment"); 1579 1580 if (DynamicSec->sh_addr != DynamicPhdr->p_vaddr) 1581 reportUniqueWarning(describe(*DynamicSec) + " is not at the start of " 1582 "PT_DYNAMIC segment"); 1583 } 1584 1585 return std::make_pair(DynamicPhdr, DynamicSec); 1586 } 1587 1588 template <typename ELFT> 1589 void ELFDumper<ELFT>::loadDynamicTable() { 1590 const Elf_Phdr *DynamicPhdr; 1591 const Elf_Shdr *DynamicSec; 1592 std::tie(DynamicPhdr, DynamicSec) = findDynamic(); 1593 if (!DynamicPhdr && !DynamicSec) 1594 return; 1595 1596 DynRegionInfo FromPhdr(ObjF, *this); 1597 bool IsPhdrTableValid = false; 1598 if (DynamicPhdr) { 1599 // Use cantFail(), because p_offset/p_filesz fields of a PT_DYNAMIC are 1600 // validated in findDynamic() and so createDRI() is not expected to fail. 1601 FromPhdr = cantFail(createDRI(DynamicPhdr->p_offset, DynamicPhdr->p_filesz, 1602 sizeof(Elf_Dyn))); 1603 FromPhdr.SizePrintName = "PT_DYNAMIC size"; 1604 FromPhdr.EntSizePrintName = ""; 1605 IsPhdrTableValid = !FromPhdr.template getAsArrayRef<Elf_Dyn>().empty(); 1606 } 1607 1608 // Locate the dynamic table described in a section header. 1609 // Ignore sh_entsize and use the expected value for entry size explicitly. 1610 // This allows us to dump dynamic sections with a broken sh_entsize 1611 // field. 1612 DynRegionInfo FromSec(ObjF, *this); 1613 bool IsSecTableValid = false; 1614 if (DynamicSec) { 1615 Expected<DynRegionInfo> RegOrErr = 1616 createDRI(DynamicSec->sh_offset, DynamicSec->sh_size, sizeof(Elf_Dyn)); 1617 if (RegOrErr) { 1618 FromSec = *RegOrErr; 1619 FromSec.Context = describe(*DynamicSec); 1620 FromSec.EntSizePrintName = ""; 1621 IsSecTableValid = !FromSec.template getAsArrayRef<Elf_Dyn>().empty(); 1622 } else { 1623 reportUniqueWarning("unable to read the dynamic table from " + 1624 describe(*DynamicSec) + ": " + 1625 toString(RegOrErr.takeError())); 1626 } 1627 } 1628 1629 // When we only have information from one of the SHT_DYNAMIC section header or 1630 // PT_DYNAMIC program header, just use that. 1631 if (!DynamicPhdr || !DynamicSec) { 1632 if ((DynamicPhdr && IsPhdrTableValid) || (DynamicSec && IsSecTableValid)) { 1633 DynamicTable = DynamicPhdr ? FromPhdr : FromSec; 1634 parseDynamicTable(); 1635 } else { 1636 reportUniqueWarning("no valid dynamic table was found"); 1637 } 1638 return; 1639 } 1640 1641 // At this point we have tables found from the section header and from the 1642 // dynamic segment. Usually they match, but we have to do sanity checks to 1643 // verify that. 1644 1645 if (FromPhdr.Addr != FromSec.Addr) 1646 reportUniqueWarning("SHT_DYNAMIC section header and PT_DYNAMIC " 1647 "program header disagree about " 1648 "the location of the dynamic table"); 1649 1650 if (!IsPhdrTableValid && !IsSecTableValid) { 1651 reportUniqueWarning("no valid dynamic table was found"); 1652 return; 1653 } 1654 1655 // Information in the PT_DYNAMIC program header has priority over the 1656 // information in a section header. 1657 if (IsPhdrTableValid) { 1658 if (!IsSecTableValid) 1659 reportUniqueWarning( 1660 "SHT_DYNAMIC dynamic table is invalid: PT_DYNAMIC will be used"); 1661 DynamicTable = FromPhdr; 1662 } else { 1663 reportUniqueWarning( 1664 "PT_DYNAMIC dynamic table is invalid: SHT_DYNAMIC will be used"); 1665 DynamicTable = FromSec; 1666 } 1667 1668 parseDynamicTable(); 1669 } 1670 1671 template <typename ELFT> 1672 ELFDumper<ELFT>::ELFDumper(const object::ELFObjectFile<ELFT> &O, 1673 ScopedPrinter &Writer) 1674 : ObjDumper(Writer, O.getFileName()), ObjF(O), Obj(O.getELFFile()), 1675 FileName(O.getFileName()), DynRelRegion(O, *this), 1676 DynRelaRegion(O, *this), DynRelrRegion(O, *this), 1677 DynPLTRelRegion(O, *this), DynSymTabShndxRegion(O, *this), 1678 DynamicTable(O, *this) { 1679 if (!O.IsContentValid()) 1680 return; 1681 1682 typename ELFT::ShdrRange Sections = cantFail(Obj.sections()); 1683 for (const Elf_Shdr &Sec : Sections) { 1684 switch (Sec.sh_type) { 1685 case ELF::SHT_SYMTAB: 1686 if (!DotSymtabSec) 1687 DotSymtabSec = &Sec; 1688 break; 1689 case ELF::SHT_DYNSYM: 1690 if (!DotDynsymSec) 1691 DotDynsymSec = &Sec; 1692 1693 if (!DynSymRegion) { 1694 Expected<DynRegionInfo> RegOrErr = 1695 createDRI(Sec.sh_offset, Sec.sh_size, Sec.sh_entsize); 1696 if (RegOrErr) { 1697 DynSymRegion = *RegOrErr; 1698 DynSymRegion->Context = describe(Sec); 1699 1700 if (Expected<StringRef> E = Obj.getStringTableForSymtab(Sec)) 1701 DynamicStringTable = *E; 1702 else 1703 reportUniqueWarning("unable to get the string table for the " + 1704 describe(Sec) + ": " + toString(E.takeError())); 1705 } else { 1706 reportUniqueWarning("unable to read dynamic symbols from " + 1707 describe(Sec) + ": " + 1708 toString(RegOrErr.takeError())); 1709 } 1710 } 1711 break; 1712 case ELF::SHT_SYMTAB_SHNDX: { 1713 uint32_t SymtabNdx = Sec.sh_link; 1714 if (SymtabNdx >= Sections.size()) { 1715 reportUniqueWarning( 1716 "unable to get the associated symbol table for " + describe(Sec) + 1717 ": sh_link (" + Twine(SymtabNdx) + 1718 ") is greater than or equal to the total number of sections (" + 1719 Twine(Sections.size()) + ")"); 1720 continue; 1721 } 1722 1723 if (Expected<ArrayRef<Elf_Word>> ShndxTableOrErr = 1724 Obj.getSHNDXTable(Sec)) { 1725 if (!ShndxTables.insert({&Sections[SymtabNdx], *ShndxTableOrErr}) 1726 .second) 1727 reportUniqueWarning( 1728 "multiple SHT_SYMTAB_SHNDX sections are linked to " + 1729 describe(Sec)); 1730 } else { 1731 reportUniqueWarning(ShndxTableOrErr.takeError()); 1732 } 1733 break; 1734 } 1735 case ELF::SHT_GNU_versym: 1736 if (!SymbolVersionSection) 1737 SymbolVersionSection = &Sec; 1738 break; 1739 case ELF::SHT_GNU_verdef: 1740 if (!SymbolVersionDefSection) 1741 SymbolVersionDefSection = &Sec; 1742 break; 1743 case ELF::SHT_GNU_verneed: 1744 if (!SymbolVersionNeedSection) 1745 SymbolVersionNeedSection = &Sec; 1746 break; 1747 case ELF::SHT_LLVM_CALL_GRAPH_PROFILE: 1748 if (!DotCGProfileSec) 1749 DotCGProfileSec = &Sec; 1750 break; 1751 case ELF::SHT_LLVM_ADDRSIG: 1752 if (!DotAddrsigSec) 1753 DotAddrsigSec = &Sec; 1754 break; 1755 } 1756 } 1757 1758 loadDynamicTable(); 1759 } 1760 1761 template <typename ELFT> void ELFDumper<ELFT>::parseDynamicTable() { 1762 auto toMappedAddr = [&](uint64_t Tag, uint64_t VAddr) -> const uint8_t * { 1763 auto MappedAddrOrError = Obj.toMappedAddr(VAddr, [&](const Twine &Msg) { 1764 this->reportUniqueWarning(Msg); 1765 return Error::success(); 1766 }); 1767 if (!MappedAddrOrError) { 1768 this->reportUniqueWarning("unable to parse DT_" + 1769 Obj.getDynamicTagAsString(Tag) + ": " + 1770 llvm::toString(MappedAddrOrError.takeError())); 1771 return nullptr; 1772 } 1773 return MappedAddrOrError.get(); 1774 }; 1775 1776 const char *StringTableBegin = nullptr; 1777 uint64_t StringTableSize = 0; 1778 Optional<DynRegionInfo> DynSymFromTable; 1779 for (const Elf_Dyn &Dyn : dynamic_table()) { 1780 switch (Dyn.d_tag) { 1781 case ELF::DT_HASH: 1782 HashTable = reinterpret_cast<const Elf_Hash *>( 1783 toMappedAddr(Dyn.getTag(), Dyn.getPtr())); 1784 break; 1785 case ELF::DT_GNU_HASH: 1786 GnuHashTable = reinterpret_cast<const Elf_GnuHash *>( 1787 toMappedAddr(Dyn.getTag(), Dyn.getPtr())); 1788 break; 1789 case ELF::DT_STRTAB: 1790 StringTableBegin = reinterpret_cast<const char *>( 1791 toMappedAddr(Dyn.getTag(), Dyn.getPtr())); 1792 break; 1793 case ELF::DT_STRSZ: 1794 StringTableSize = Dyn.getVal(); 1795 break; 1796 case ELF::DT_SYMTAB: { 1797 // If we can't map the DT_SYMTAB value to an address (e.g. when there are 1798 // no program headers), we ignore its value. 1799 if (const uint8_t *VA = toMappedAddr(Dyn.getTag(), Dyn.getPtr())) { 1800 DynSymFromTable.emplace(ObjF, *this); 1801 DynSymFromTable->Addr = VA; 1802 DynSymFromTable->EntSize = sizeof(Elf_Sym); 1803 DynSymFromTable->EntSizePrintName = ""; 1804 } 1805 break; 1806 } 1807 case ELF::DT_SYMENT: { 1808 uint64_t Val = Dyn.getVal(); 1809 if (Val != sizeof(Elf_Sym)) 1810 this->reportUniqueWarning("DT_SYMENT value of 0x" + 1811 Twine::utohexstr(Val) + 1812 " is not the size of a symbol (0x" + 1813 Twine::utohexstr(sizeof(Elf_Sym)) + ")"); 1814 break; 1815 } 1816 case ELF::DT_RELA: 1817 DynRelaRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr()); 1818 break; 1819 case ELF::DT_RELASZ: 1820 DynRelaRegion.Size = Dyn.getVal(); 1821 DynRelaRegion.SizePrintName = "DT_RELASZ value"; 1822 break; 1823 case ELF::DT_RELAENT: 1824 DynRelaRegion.EntSize = Dyn.getVal(); 1825 DynRelaRegion.EntSizePrintName = "DT_RELAENT value"; 1826 break; 1827 case ELF::DT_SONAME: 1828 SONameOffset = Dyn.getVal(); 1829 break; 1830 case ELF::DT_REL: 1831 DynRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr()); 1832 break; 1833 case ELF::DT_RELSZ: 1834 DynRelRegion.Size = Dyn.getVal(); 1835 DynRelRegion.SizePrintName = "DT_RELSZ value"; 1836 break; 1837 case ELF::DT_RELENT: 1838 DynRelRegion.EntSize = Dyn.getVal(); 1839 DynRelRegion.EntSizePrintName = "DT_RELENT value"; 1840 break; 1841 case ELF::DT_RELR: 1842 case ELF::DT_ANDROID_RELR: 1843 DynRelrRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr()); 1844 break; 1845 case ELF::DT_RELRSZ: 1846 case ELF::DT_ANDROID_RELRSZ: 1847 DynRelrRegion.Size = Dyn.getVal(); 1848 DynRelrRegion.SizePrintName = Dyn.d_tag == ELF::DT_RELRSZ 1849 ? "DT_RELRSZ value" 1850 : "DT_ANDROID_RELRSZ value"; 1851 break; 1852 case ELF::DT_RELRENT: 1853 case ELF::DT_ANDROID_RELRENT: 1854 DynRelrRegion.EntSize = Dyn.getVal(); 1855 DynRelrRegion.EntSizePrintName = Dyn.d_tag == ELF::DT_RELRENT 1856 ? "DT_RELRENT value" 1857 : "DT_ANDROID_RELRENT value"; 1858 break; 1859 case ELF::DT_PLTREL: 1860 if (Dyn.getVal() == DT_REL) 1861 DynPLTRelRegion.EntSize = sizeof(Elf_Rel); 1862 else if (Dyn.getVal() == DT_RELA) 1863 DynPLTRelRegion.EntSize = sizeof(Elf_Rela); 1864 else 1865 reportUniqueWarning(Twine("unknown DT_PLTREL value of ") + 1866 Twine((uint64_t)Dyn.getVal())); 1867 DynPLTRelRegion.EntSizePrintName = "PLTREL entry size"; 1868 break; 1869 case ELF::DT_JMPREL: 1870 DynPLTRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr()); 1871 break; 1872 case ELF::DT_PLTRELSZ: 1873 DynPLTRelRegion.Size = Dyn.getVal(); 1874 DynPLTRelRegion.SizePrintName = "DT_PLTRELSZ value"; 1875 break; 1876 case ELF::DT_SYMTAB_SHNDX: 1877 DynSymTabShndxRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr()); 1878 DynSymTabShndxRegion.EntSize = sizeof(Elf_Word); 1879 break; 1880 } 1881 } 1882 1883 if (StringTableBegin) { 1884 const uint64_t FileSize = Obj.getBufSize(); 1885 const uint64_t Offset = (const uint8_t *)StringTableBegin - Obj.base(); 1886 if (StringTableSize > FileSize - Offset) 1887 reportUniqueWarning( 1888 "the dynamic string table at 0x" + Twine::utohexstr(Offset) + 1889 " goes past the end of the file (0x" + Twine::utohexstr(FileSize) + 1890 ") with DT_STRSZ = 0x" + Twine::utohexstr(StringTableSize)); 1891 else 1892 DynamicStringTable = StringRef(StringTableBegin, StringTableSize); 1893 } 1894 1895 const bool IsHashTableSupported = getHashTableEntSize() == 4; 1896 if (DynSymRegion) { 1897 // Often we find the information about the dynamic symbol table 1898 // location in the SHT_DYNSYM section header. However, the value in 1899 // DT_SYMTAB has priority, because it is used by dynamic loaders to 1900 // locate .dynsym at runtime. The location we find in the section header 1901 // and the location we find here should match. 1902 if (DynSymFromTable && DynSymFromTable->Addr != DynSymRegion->Addr) 1903 reportUniqueWarning( 1904 createError("SHT_DYNSYM section header and DT_SYMTAB disagree about " 1905 "the location of the dynamic symbol table")); 1906 1907 // According to the ELF gABI: "The number of symbol table entries should 1908 // equal nchain". Check to see if the DT_HASH hash table nchain value 1909 // conflicts with the number of symbols in the dynamic symbol table 1910 // according to the section header. 1911 if (HashTable && IsHashTableSupported) { 1912 if (DynSymRegion->EntSize == 0) 1913 reportUniqueWarning("SHT_DYNSYM section has sh_entsize == 0"); 1914 else if (HashTable->nchain != DynSymRegion->Size / DynSymRegion->EntSize) 1915 reportUniqueWarning( 1916 "hash table nchain (" + Twine(HashTable->nchain) + 1917 ") differs from symbol count derived from SHT_DYNSYM section " 1918 "header (" + 1919 Twine(DynSymRegion->Size / DynSymRegion->EntSize) + ")"); 1920 } 1921 } 1922 1923 // Delay the creation of the actual dynamic symbol table until now, so that 1924 // checks can always be made against the section header-based properties, 1925 // without worrying about tag order. 1926 if (DynSymFromTable) { 1927 if (!DynSymRegion) { 1928 DynSymRegion = DynSymFromTable; 1929 } else { 1930 DynSymRegion->Addr = DynSymFromTable->Addr; 1931 DynSymRegion->EntSize = DynSymFromTable->EntSize; 1932 DynSymRegion->EntSizePrintName = DynSymFromTable->EntSizePrintName; 1933 } 1934 } 1935 1936 // Derive the dynamic symbol table size from the DT_HASH hash table, if 1937 // present. 1938 if (HashTable && IsHashTableSupported && DynSymRegion) { 1939 const uint64_t FileSize = Obj.getBufSize(); 1940 const uint64_t DerivedSize = 1941 (uint64_t)HashTable->nchain * DynSymRegion->EntSize; 1942 const uint64_t Offset = (const uint8_t *)DynSymRegion->Addr - Obj.base(); 1943 if (DerivedSize > FileSize - Offset) 1944 reportUniqueWarning( 1945 "the size (0x" + Twine::utohexstr(DerivedSize) + 1946 ") of the dynamic symbol table at 0x" + Twine::utohexstr(Offset) + 1947 ", derived from the hash table, goes past the end of the file (0x" + 1948 Twine::utohexstr(FileSize) + ") and will be ignored"); 1949 else 1950 DynSymRegion->Size = HashTable->nchain * DynSymRegion->EntSize; 1951 } 1952 } 1953 1954 template <typename ELFT> void ELFDumper<ELFT>::printVersionInfo() { 1955 // Dump version symbol section. 1956 printVersionSymbolSection(SymbolVersionSection); 1957 1958 // Dump version definition section. 1959 printVersionDefinitionSection(SymbolVersionDefSection); 1960 1961 // Dump version dependency section. 1962 printVersionDependencySection(SymbolVersionNeedSection); 1963 } 1964 1965 #define LLVM_READOBJ_DT_FLAG_ENT(prefix, enum) \ 1966 { #enum, prefix##_##enum } 1967 1968 static const EnumEntry<unsigned> ElfDynamicDTFlags[] = { 1969 LLVM_READOBJ_DT_FLAG_ENT(DF, ORIGIN), 1970 LLVM_READOBJ_DT_FLAG_ENT(DF, SYMBOLIC), 1971 LLVM_READOBJ_DT_FLAG_ENT(DF, TEXTREL), 1972 LLVM_READOBJ_DT_FLAG_ENT(DF, BIND_NOW), 1973 LLVM_READOBJ_DT_FLAG_ENT(DF, STATIC_TLS) 1974 }; 1975 1976 static const EnumEntry<unsigned> ElfDynamicDTFlags1[] = { 1977 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOW), 1978 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAL), 1979 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GROUP), 1980 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODELETE), 1981 LLVM_READOBJ_DT_FLAG_ENT(DF_1, LOADFLTR), 1982 LLVM_READOBJ_DT_FLAG_ENT(DF_1, INITFIRST), 1983 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOOPEN), 1984 LLVM_READOBJ_DT_FLAG_ENT(DF_1, ORIGIN), 1985 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DIRECT), 1986 LLVM_READOBJ_DT_FLAG_ENT(DF_1, TRANS), 1987 LLVM_READOBJ_DT_FLAG_ENT(DF_1, INTERPOSE), 1988 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODEFLIB), 1989 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODUMP), 1990 LLVM_READOBJ_DT_FLAG_ENT(DF_1, CONFALT), 1991 LLVM_READOBJ_DT_FLAG_ENT(DF_1, ENDFILTEE), 1992 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELDNE), 1993 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELPND), 1994 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODIRECT), 1995 LLVM_READOBJ_DT_FLAG_ENT(DF_1, IGNMULDEF), 1996 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOKSYMS), 1997 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOHDR), 1998 LLVM_READOBJ_DT_FLAG_ENT(DF_1, EDITED), 1999 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NORELOC), 2000 LLVM_READOBJ_DT_FLAG_ENT(DF_1, SYMINTPOSE), 2001 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAUDIT), 2002 LLVM_READOBJ_DT_FLAG_ENT(DF_1, SINGLETON), 2003 LLVM_READOBJ_DT_FLAG_ENT(DF_1, PIE), 2004 }; 2005 2006 static const EnumEntry<unsigned> ElfDynamicDTMipsFlags[] = { 2007 LLVM_READOBJ_DT_FLAG_ENT(RHF, NONE), 2008 LLVM_READOBJ_DT_FLAG_ENT(RHF, QUICKSTART), 2009 LLVM_READOBJ_DT_FLAG_ENT(RHF, NOTPOT), 2010 LLVM_READOBJ_DT_FLAG_ENT(RHS, NO_LIBRARY_REPLACEMENT), 2011 LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_MOVE), 2012 LLVM_READOBJ_DT_FLAG_ENT(RHF, SGI_ONLY), 2013 LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_INIT), 2014 LLVM_READOBJ_DT_FLAG_ENT(RHF, DELTA_C_PLUS_PLUS), 2015 LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_START_INIT), 2016 LLVM_READOBJ_DT_FLAG_ENT(RHF, PIXIE), 2017 LLVM_READOBJ_DT_FLAG_ENT(RHF, DEFAULT_DELAY_LOAD), 2018 LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTART), 2019 LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTARTED), 2020 LLVM_READOBJ_DT_FLAG_ENT(RHF, CORD), 2021 LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_UNRES_UNDEF), 2022 LLVM_READOBJ_DT_FLAG_ENT(RHF, RLD_ORDER_SAFE) 2023 }; 2024 2025 #undef LLVM_READOBJ_DT_FLAG_ENT 2026 2027 template <typename T, typename TFlag> 2028 void printFlags(T Value, ArrayRef<EnumEntry<TFlag>> Flags, raw_ostream &OS) { 2029 SmallVector<EnumEntry<TFlag>, 10> SetFlags; 2030 for (const EnumEntry<TFlag> &Flag : Flags) 2031 if (Flag.Value != 0 && (Value & Flag.Value) == Flag.Value) 2032 SetFlags.push_back(Flag); 2033 2034 for (const EnumEntry<TFlag> &Flag : SetFlags) 2035 OS << Flag.Name << " "; 2036 } 2037 2038 template <class ELFT> 2039 const typename ELFT::Shdr * 2040 ELFDumper<ELFT>::findSectionByName(StringRef Name) const { 2041 for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) { 2042 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Shdr)) { 2043 if (*NameOrErr == Name) 2044 return &Shdr; 2045 } else { 2046 reportUniqueWarning("unable to read the name of " + describe(Shdr) + 2047 ": " + toString(NameOrErr.takeError())); 2048 } 2049 } 2050 return nullptr; 2051 } 2052 2053 template <class ELFT> 2054 std::string ELFDumper<ELFT>::getDynamicEntry(uint64_t Type, 2055 uint64_t Value) const { 2056 auto FormatHexValue = [](uint64_t V) { 2057 std::string Str; 2058 raw_string_ostream OS(Str); 2059 const char *ConvChar = 2060 (opts::Output == opts::GNU) ? "0x%" PRIx64 : "0x%" PRIX64; 2061 OS << format(ConvChar, V); 2062 return OS.str(); 2063 }; 2064 2065 auto FormatFlags = [](uint64_t V, 2066 llvm::ArrayRef<llvm::EnumEntry<unsigned int>> Array) { 2067 std::string Str; 2068 raw_string_ostream OS(Str); 2069 printFlags(V, Array, OS); 2070 return OS.str(); 2071 }; 2072 2073 // Handle custom printing of architecture specific tags 2074 switch (Obj.getHeader().e_machine) { 2075 case EM_AARCH64: 2076 switch (Type) { 2077 case DT_AARCH64_BTI_PLT: 2078 case DT_AARCH64_PAC_PLT: 2079 case DT_AARCH64_VARIANT_PCS: 2080 return std::to_string(Value); 2081 default: 2082 break; 2083 } 2084 break; 2085 case EM_HEXAGON: 2086 switch (Type) { 2087 case DT_HEXAGON_VER: 2088 return std::to_string(Value); 2089 case DT_HEXAGON_SYMSZ: 2090 case DT_HEXAGON_PLT: 2091 return FormatHexValue(Value); 2092 default: 2093 break; 2094 } 2095 break; 2096 case EM_MIPS: 2097 switch (Type) { 2098 case DT_MIPS_RLD_VERSION: 2099 case DT_MIPS_LOCAL_GOTNO: 2100 case DT_MIPS_SYMTABNO: 2101 case DT_MIPS_UNREFEXTNO: 2102 return std::to_string(Value); 2103 case DT_MIPS_TIME_STAMP: 2104 case DT_MIPS_ICHECKSUM: 2105 case DT_MIPS_IVERSION: 2106 case DT_MIPS_BASE_ADDRESS: 2107 case DT_MIPS_MSYM: 2108 case DT_MIPS_CONFLICT: 2109 case DT_MIPS_LIBLIST: 2110 case DT_MIPS_CONFLICTNO: 2111 case DT_MIPS_LIBLISTNO: 2112 case DT_MIPS_GOTSYM: 2113 case DT_MIPS_HIPAGENO: 2114 case DT_MIPS_RLD_MAP: 2115 case DT_MIPS_DELTA_CLASS: 2116 case DT_MIPS_DELTA_CLASS_NO: 2117 case DT_MIPS_DELTA_INSTANCE: 2118 case DT_MIPS_DELTA_RELOC: 2119 case DT_MIPS_DELTA_RELOC_NO: 2120 case DT_MIPS_DELTA_SYM: 2121 case DT_MIPS_DELTA_SYM_NO: 2122 case DT_MIPS_DELTA_CLASSSYM: 2123 case DT_MIPS_DELTA_CLASSSYM_NO: 2124 case DT_MIPS_CXX_FLAGS: 2125 case DT_MIPS_PIXIE_INIT: 2126 case DT_MIPS_SYMBOL_LIB: 2127 case DT_MIPS_LOCALPAGE_GOTIDX: 2128 case DT_MIPS_LOCAL_GOTIDX: 2129 case DT_MIPS_HIDDEN_GOTIDX: 2130 case DT_MIPS_PROTECTED_GOTIDX: 2131 case DT_MIPS_OPTIONS: 2132 case DT_MIPS_INTERFACE: 2133 case DT_MIPS_DYNSTR_ALIGN: 2134 case DT_MIPS_INTERFACE_SIZE: 2135 case DT_MIPS_RLD_TEXT_RESOLVE_ADDR: 2136 case DT_MIPS_PERF_SUFFIX: 2137 case DT_MIPS_COMPACT_SIZE: 2138 case DT_MIPS_GP_VALUE: 2139 case DT_MIPS_AUX_DYNAMIC: 2140 case DT_MIPS_PLTGOT: 2141 case DT_MIPS_RWPLT: 2142 case DT_MIPS_RLD_MAP_REL: 2143 return FormatHexValue(Value); 2144 case DT_MIPS_FLAGS: 2145 return FormatFlags(Value, makeArrayRef(ElfDynamicDTMipsFlags)); 2146 default: 2147 break; 2148 } 2149 break; 2150 default: 2151 break; 2152 } 2153 2154 switch (Type) { 2155 case DT_PLTREL: 2156 if (Value == DT_REL) 2157 return "REL"; 2158 if (Value == DT_RELA) 2159 return "RELA"; 2160 LLVM_FALLTHROUGH; 2161 case DT_PLTGOT: 2162 case DT_HASH: 2163 case DT_STRTAB: 2164 case DT_SYMTAB: 2165 case DT_RELA: 2166 case DT_INIT: 2167 case DT_FINI: 2168 case DT_REL: 2169 case DT_JMPREL: 2170 case DT_INIT_ARRAY: 2171 case DT_FINI_ARRAY: 2172 case DT_PREINIT_ARRAY: 2173 case DT_DEBUG: 2174 case DT_VERDEF: 2175 case DT_VERNEED: 2176 case DT_VERSYM: 2177 case DT_GNU_HASH: 2178 case DT_NULL: 2179 return FormatHexValue(Value); 2180 case DT_RELACOUNT: 2181 case DT_RELCOUNT: 2182 case DT_VERDEFNUM: 2183 case DT_VERNEEDNUM: 2184 return std::to_string(Value); 2185 case DT_PLTRELSZ: 2186 case DT_RELASZ: 2187 case DT_RELAENT: 2188 case DT_STRSZ: 2189 case DT_SYMENT: 2190 case DT_RELSZ: 2191 case DT_RELENT: 2192 case DT_INIT_ARRAYSZ: 2193 case DT_FINI_ARRAYSZ: 2194 case DT_PREINIT_ARRAYSZ: 2195 case DT_ANDROID_RELSZ: 2196 case DT_ANDROID_RELASZ: 2197 return std::to_string(Value) + " (bytes)"; 2198 case DT_NEEDED: 2199 case DT_SONAME: 2200 case DT_AUXILIARY: 2201 case DT_USED: 2202 case DT_FILTER: 2203 case DT_RPATH: 2204 case DT_RUNPATH: { 2205 const std::map<uint64_t, const char *> TagNames = { 2206 {DT_NEEDED, "Shared library"}, {DT_SONAME, "Library soname"}, 2207 {DT_AUXILIARY, "Auxiliary library"}, {DT_USED, "Not needed object"}, 2208 {DT_FILTER, "Filter library"}, {DT_RPATH, "Library rpath"}, 2209 {DT_RUNPATH, "Library runpath"}, 2210 }; 2211 2212 return (Twine(TagNames.at(Type)) + ": [" + getDynamicString(Value) + "]") 2213 .str(); 2214 } 2215 case DT_FLAGS: 2216 return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags)); 2217 case DT_FLAGS_1: 2218 return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags1)); 2219 default: 2220 return FormatHexValue(Value); 2221 } 2222 } 2223 2224 template <class ELFT> 2225 StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const { 2226 if (DynamicStringTable.empty() && !DynamicStringTable.data()) { 2227 reportUniqueWarning("string table was not found"); 2228 return "<?>"; 2229 } 2230 2231 auto WarnAndReturn = [this](const Twine &Msg, uint64_t Offset) { 2232 reportUniqueWarning("string table at offset 0x" + Twine::utohexstr(Offset) + 2233 Msg); 2234 return "<?>"; 2235 }; 2236 2237 const uint64_t FileSize = Obj.getBufSize(); 2238 const uint64_t Offset = 2239 (const uint8_t *)DynamicStringTable.data() - Obj.base(); 2240 if (DynamicStringTable.size() > FileSize - Offset) 2241 return WarnAndReturn(" with size 0x" + 2242 Twine::utohexstr(DynamicStringTable.size()) + 2243 " goes past the end of the file (0x" + 2244 Twine::utohexstr(FileSize) + ")", 2245 Offset); 2246 2247 if (Value >= DynamicStringTable.size()) 2248 return WarnAndReturn( 2249 ": unable to read the string at 0x" + Twine::utohexstr(Offset + Value) + 2250 ": it goes past the end of the table (0x" + 2251 Twine::utohexstr(Offset + DynamicStringTable.size()) + ")", 2252 Offset); 2253 2254 if (DynamicStringTable.back() != '\0') 2255 return WarnAndReturn(": unable to read the string at 0x" + 2256 Twine::utohexstr(Offset + Value) + 2257 ": the string table is not null-terminated", 2258 Offset); 2259 2260 return DynamicStringTable.data() + Value; 2261 } 2262 2263 template <class ELFT> void ELFDumper<ELFT>::printUnwindInfo() { 2264 DwarfCFIEH::PrinterContext<ELFT> Ctx(W, ObjF); 2265 Ctx.printUnwindInformation(); 2266 } 2267 2268 // The namespace is needed to fix the compilation with GCC older than 7.0+. 2269 namespace { 2270 template <> void ELFDumper<ELF32LE>::printUnwindInfo() { 2271 if (Obj.getHeader().e_machine == EM_ARM) { 2272 ARM::EHABI::PrinterContext<ELF32LE> Ctx(W, Obj, ObjF.getFileName(), 2273 DotSymtabSec); 2274 Ctx.PrintUnwindInformation(); 2275 } 2276 DwarfCFIEH::PrinterContext<ELF32LE> Ctx(W, ObjF); 2277 Ctx.printUnwindInformation(); 2278 } 2279 } // namespace 2280 2281 template <class ELFT> void ELFDumper<ELFT>::printNeededLibraries() { 2282 ListScope D(W, "NeededLibraries"); 2283 2284 std::vector<StringRef> Libs; 2285 for (const auto &Entry : dynamic_table()) 2286 if (Entry.d_tag == ELF::DT_NEEDED) 2287 Libs.push_back(getDynamicString(Entry.d_un.d_val)); 2288 2289 llvm::sort(Libs); 2290 2291 for (StringRef L : Libs) 2292 W.startLine() << L << "\n"; 2293 } 2294 2295 template <class ELFT> 2296 static Error checkHashTable(const ELFDumper<ELFT> &Dumper, 2297 const typename ELFT::Hash *H, 2298 bool *IsHeaderValid = nullptr) { 2299 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile(); 2300 const uint64_t SecOffset = (const uint8_t *)H - Obj.base(); 2301 if (Dumper.getHashTableEntSize() == 8) { 2302 auto It = llvm::find_if(ElfMachineType, [&](const EnumEntry<unsigned> &E) { 2303 return E.Value == Obj.getHeader().e_machine; 2304 }); 2305 if (IsHeaderValid) 2306 *IsHeaderValid = false; 2307 return createError("the hash table at 0x" + Twine::utohexstr(SecOffset) + 2308 " is not supported: it contains non-standard 8 " 2309 "byte entries on " + 2310 It->AltName + " platform"); 2311 } 2312 2313 auto MakeError = [&](const Twine &Msg = "") { 2314 return createError("the hash table at offset 0x" + 2315 Twine::utohexstr(SecOffset) + 2316 " goes past the end of the file (0x" + 2317 Twine::utohexstr(Obj.getBufSize()) + ")" + Msg); 2318 }; 2319 2320 // Each SHT_HASH section starts from two 32-bit fields: nbucket and nchain. 2321 const unsigned HeaderSize = 2 * sizeof(typename ELFT::Word); 2322 2323 if (IsHeaderValid) 2324 *IsHeaderValid = Obj.getBufSize() - SecOffset >= HeaderSize; 2325 2326 if (Obj.getBufSize() - SecOffset < HeaderSize) 2327 return MakeError(); 2328 2329 if (Obj.getBufSize() - SecOffset - HeaderSize < 2330 ((uint64_t)H->nbucket + H->nchain) * sizeof(typename ELFT::Word)) 2331 return MakeError(", nbucket = " + Twine(H->nbucket) + 2332 ", nchain = " + Twine(H->nchain)); 2333 return Error::success(); 2334 } 2335 2336 template <class ELFT> 2337 static Error checkGNUHashTable(const ELFFile<ELFT> &Obj, 2338 const typename ELFT::GnuHash *GnuHashTable, 2339 bool *IsHeaderValid = nullptr) { 2340 const uint8_t *TableData = reinterpret_cast<const uint8_t *>(GnuHashTable); 2341 assert(TableData >= Obj.base() && TableData < Obj.base() + Obj.getBufSize() && 2342 "GnuHashTable must always point to a location inside the file"); 2343 2344 uint64_t TableOffset = TableData - Obj.base(); 2345 if (IsHeaderValid) 2346 *IsHeaderValid = TableOffset + /*Header size:*/ 16 < Obj.getBufSize(); 2347 if (TableOffset + 16 + (uint64_t)GnuHashTable->nbuckets * 4 + 2348 (uint64_t)GnuHashTable->maskwords * sizeof(typename ELFT::Off) >= 2349 Obj.getBufSize()) 2350 return createError("unable to dump the SHT_GNU_HASH " 2351 "section at 0x" + 2352 Twine::utohexstr(TableOffset) + 2353 ": it goes past the end of the file"); 2354 return Error::success(); 2355 } 2356 2357 template <typename ELFT> void ELFDumper<ELFT>::printHashTable() { 2358 DictScope D(W, "HashTable"); 2359 if (!HashTable) 2360 return; 2361 2362 bool IsHeaderValid; 2363 Error Err = checkHashTable(*this, HashTable, &IsHeaderValid); 2364 if (IsHeaderValid) { 2365 W.printNumber("Num Buckets", HashTable->nbucket); 2366 W.printNumber("Num Chains", HashTable->nchain); 2367 } 2368 2369 if (Err) { 2370 reportUniqueWarning(std::move(Err)); 2371 return; 2372 } 2373 2374 W.printList("Buckets", HashTable->buckets()); 2375 W.printList("Chains", HashTable->chains()); 2376 } 2377 2378 template <class ELFT> 2379 static Expected<ArrayRef<typename ELFT::Word>> 2380 getGnuHashTableChains(Optional<DynRegionInfo> DynSymRegion, 2381 const typename ELFT::GnuHash *GnuHashTable) { 2382 if (!DynSymRegion) 2383 return createError("no dynamic symbol table found"); 2384 2385 ArrayRef<typename ELFT::Sym> DynSymTable = 2386 DynSymRegion->template getAsArrayRef<typename ELFT::Sym>(); 2387 size_t NumSyms = DynSymTable.size(); 2388 if (!NumSyms) 2389 return createError("the dynamic symbol table is empty"); 2390 2391 if (GnuHashTable->symndx < NumSyms) 2392 return GnuHashTable->values(NumSyms); 2393 2394 // A normal empty GNU hash table section produced by linker might have 2395 // symndx set to the number of dynamic symbols + 1 (for the zero symbol) 2396 // and have dummy null values in the Bloom filter and in the buckets 2397 // vector (or no values at all). It happens because the value of symndx is not 2398 // important for dynamic loaders when the GNU hash table is empty. They just 2399 // skip the whole object during symbol lookup. In such cases, the symndx value 2400 // is irrelevant and we should not report a warning. 2401 ArrayRef<typename ELFT::Word> Buckets = GnuHashTable->buckets(); 2402 if (!llvm::all_of(Buckets, [](typename ELFT::Word V) { return V == 0; })) 2403 return createError( 2404 "the first hashed symbol index (" + Twine(GnuHashTable->symndx) + 2405 ") is greater than or equal to the number of dynamic symbols (" + 2406 Twine(NumSyms) + ")"); 2407 // There is no way to represent an array of (dynamic symbols count - symndx) 2408 // length. 2409 return ArrayRef<typename ELFT::Word>(); 2410 } 2411 2412 template <typename ELFT> 2413 void ELFDumper<ELFT>::printGnuHashTable() { 2414 DictScope D(W, "GnuHashTable"); 2415 if (!GnuHashTable) 2416 return; 2417 2418 bool IsHeaderValid; 2419 Error Err = checkGNUHashTable<ELFT>(Obj, GnuHashTable, &IsHeaderValid); 2420 if (IsHeaderValid) { 2421 W.printNumber("Num Buckets", GnuHashTable->nbuckets); 2422 W.printNumber("First Hashed Symbol Index", GnuHashTable->symndx); 2423 W.printNumber("Num Mask Words", GnuHashTable->maskwords); 2424 W.printNumber("Shift Count", GnuHashTable->shift2); 2425 } 2426 2427 if (Err) { 2428 reportUniqueWarning(std::move(Err)); 2429 return; 2430 } 2431 2432 ArrayRef<typename ELFT::Off> BloomFilter = GnuHashTable->filter(); 2433 W.printHexList("Bloom Filter", BloomFilter); 2434 2435 ArrayRef<Elf_Word> Buckets = GnuHashTable->buckets(); 2436 W.printList("Buckets", Buckets); 2437 2438 Expected<ArrayRef<Elf_Word>> Chains = 2439 getGnuHashTableChains<ELFT>(DynSymRegion, GnuHashTable); 2440 if (!Chains) { 2441 reportUniqueWarning("unable to dump 'Values' for the SHT_GNU_HASH " 2442 "section: " + 2443 toString(Chains.takeError())); 2444 return; 2445 } 2446 2447 W.printHexList("Values", *Chains); 2448 } 2449 2450 template <typename ELFT> void ELFDumper<ELFT>::printLoadName() { 2451 StringRef SOName = "<Not found>"; 2452 if (SONameOffset) 2453 SOName = getDynamicString(*SONameOffset); 2454 W.printString("LoadName", SOName); 2455 } 2456 2457 template <class ELFT> void ELFDumper<ELFT>::printArchSpecificInfo() { 2458 switch (Obj.getHeader().e_machine) { 2459 case EM_ARM: 2460 case EM_RISCV: 2461 printAttributes(); 2462 break; 2463 case EM_MIPS: { 2464 printMipsABIFlags(); 2465 printMipsOptions(); 2466 printMipsReginfo(); 2467 MipsGOTParser<ELFT> Parser(*this); 2468 if (Error E = Parser.findGOT(dynamic_table(), dynamic_symbols())) 2469 reportUniqueWarning(std::move(E)); 2470 else if (!Parser.isGotEmpty()) 2471 printMipsGOT(Parser); 2472 2473 if (Error E = Parser.findPLT(dynamic_table())) 2474 reportUniqueWarning(std::move(E)); 2475 else if (!Parser.isPltEmpty()) 2476 printMipsPLT(Parser); 2477 break; 2478 } 2479 default: 2480 break; 2481 } 2482 } 2483 2484 template <class ELFT> void ELFDumper<ELFT>::printAttributes() { 2485 if (!Obj.isLE()) { 2486 W.startLine() << "Attributes not implemented.\n"; 2487 return; 2488 } 2489 2490 const unsigned Machine = Obj.getHeader().e_machine; 2491 assert((Machine == EM_ARM || Machine == EM_RISCV) && 2492 "Attributes not implemented."); 2493 2494 DictScope BA(W, "BuildAttributes"); 2495 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) { 2496 if (Sec.sh_type != ELF::SHT_ARM_ATTRIBUTES && 2497 Sec.sh_type != ELF::SHT_RISCV_ATTRIBUTES) 2498 continue; 2499 2500 ArrayRef<uint8_t> Contents; 2501 if (Expected<ArrayRef<uint8_t>> ContentOrErr = 2502 Obj.getSectionContents(Sec)) { 2503 Contents = *ContentOrErr; 2504 if (Contents.empty()) { 2505 reportUniqueWarning("the " + describe(Sec) + " is empty"); 2506 continue; 2507 } 2508 } else { 2509 reportUniqueWarning("unable to read the content of the " + describe(Sec) + 2510 ": " + toString(ContentOrErr.takeError())); 2511 continue; 2512 } 2513 2514 W.printHex("FormatVersion", Contents[0]); 2515 2516 auto ParseAttrubutes = [&]() { 2517 if (Machine == EM_ARM) 2518 return ARMAttributeParser(&W).parse(Contents, support::little); 2519 return RISCVAttributeParser(&W).parse(Contents, support::little); 2520 }; 2521 2522 if (Error E = ParseAttrubutes()) 2523 reportUniqueWarning("unable to dump attributes from the " + 2524 describe(Sec) + ": " + toString(std::move(E))); 2525 } 2526 } 2527 2528 namespace { 2529 2530 template <class ELFT> class MipsGOTParser { 2531 public: 2532 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT) 2533 using Entry = typename ELFT::Addr; 2534 using Entries = ArrayRef<Entry>; 2535 2536 const bool IsStatic; 2537 const ELFFile<ELFT> &Obj; 2538 const ELFDumper<ELFT> &Dumper; 2539 2540 MipsGOTParser(const ELFDumper<ELFT> &D); 2541 Error findGOT(Elf_Dyn_Range DynTable, Elf_Sym_Range DynSyms); 2542 Error findPLT(Elf_Dyn_Range DynTable); 2543 2544 bool isGotEmpty() const { return GotEntries.empty(); } 2545 bool isPltEmpty() const { return PltEntries.empty(); } 2546 2547 uint64_t getGp() const; 2548 2549 const Entry *getGotLazyResolver() const; 2550 const Entry *getGotModulePointer() const; 2551 const Entry *getPltLazyResolver() const; 2552 const Entry *getPltModulePointer() const; 2553 2554 Entries getLocalEntries() const; 2555 Entries getGlobalEntries() const; 2556 Entries getOtherEntries() const; 2557 Entries getPltEntries() const; 2558 2559 uint64_t getGotAddress(const Entry * E) const; 2560 int64_t getGotOffset(const Entry * E) const; 2561 const Elf_Sym *getGotSym(const Entry *E) const; 2562 2563 uint64_t getPltAddress(const Entry * E) const; 2564 const Elf_Sym *getPltSym(const Entry *E) const; 2565 2566 StringRef getPltStrTable() const { return PltStrTable; } 2567 const Elf_Shdr *getPltSymTable() const { return PltSymTable; } 2568 2569 private: 2570 const Elf_Shdr *GotSec; 2571 size_t LocalNum; 2572 size_t GlobalNum; 2573 2574 const Elf_Shdr *PltSec; 2575 const Elf_Shdr *PltRelSec; 2576 const Elf_Shdr *PltSymTable; 2577 StringRef FileName; 2578 2579 Elf_Sym_Range GotDynSyms; 2580 StringRef PltStrTable; 2581 2582 Entries GotEntries; 2583 Entries PltEntries; 2584 }; 2585 2586 } // end anonymous namespace 2587 2588 template <class ELFT> 2589 MipsGOTParser<ELFT>::MipsGOTParser(const ELFDumper<ELFT> &D) 2590 : IsStatic(D.dynamic_table().empty()), Obj(D.getElfObject().getELFFile()), 2591 Dumper(D), GotSec(nullptr), LocalNum(0), GlobalNum(0), PltSec(nullptr), 2592 PltRelSec(nullptr), PltSymTable(nullptr), 2593 FileName(D.getElfObject().getFileName()) {} 2594 2595 template <class ELFT> 2596 Error MipsGOTParser<ELFT>::findGOT(Elf_Dyn_Range DynTable, 2597 Elf_Sym_Range DynSyms) { 2598 // See "Global Offset Table" in Chapter 5 in the following document 2599 // for detailed GOT description. 2600 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 2601 2602 // Find static GOT secton. 2603 if (IsStatic) { 2604 GotSec = Dumper.findSectionByName(".got"); 2605 if (!GotSec) 2606 return Error::success(); 2607 2608 ArrayRef<uint8_t> Content = 2609 unwrapOrError(FileName, Obj.getSectionContents(*GotSec)); 2610 GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()), 2611 Content.size() / sizeof(Entry)); 2612 LocalNum = GotEntries.size(); 2613 return Error::success(); 2614 } 2615 2616 // Lookup dynamic table tags which define the GOT layout. 2617 Optional<uint64_t> DtPltGot; 2618 Optional<uint64_t> DtLocalGotNum; 2619 Optional<uint64_t> DtGotSym; 2620 for (const auto &Entry : DynTable) { 2621 switch (Entry.getTag()) { 2622 case ELF::DT_PLTGOT: 2623 DtPltGot = Entry.getVal(); 2624 break; 2625 case ELF::DT_MIPS_LOCAL_GOTNO: 2626 DtLocalGotNum = Entry.getVal(); 2627 break; 2628 case ELF::DT_MIPS_GOTSYM: 2629 DtGotSym = Entry.getVal(); 2630 break; 2631 } 2632 } 2633 2634 if (!DtPltGot && !DtLocalGotNum && !DtGotSym) 2635 return Error::success(); 2636 2637 if (!DtPltGot) 2638 return createError("cannot find PLTGOT dynamic tag"); 2639 if (!DtLocalGotNum) 2640 return createError("cannot find MIPS_LOCAL_GOTNO dynamic tag"); 2641 if (!DtGotSym) 2642 return createError("cannot find MIPS_GOTSYM dynamic tag"); 2643 2644 size_t DynSymTotal = DynSyms.size(); 2645 if (*DtGotSym > DynSymTotal) 2646 return createError("DT_MIPS_GOTSYM value (" + Twine(*DtGotSym) + 2647 ") exceeds the number of dynamic symbols (" + 2648 Twine(DynSymTotal) + ")"); 2649 2650 GotSec = findNotEmptySectionByAddress(Obj, FileName, *DtPltGot); 2651 if (!GotSec) 2652 return createError("there is no non-empty GOT section at 0x" + 2653 Twine::utohexstr(*DtPltGot)); 2654 2655 LocalNum = *DtLocalGotNum; 2656 GlobalNum = DynSymTotal - *DtGotSym; 2657 2658 ArrayRef<uint8_t> Content = 2659 unwrapOrError(FileName, Obj.getSectionContents(*GotSec)); 2660 GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()), 2661 Content.size() / sizeof(Entry)); 2662 GotDynSyms = DynSyms.drop_front(*DtGotSym); 2663 2664 return Error::success(); 2665 } 2666 2667 template <class ELFT> 2668 Error MipsGOTParser<ELFT>::findPLT(Elf_Dyn_Range DynTable) { 2669 // Lookup dynamic table tags which define the PLT layout. 2670 Optional<uint64_t> DtMipsPltGot; 2671 Optional<uint64_t> DtJmpRel; 2672 for (const auto &Entry : DynTable) { 2673 switch (Entry.getTag()) { 2674 case ELF::DT_MIPS_PLTGOT: 2675 DtMipsPltGot = Entry.getVal(); 2676 break; 2677 case ELF::DT_JMPREL: 2678 DtJmpRel = Entry.getVal(); 2679 break; 2680 } 2681 } 2682 2683 if (!DtMipsPltGot && !DtJmpRel) 2684 return Error::success(); 2685 2686 // Find PLT section. 2687 if (!DtMipsPltGot) 2688 return createError("cannot find MIPS_PLTGOT dynamic tag"); 2689 if (!DtJmpRel) 2690 return createError("cannot find JMPREL dynamic tag"); 2691 2692 PltSec = findNotEmptySectionByAddress(Obj, FileName, *DtMipsPltGot); 2693 if (!PltSec) 2694 return createError("there is no non-empty PLTGOT section at 0x" + 2695 Twine::utohexstr(*DtMipsPltGot)); 2696 2697 PltRelSec = findNotEmptySectionByAddress(Obj, FileName, *DtJmpRel); 2698 if (!PltRelSec) 2699 return createError("there is no non-empty RELPLT section at 0x" + 2700 Twine::utohexstr(*DtJmpRel)); 2701 2702 if (Expected<ArrayRef<uint8_t>> PltContentOrErr = 2703 Obj.getSectionContents(*PltSec)) 2704 PltEntries = 2705 Entries(reinterpret_cast<const Entry *>(PltContentOrErr->data()), 2706 PltContentOrErr->size() / sizeof(Entry)); 2707 else 2708 return createError("unable to read PLTGOT section content: " + 2709 toString(PltContentOrErr.takeError())); 2710 2711 if (Expected<const Elf_Shdr *> PltSymTableOrErr = 2712 Obj.getSection(PltRelSec->sh_link)) 2713 PltSymTable = *PltSymTableOrErr; 2714 else 2715 return createError("unable to get a symbol table linked to the " + 2716 describe(Obj, *PltRelSec) + ": " + 2717 toString(PltSymTableOrErr.takeError())); 2718 2719 if (Expected<StringRef> StrTabOrErr = 2720 Obj.getStringTableForSymtab(*PltSymTable)) 2721 PltStrTable = *StrTabOrErr; 2722 else 2723 return createError("unable to get a string table for the " + 2724 describe(Obj, *PltSymTable) + ": " + 2725 toString(StrTabOrErr.takeError())); 2726 2727 return Error::success(); 2728 } 2729 2730 template <class ELFT> uint64_t MipsGOTParser<ELFT>::getGp() const { 2731 return GotSec->sh_addr + 0x7ff0; 2732 } 2733 2734 template <class ELFT> 2735 const typename MipsGOTParser<ELFT>::Entry * 2736 MipsGOTParser<ELFT>::getGotLazyResolver() const { 2737 return LocalNum > 0 ? &GotEntries[0] : nullptr; 2738 } 2739 2740 template <class ELFT> 2741 const typename MipsGOTParser<ELFT>::Entry * 2742 MipsGOTParser<ELFT>::getGotModulePointer() const { 2743 if (LocalNum < 2) 2744 return nullptr; 2745 const Entry &E = GotEntries[1]; 2746 if ((E >> (sizeof(Entry) * 8 - 1)) == 0) 2747 return nullptr; 2748 return &E; 2749 } 2750 2751 template <class ELFT> 2752 typename MipsGOTParser<ELFT>::Entries 2753 MipsGOTParser<ELFT>::getLocalEntries() const { 2754 size_t Skip = getGotModulePointer() ? 2 : 1; 2755 if (LocalNum - Skip <= 0) 2756 return Entries(); 2757 return GotEntries.slice(Skip, LocalNum - Skip); 2758 } 2759 2760 template <class ELFT> 2761 typename MipsGOTParser<ELFT>::Entries 2762 MipsGOTParser<ELFT>::getGlobalEntries() const { 2763 if (GlobalNum == 0) 2764 return Entries(); 2765 return GotEntries.slice(LocalNum, GlobalNum); 2766 } 2767 2768 template <class ELFT> 2769 typename MipsGOTParser<ELFT>::Entries 2770 MipsGOTParser<ELFT>::getOtherEntries() const { 2771 size_t OtherNum = GotEntries.size() - LocalNum - GlobalNum; 2772 if (OtherNum == 0) 2773 return Entries(); 2774 return GotEntries.slice(LocalNum + GlobalNum, OtherNum); 2775 } 2776 2777 template <class ELFT> 2778 uint64_t MipsGOTParser<ELFT>::getGotAddress(const Entry *E) const { 2779 int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry); 2780 return GotSec->sh_addr + Offset; 2781 } 2782 2783 template <class ELFT> 2784 int64_t MipsGOTParser<ELFT>::getGotOffset(const Entry *E) const { 2785 int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry); 2786 return Offset - 0x7ff0; 2787 } 2788 2789 template <class ELFT> 2790 const typename MipsGOTParser<ELFT>::Elf_Sym * 2791 MipsGOTParser<ELFT>::getGotSym(const Entry *E) const { 2792 int64_t Offset = std::distance(GotEntries.data(), E); 2793 return &GotDynSyms[Offset - LocalNum]; 2794 } 2795 2796 template <class ELFT> 2797 const typename MipsGOTParser<ELFT>::Entry * 2798 MipsGOTParser<ELFT>::getPltLazyResolver() const { 2799 return PltEntries.empty() ? nullptr : &PltEntries[0]; 2800 } 2801 2802 template <class ELFT> 2803 const typename MipsGOTParser<ELFT>::Entry * 2804 MipsGOTParser<ELFT>::getPltModulePointer() const { 2805 return PltEntries.size() < 2 ? nullptr : &PltEntries[1]; 2806 } 2807 2808 template <class ELFT> 2809 typename MipsGOTParser<ELFT>::Entries 2810 MipsGOTParser<ELFT>::getPltEntries() const { 2811 if (PltEntries.size() <= 2) 2812 return Entries(); 2813 return PltEntries.slice(2, PltEntries.size() - 2); 2814 } 2815 2816 template <class ELFT> 2817 uint64_t MipsGOTParser<ELFT>::getPltAddress(const Entry *E) const { 2818 int64_t Offset = std::distance(PltEntries.data(), E) * sizeof(Entry); 2819 return PltSec->sh_addr + Offset; 2820 } 2821 2822 template <class ELFT> 2823 const typename MipsGOTParser<ELFT>::Elf_Sym * 2824 MipsGOTParser<ELFT>::getPltSym(const Entry *E) const { 2825 int64_t Offset = std::distance(getPltEntries().data(), E); 2826 if (PltRelSec->sh_type == ELF::SHT_REL) { 2827 Elf_Rel_Range Rels = unwrapOrError(FileName, Obj.rels(*PltRelSec)); 2828 return unwrapOrError(FileName, 2829 Obj.getRelocationSymbol(Rels[Offset], PltSymTable)); 2830 } else { 2831 Elf_Rela_Range Rels = unwrapOrError(FileName, Obj.relas(*PltRelSec)); 2832 return unwrapOrError(FileName, 2833 Obj.getRelocationSymbol(Rels[Offset], PltSymTable)); 2834 } 2835 } 2836 2837 static const EnumEntry<unsigned> ElfMipsISAExtType[] = { 2838 {"None", Mips::AFL_EXT_NONE}, 2839 {"Broadcom SB-1", Mips::AFL_EXT_SB1}, 2840 {"Cavium Networks Octeon", Mips::AFL_EXT_OCTEON}, 2841 {"Cavium Networks Octeon2", Mips::AFL_EXT_OCTEON2}, 2842 {"Cavium Networks OcteonP", Mips::AFL_EXT_OCTEONP}, 2843 {"Cavium Networks Octeon3", Mips::AFL_EXT_OCTEON3}, 2844 {"LSI R4010", Mips::AFL_EXT_4010}, 2845 {"Loongson 2E", Mips::AFL_EXT_LOONGSON_2E}, 2846 {"Loongson 2F", Mips::AFL_EXT_LOONGSON_2F}, 2847 {"Loongson 3A", Mips::AFL_EXT_LOONGSON_3A}, 2848 {"MIPS R4650", Mips::AFL_EXT_4650}, 2849 {"MIPS R5900", Mips::AFL_EXT_5900}, 2850 {"MIPS R10000", Mips::AFL_EXT_10000}, 2851 {"NEC VR4100", Mips::AFL_EXT_4100}, 2852 {"NEC VR4111/VR4181", Mips::AFL_EXT_4111}, 2853 {"NEC VR4120", Mips::AFL_EXT_4120}, 2854 {"NEC VR5400", Mips::AFL_EXT_5400}, 2855 {"NEC VR5500", Mips::AFL_EXT_5500}, 2856 {"RMI Xlr", Mips::AFL_EXT_XLR}, 2857 {"Toshiba R3900", Mips::AFL_EXT_3900} 2858 }; 2859 2860 static const EnumEntry<unsigned> ElfMipsASEFlags[] = { 2861 {"DSP", Mips::AFL_ASE_DSP}, 2862 {"DSPR2", Mips::AFL_ASE_DSPR2}, 2863 {"Enhanced VA Scheme", Mips::AFL_ASE_EVA}, 2864 {"MCU", Mips::AFL_ASE_MCU}, 2865 {"MDMX", Mips::AFL_ASE_MDMX}, 2866 {"MIPS-3D", Mips::AFL_ASE_MIPS3D}, 2867 {"MT", Mips::AFL_ASE_MT}, 2868 {"SmartMIPS", Mips::AFL_ASE_SMARTMIPS}, 2869 {"VZ", Mips::AFL_ASE_VIRT}, 2870 {"MSA", Mips::AFL_ASE_MSA}, 2871 {"MIPS16", Mips::AFL_ASE_MIPS16}, 2872 {"microMIPS", Mips::AFL_ASE_MICROMIPS}, 2873 {"XPA", Mips::AFL_ASE_XPA}, 2874 {"CRC", Mips::AFL_ASE_CRC}, 2875 {"GINV", Mips::AFL_ASE_GINV}, 2876 }; 2877 2878 static const EnumEntry<unsigned> ElfMipsFpABIType[] = { 2879 {"Hard or soft float", Mips::Val_GNU_MIPS_ABI_FP_ANY}, 2880 {"Hard float (double precision)", Mips::Val_GNU_MIPS_ABI_FP_DOUBLE}, 2881 {"Hard float (single precision)", Mips::Val_GNU_MIPS_ABI_FP_SINGLE}, 2882 {"Soft float", Mips::Val_GNU_MIPS_ABI_FP_SOFT}, 2883 {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)", 2884 Mips::Val_GNU_MIPS_ABI_FP_OLD_64}, 2885 {"Hard float (32-bit CPU, Any FPU)", Mips::Val_GNU_MIPS_ABI_FP_XX}, 2886 {"Hard float (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64}, 2887 {"Hard float compat (32-bit CPU, 64-bit FPU)", 2888 Mips::Val_GNU_MIPS_ABI_FP_64A} 2889 }; 2890 2891 static const EnumEntry<unsigned> ElfMipsFlags1[] { 2892 {"ODDSPREG", Mips::AFL_FLAGS1_ODDSPREG}, 2893 }; 2894 2895 static int getMipsRegisterSize(uint8_t Flag) { 2896 switch (Flag) { 2897 case Mips::AFL_REG_NONE: 2898 return 0; 2899 case Mips::AFL_REG_32: 2900 return 32; 2901 case Mips::AFL_REG_64: 2902 return 64; 2903 case Mips::AFL_REG_128: 2904 return 128; 2905 default: 2906 return -1; 2907 } 2908 } 2909 2910 template <class ELFT> 2911 static void printMipsReginfoData(ScopedPrinter &W, 2912 const Elf_Mips_RegInfo<ELFT> &Reginfo) { 2913 W.printHex("GP", Reginfo.ri_gp_value); 2914 W.printHex("General Mask", Reginfo.ri_gprmask); 2915 W.printHex("Co-Proc Mask0", Reginfo.ri_cprmask[0]); 2916 W.printHex("Co-Proc Mask1", Reginfo.ri_cprmask[1]); 2917 W.printHex("Co-Proc Mask2", Reginfo.ri_cprmask[2]); 2918 W.printHex("Co-Proc Mask3", Reginfo.ri_cprmask[3]); 2919 } 2920 2921 template <class ELFT> void ELFDumper<ELFT>::printMipsReginfo() { 2922 const Elf_Shdr *RegInfoSec = findSectionByName(".reginfo"); 2923 if (!RegInfoSec) { 2924 W.startLine() << "There is no .reginfo section in the file.\n"; 2925 return; 2926 } 2927 2928 Expected<ArrayRef<uint8_t>> ContentsOrErr = 2929 Obj.getSectionContents(*RegInfoSec); 2930 if (!ContentsOrErr) { 2931 this->reportUniqueWarning( 2932 "unable to read the content of the .reginfo section (" + 2933 describe(*RegInfoSec) + "): " + toString(ContentsOrErr.takeError())); 2934 return; 2935 } 2936 2937 if (ContentsOrErr->size() < sizeof(Elf_Mips_RegInfo<ELFT>)) { 2938 this->reportUniqueWarning("the .reginfo section has an invalid size (0x" + 2939 Twine::utohexstr(ContentsOrErr->size()) + ")"); 2940 return; 2941 } 2942 2943 DictScope GS(W, "MIPS RegInfo"); 2944 printMipsReginfoData(W, *reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>( 2945 ContentsOrErr->data())); 2946 } 2947 2948 template <class ELFT> 2949 static Expected<const Elf_Mips_Options<ELFT> *> 2950 readMipsOptions(const uint8_t *SecBegin, ArrayRef<uint8_t> &SecData, 2951 bool &IsSupported) { 2952 if (SecData.size() < sizeof(Elf_Mips_Options<ELFT>)) 2953 return createError("the .MIPS.options section has an invalid size (0x" + 2954 Twine::utohexstr(SecData.size()) + ")"); 2955 2956 const Elf_Mips_Options<ELFT> *O = 2957 reinterpret_cast<const Elf_Mips_Options<ELFT> *>(SecData.data()); 2958 const uint8_t Size = O->size; 2959 if (Size > SecData.size()) { 2960 const uint64_t Offset = SecData.data() - SecBegin; 2961 const uint64_t SecSize = Offset + SecData.size(); 2962 return createError("a descriptor of size 0x" + Twine::utohexstr(Size) + 2963 " at offset 0x" + Twine::utohexstr(Offset) + 2964 " goes past the end of the .MIPS.options " 2965 "section of size 0x" + 2966 Twine::utohexstr(SecSize)); 2967 } 2968 2969 IsSupported = O->kind == ODK_REGINFO; 2970 const size_t ExpectedSize = 2971 sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>); 2972 2973 if (IsSupported) 2974 if (Size < ExpectedSize) 2975 return createError( 2976 "a .MIPS.options entry of kind " + 2977 Twine(getElfMipsOptionsOdkType(O->kind)) + 2978 " has an invalid size (0x" + Twine::utohexstr(Size) + 2979 "), the expected size is 0x" + Twine::utohexstr(ExpectedSize)); 2980 2981 SecData = SecData.drop_front(Size); 2982 return O; 2983 } 2984 2985 template <class ELFT> void ELFDumper<ELFT>::printMipsOptions() { 2986 const Elf_Shdr *MipsOpts = findSectionByName(".MIPS.options"); 2987 if (!MipsOpts) { 2988 W.startLine() << "There is no .MIPS.options section in the file.\n"; 2989 return; 2990 } 2991 2992 DictScope GS(W, "MIPS Options"); 2993 2994 ArrayRef<uint8_t> Data = 2995 unwrapOrError(ObjF.getFileName(), Obj.getSectionContents(*MipsOpts)); 2996 const uint8_t *const SecBegin = Data.begin(); 2997 while (!Data.empty()) { 2998 bool IsSupported; 2999 Expected<const Elf_Mips_Options<ELFT> *> OptsOrErr = 3000 readMipsOptions<ELFT>(SecBegin, Data, IsSupported); 3001 if (!OptsOrErr) { 3002 reportUniqueWarning(OptsOrErr.takeError()); 3003 break; 3004 } 3005 3006 unsigned Kind = (*OptsOrErr)->kind; 3007 const char *Type = getElfMipsOptionsOdkType(Kind); 3008 if (!IsSupported) { 3009 W.startLine() << "Unsupported MIPS options tag: " << Type << " (" << Kind 3010 << ")\n"; 3011 continue; 3012 } 3013 3014 DictScope GS(W, Type); 3015 if (Kind == ODK_REGINFO) 3016 printMipsReginfoData(W, (*OptsOrErr)->getRegInfo()); 3017 else 3018 llvm_unreachable("unexpected .MIPS.options section descriptor kind"); 3019 } 3020 } 3021 3022 template <class ELFT> void ELFDumper<ELFT>::printStackMap() const { 3023 const Elf_Shdr *StackMapSection = findSectionByName(".llvm_stackmaps"); 3024 if (!StackMapSection) 3025 return; 3026 3027 auto Warn = [&](Error &&E) { 3028 this->reportUniqueWarning("unable to read the stack map from " + 3029 describe(*StackMapSection) + ": " + 3030 toString(std::move(E))); 3031 }; 3032 3033 Expected<ArrayRef<uint8_t>> ContentOrErr = 3034 Obj.getSectionContents(*StackMapSection); 3035 if (!ContentOrErr) { 3036 Warn(ContentOrErr.takeError()); 3037 return; 3038 } 3039 3040 if (Error E = StackMapParser<ELFT::TargetEndianness>::validateHeader( 3041 *ContentOrErr)) { 3042 Warn(std::move(E)); 3043 return; 3044 } 3045 3046 prettyPrintStackMap(W, StackMapParser<ELFT::TargetEndianness>(*ContentOrErr)); 3047 } 3048 3049 template <class ELFT> 3050 void ELFDumper<ELFT>::printReloc(const Relocation<ELFT> &R, unsigned RelIndex, 3051 const Elf_Shdr &Sec, const Elf_Shdr *SymTab) { 3052 Expected<RelSymbol<ELFT>> Target = getRelocationTarget(R, SymTab); 3053 if (!Target) 3054 reportUniqueWarning("unable to print relocation " + Twine(RelIndex) + 3055 " in " + describe(Sec) + ": " + 3056 toString(Target.takeError())); 3057 else 3058 printRelRelaReloc(R, *Target); 3059 } 3060 3061 static inline void printFields(formatted_raw_ostream &OS, StringRef Str1, 3062 StringRef Str2) { 3063 OS.PadToColumn(2u); 3064 OS << Str1; 3065 OS.PadToColumn(37u); 3066 OS << Str2 << "\n"; 3067 OS.flush(); 3068 } 3069 3070 template <class ELFT> 3071 static std::string getSectionHeadersNumString(const ELFFile<ELFT> &Obj, 3072 StringRef FileName) { 3073 const typename ELFT::Ehdr &ElfHeader = Obj.getHeader(); 3074 if (ElfHeader.e_shnum != 0) 3075 return to_string(ElfHeader.e_shnum); 3076 3077 Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections(); 3078 if (!ArrOrErr) { 3079 // In this case we can ignore an error, because we have already reported a 3080 // warning about the broken section header table earlier. 3081 consumeError(ArrOrErr.takeError()); 3082 return "<?>"; 3083 } 3084 3085 if (ArrOrErr->empty()) 3086 return "0"; 3087 return "0 (" + to_string((*ArrOrErr)[0].sh_size) + ")"; 3088 } 3089 3090 template <class ELFT> 3091 static std::string getSectionHeaderTableIndexString(const ELFFile<ELFT> &Obj, 3092 StringRef FileName) { 3093 const typename ELFT::Ehdr &ElfHeader = Obj.getHeader(); 3094 if (ElfHeader.e_shstrndx != SHN_XINDEX) 3095 return to_string(ElfHeader.e_shstrndx); 3096 3097 Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections(); 3098 if (!ArrOrErr) { 3099 // In this case we can ignore an error, because we have already reported a 3100 // warning about the broken section header table earlier. 3101 consumeError(ArrOrErr.takeError()); 3102 return "<?>"; 3103 } 3104 3105 if (ArrOrErr->empty()) 3106 return "65535 (corrupt: out of range)"; 3107 return to_string(ElfHeader.e_shstrndx) + " (" + 3108 to_string((*ArrOrErr)[0].sh_link) + ")"; 3109 } 3110 3111 static const EnumEntry<unsigned> *getObjectFileEnumEntry(unsigned Type) { 3112 auto It = llvm::find_if(ElfObjectFileType, [&](const EnumEntry<unsigned> &E) { 3113 return E.Value == Type; 3114 }); 3115 if (It != makeArrayRef(ElfObjectFileType).end()) 3116 return It; 3117 return nullptr; 3118 } 3119 3120 template <class ELFT> void GNUELFDumper<ELFT>::printFileHeaders() { 3121 const Elf_Ehdr &e = this->Obj.getHeader(); 3122 OS << "ELF Header:\n"; 3123 OS << " Magic: "; 3124 std::string Str; 3125 for (int i = 0; i < ELF::EI_NIDENT; i++) 3126 OS << format(" %02x", static_cast<int>(e.e_ident[i])); 3127 OS << "\n"; 3128 Str = printEnum(e.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass)); 3129 printFields(OS, "Class:", Str); 3130 Str = printEnum(e.e_ident[ELF::EI_DATA], makeArrayRef(ElfDataEncoding)); 3131 printFields(OS, "Data:", Str); 3132 OS.PadToColumn(2u); 3133 OS << "Version:"; 3134 OS.PadToColumn(37u); 3135 OS << to_hexString(e.e_ident[ELF::EI_VERSION]); 3136 if (e.e_version == ELF::EV_CURRENT) 3137 OS << " (current)"; 3138 OS << "\n"; 3139 Str = printEnum(e.e_ident[ELF::EI_OSABI], makeArrayRef(ElfOSABI)); 3140 printFields(OS, "OS/ABI:", Str); 3141 printFields(OS, 3142 "ABI Version:", std::to_string(e.e_ident[ELF::EI_ABIVERSION])); 3143 3144 if (const EnumEntry<unsigned> *E = getObjectFileEnumEntry(e.e_type)) { 3145 Str = E->AltName.str(); 3146 } else { 3147 if (e.e_type >= ET_LOPROC) 3148 Str = "Processor Specific: (" + to_hexString(e.e_type, false) + ")"; 3149 else if (e.e_type >= ET_LOOS) 3150 Str = "OS Specific: (" + to_hexString(e.e_type, false) + ")"; 3151 else 3152 Str = "<unknown>: " + to_hexString(e.e_type, false); 3153 } 3154 printFields(OS, "Type:", Str); 3155 3156 Str = printEnum(e.e_machine, makeArrayRef(ElfMachineType)); 3157 printFields(OS, "Machine:", Str); 3158 Str = "0x" + to_hexString(e.e_version); 3159 printFields(OS, "Version:", Str); 3160 Str = "0x" + to_hexString(e.e_entry); 3161 printFields(OS, "Entry point address:", Str); 3162 Str = to_string(e.e_phoff) + " (bytes into file)"; 3163 printFields(OS, "Start of program headers:", Str); 3164 Str = to_string(e.e_shoff) + " (bytes into file)"; 3165 printFields(OS, "Start of section headers:", Str); 3166 std::string ElfFlags; 3167 if (e.e_machine == EM_MIPS) 3168 ElfFlags = 3169 printFlags(e.e_flags, makeArrayRef(ElfHeaderMipsFlags), 3170 unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI), 3171 unsigned(ELF::EF_MIPS_MACH)); 3172 else if (e.e_machine == EM_RISCV) 3173 ElfFlags = printFlags(e.e_flags, makeArrayRef(ElfHeaderRISCVFlags)); 3174 Str = "0x" + to_hexString(e.e_flags); 3175 if (!ElfFlags.empty()) 3176 Str = Str + ", " + ElfFlags; 3177 printFields(OS, "Flags:", Str); 3178 Str = to_string(e.e_ehsize) + " (bytes)"; 3179 printFields(OS, "Size of this header:", Str); 3180 Str = to_string(e.e_phentsize) + " (bytes)"; 3181 printFields(OS, "Size of program headers:", Str); 3182 Str = to_string(e.e_phnum); 3183 printFields(OS, "Number of program headers:", Str); 3184 Str = to_string(e.e_shentsize) + " (bytes)"; 3185 printFields(OS, "Size of section headers:", Str); 3186 Str = getSectionHeadersNumString(this->Obj, this->FileName); 3187 printFields(OS, "Number of section headers:", Str); 3188 Str = getSectionHeaderTableIndexString(this->Obj, this->FileName); 3189 printFields(OS, "Section header string table index:", Str); 3190 } 3191 3192 template <class ELFT> std::vector<GroupSection> ELFDumper<ELFT>::getGroups() { 3193 auto GetSignature = [&](const Elf_Sym &Sym, unsigned SymNdx, 3194 const Elf_Shdr &Symtab) -> StringRef { 3195 Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(Symtab); 3196 if (!StrTableOrErr) { 3197 reportUniqueWarning("unable to get the string table for " + 3198 describe(Symtab) + ": " + 3199 toString(StrTableOrErr.takeError())); 3200 return "<?>"; 3201 } 3202 3203 StringRef Strings = *StrTableOrErr; 3204 if (Sym.st_name >= Strings.size()) { 3205 reportUniqueWarning("unable to get the name of the symbol with index " + 3206 Twine(SymNdx) + ": st_name (0x" + 3207 Twine::utohexstr(Sym.st_name) + 3208 ") is past the end of the string table of size 0x" + 3209 Twine::utohexstr(Strings.size())); 3210 return "<?>"; 3211 } 3212 3213 return StrTableOrErr->data() + Sym.st_name; 3214 }; 3215 3216 std::vector<GroupSection> Ret; 3217 uint64_t I = 0; 3218 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) { 3219 ++I; 3220 if (Sec.sh_type != ELF::SHT_GROUP) 3221 continue; 3222 3223 StringRef Signature = "<?>"; 3224 if (Expected<const Elf_Shdr *> SymtabOrErr = Obj.getSection(Sec.sh_link)) { 3225 if (Expected<const Elf_Sym *> SymOrErr = 3226 Obj.template getEntry<Elf_Sym>(**SymtabOrErr, Sec.sh_info)) 3227 Signature = GetSignature(**SymOrErr, Sec.sh_info, **SymtabOrErr); 3228 else 3229 reportUniqueWarning("unable to get the signature symbol for " + 3230 describe(Sec) + ": " + 3231 toString(SymOrErr.takeError())); 3232 } else { 3233 reportUniqueWarning("unable to get the symbol table for " + 3234 describe(Sec) + ": " + 3235 toString(SymtabOrErr.takeError())); 3236 } 3237 3238 ArrayRef<Elf_Word> Data; 3239 if (Expected<ArrayRef<Elf_Word>> ContentsOrErr = 3240 Obj.template getSectionContentsAsArray<Elf_Word>(Sec)) { 3241 if (ContentsOrErr->empty()) 3242 reportUniqueWarning("unable to read the section group flag from the " + 3243 describe(Sec) + ": the section is empty"); 3244 else 3245 Data = *ContentsOrErr; 3246 } else { 3247 reportUniqueWarning("unable to get the content of the " + describe(Sec) + 3248 ": " + toString(ContentsOrErr.takeError())); 3249 } 3250 3251 Ret.push_back({getPrintableSectionName(Sec), 3252 maybeDemangle(Signature), 3253 Sec.sh_name, 3254 I - 1, 3255 Sec.sh_link, 3256 Sec.sh_info, 3257 Data.empty() ? Elf_Word(0) : Data[0], 3258 {}}); 3259 3260 if (Data.empty()) 3261 continue; 3262 3263 std::vector<GroupMember> &GM = Ret.back().Members; 3264 for (uint32_t Ndx : Data.slice(1)) { 3265 if (Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(Ndx)) { 3266 GM.push_back({getPrintableSectionName(**SecOrErr), Ndx}); 3267 } else { 3268 reportUniqueWarning("unable to get the section with index " + 3269 Twine(Ndx) + " when dumping the " + describe(Sec) + 3270 ": " + toString(SecOrErr.takeError())); 3271 GM.push_back({"<?>", Ndx}); 3272 } 3273 } 3274 } 3275 return Ret; 3276 } 3277 3278 static DenseMap<uint64_t, const GroupSection *> 3279 mapSectionsToGroups(ArrayRef<GroupSection> Groups) { 3280 DenseMap<uint64_t, const GroupSection *> Ret; 3281 for (const GroupSection &G : Groups) 3282 for (const GroupMember &GM : G.Members) 3283 Ret.insert({GM.Index, &G}); 3284 return Ret; 3285 } 3286 3287 template <class ELFT> void GNUELFDumper<ELFT>::printGroupSections() { 3288 std::vector<GroupSection> V = this->getGroups(); 3289 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V); 3290 for (const GroupSection &G : V) { 3291 OS << "\n" 3292 << getGroupType(G.Type) << " group section [" 3293 << format_decimal(G.Index, 5) << "] `" << G.Name << "' [" << G.Signature 3294 << "] contains " << G.Members.size() << " sections:\n" 3295 << " [Index] Name\n"; 3296 for (const GroupMember &GM : G.Members) { 3297 const GroupSection *MainGroup = Map[GM.Index]; 3298 if (MainGroup != &G) 3299 this->reportUniqueWarning( 3300 "section with index " + Twine(GM.Index) + 3301 ", included in the group section with index " + 3302 Twine(MainGroup->Index) + 3303 ", was also found in the group section with index " + 3304 Twine(G.Index)); 3305 OS << " [" << format_decimal(GM.Index, 5) << "] " << GM.Name << "\n"; 3306 } 3307 } 3308 3309 if (V.empty()) 3310 OS << "There are no section groups in this file.\n"; 3311 } 3312 3313 template <class ELFT> 3314 void GNUELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) { 3315 OS << to_string(format_hex_no_prefix(R, ELFT::Is64Bits ? 16 : 8)) << "\n"; 3316 } 3317 3318 template <class ELFT> 3319 void GNUELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R, 3320 const RelSymbol<ELFT> &RelSym) { 3321 // First two fields are bit width dependent. The rest of them are fixed width. 3322 unsigned Bias = ELFT::Is64Bits ? 8 : 0; 3323 Field Fields[5] = {0, 10 + Bias, 19 + 2 * Bias, 42 + 2 * Bias, 53 + 2 * Bias}; 3324 unsigned Width = ELFT::Is64Bits ? 16 : 8; 3325 3326 Fields[0].Str = to_string(format_hex_no_prefix(R.Offset, Width)); 3327 Fields[1].Str = to_string(format_hex_no_prefix(R.Info, Width)); 3328 3329 SmallString<32> RelocName; 3330 this->Obj.getRelocationTypeName(R.Type, RelocName); 3331 Fields[2].Str = RelocName.c_str(); 3332 3333 if (RelSym.Sym) 3334 Fields[3].Str = 3335 to_string(format_hex_no_prefix(RelSym.Sym->getValue(), Width)); 3336 3337 Fields[4].Str = std::string(RelSym.Name); 3338 for (const Field &F : Fields) 3339 printField(F); 3340 3341 std::string Addend; 3342 if (Optional<int64_t> A = R.Addend) { 3343 int64_t RelAddend = *A; 3344 if (!RelSym.Name.empty()) { 3345 if (RelAddend < 0) { 3346 Addend = " - "; 3347 RelAddend = std::abs(RelAddend); 3348 } else { 3349 Addend = " + "; 3350 } 3351 } 3352 Addend += to_hexString(RelAddend, false); 3353 } 3354 OS << Addend << "\n"; 3355 } 3356 3357 template <class ELFT> 3358 static void printRelocHeaderFields(formatted_raw_ostream &OS, unsigned SType) { 3359 bool IsRela = SType == ELF::SHT_RELA || SType == ELF::SHT_ANDROID_RELA; 3360 bool IsRelr = SType == ELF::SHT_RELR || SType == ELF::SHT_ANDROID_RELR; 3361 if (ELFT::Is64Bits) 3362 OS << " "; 3363 else 3364 OS << " "; 3365 if (IsRelr && opts::RawRelr) 3366 OS << "Data "; 3367 else 3368 OS << "Offset"; 3369 if (ELFT::Is64Bits) 3370 OS << " Info Type" 3371 << " Symbol's Value Symbol's Name"; 3372 else 3373 OS << " Info Type Sym. Value Symbol's Name"; 3374 if (IsRela) 3375 OS << " + Addend"; 3376 OS << "\n"; 3377 } 3378 3379 template <class ELFT> 3380 void GNUELFDumper<ELFT>::printDynamicRelocHeader(unsigned Type, StringRef Name, 3381 const DynRegionInfo &Reg) { 3382 uint64_t Offset = Reg.Addr - this->Obj.base(); 3383 OS << "\n'" << Name.str().c_str() << "' relocation section at offset 0x" 3384 << to_hexString(Offset, false) << " contains " << Reg.Size << " bytes:\n"; 3385 printRelocHeaderFields<ELFT>(OS, Type); 3386 } 3387 3388 template <class ELFT> 3389 static bool isRelocationSec(const typename ELFT::Shdr &Sec) { 3390 return Sec.sh_type == ELF::SHT_REL || Sec.sh_type == ELF::SHT_RELA || 3391 Sec.sh_type == ELF::SHT_RELR || Sec.sh_type == ELF::SHT_ANDROID_REL || 3392 Sec.sh_type == ELF::SHT_ANDROID_RELA || 3393 Sec.sh_type == ELF::SHT_ANDROID_RELR; 3394 } 3395 3396 template <class ELFT> void GNUELFDumper<ELFT>::printRelocations() { 3397 auto GetEntriesNum = [&](const Elf_Shdr &Sec) -> Expected<size_t> { 3398 // Android's packed relocation section needs to be unpacked first 3399 // to get the actual number of entries. 3400 if (Sec.sh_type == ELF::SHT_ANDROID_REL || 3401 Sec.sh_type == ELF::SHT_ANDROID_RELA) { 3402 Expected<std::vector<typename ELFT::Rela>> RelasOrErr = 3403 this->Obj.android_relas(Sec); 3404 if (!RelasOrErr) 3405 return RelasOrErr.takeError(); 3406 return RelasOrErr->size(); 3407 } 3408 3409 if (!opts::RawRelr && (Sec.sh_type == ELF::SHT_RELR || 3410 Sec.sh_type == ELF::SHT_ANDROID_RELR)) { 3411 Expected<Elf_Relr_Range> RelrsOrErr = this->Obj.relrs(Sec); 3412 if (!RelrsOrErr) 3413 return RelrsOrErr.takeError(); 3414 return this->Obj.decode_relrs(*RelrsOrErr).size(); 3415 } 3416 3417 return Sec.getEntityCount(); 3418 }; 3419 3420 bool HasRelocSections = false; 3421 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) { 3422 if (!isRelocationSec<ELFT>(Sec)) 3423 continue; 3424 HasRelocSections = true; 3425 3426 std::string EntriesNum = "<?>"; 3427 if (Expected<size_t> NumOrErr = GetEntriesNum(Sec)) 3428 EntriesNum = std::to_string(*NumOrErr); 3429 else 3430 this->reportUniqueWarning("unable to get the number of relocations in " + 3431 this->describe(Sec) + ": " + 3432 toString(NumOrErr.takeError())); 3433 3434 uintX_t Offset = Sec.sh_offset; 3435 StringRef Name = this->getPrintableSectionName(Sec); 3436 OS << "\nRelocation section '" << Name << "' at offset 0x" 3437 << to_hexString(Offset, false) << " contains " << EntriesNum 3438 << " entries:\n"; 3439 printRelocHeaderFields<ELFT>(OS, Sec.sh_type); 3440 this->printRelocationsHelper(Sec); 3441 } 3442 if (!HasRelocSections) 3443 OS << "\nThere are no relocations in this file.\n"; 3444 } 3445 3446 // Print the offset of a particular section from anyone of the ranges: 3447 // [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER]. 3448 // If 'Type' does not fall within any of those ranges, then a string is 3449 // returned as '<unknown>' followed by the type value. 3450 static std::string getSectionTypeOffsetString(unsigned Type) { 3451 if (Type >= SHT_LOOS && Type <= SHT_HIOS) 3452 return "LOOS+0x" + to_hexString(Type - SHT_LOOS); 3453 else if (Type >= SHT_LOPROC && Type <= SHT_HIPROC) 3454 return "LOPROC+0x" + to_hexString(Type - SHT_LOPROC); 3455 else if (Type >= SHT_LOUSER && Type <= SHT_HIUSER) 3456 return "LOUSER+0x" + to_hexString(Type - SHT_LOUSER); 3457 return "0x" + to_hexString(Type) + ": <unknown>"; 3458 } 3459 3460 static std::string getSectionTypeString(unsigned Machine, unsigned Type) { 3461 StringRef Name = getELFSectionTypeName(Machine, Type); 3462 3463 // Handle SHT_GNU_* type names. 3464 if (Name.startswith("SHT_GNU_")) { 3465 if (Name == "SHT_GNU_HASH") 3466 return "GNU_HASH"; 3467 // E.g. SHT_GNU_verneed -> VERNEED. 3468 return Name.drop_front(8).upper(); 3469 } 3470 3471 if (Name == "SHT_SYMTAB_SHNDX") 3472 return "SYMTAB SECTION INDICES"; 3473 3474 if (Name.startswith("SHT_")) 3475 return Name.drop_front(4).str(); 3476 return getSectionTypeOffsetString(Type); 3477 } 3478 3479 static void printSectionDescription(formatted_raw_ostream &OS, 3480 unsigned EMachine) { 3481 OS << "Key to Flags:\n"; 3482 OS << " W (write), A (alloc), X (execute), M (merge), S (strings), I " 3483 "(info),\n"; 3484 OS << " L (link order), O (extra OS processing required), G (group), T " 3485 "(TLS),\n"; 3486 OS << " C (compressed), x (unknown), o (OS specific), E (exclude),\n"; 3487 OS << " R (retain)"; 3488 3489 if (EMachine == EM_X86_64) 3490 OS << ", l (large)"; 3491 else if (EMachine == EM_ARM) 3492 OS << ", y (purecode)"; 3493 3494 OS << ", p (processor specific)\n"; 3495 } 3496 3497 template <class ELFT> void GNUELFDumper<ELFT>::printSectionHeaders() { 3498 unsigned Bias = ELFT::Is64Bits ? 0 : 8; 3499 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections()); 3500 OS << "There are " << to_string(Sections.size()) 3501 << " section headers, starting at offset " 3502 << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n"; 3503 OS << "Section Headers:\n"; 3504 Field Fields[11] = { 3505 {"[Nr]", 2}, {"Name", 7}, {"Type", 25}, 3506 {"Address", 41}, {"Off", 58 - Bias}, {"Size", 65 - Bias}, 3507 {"ES", 72 - Bias}, {"Flg", 75 - Bias}, {"Lk", 79 - Bias}, 3508 {"Inf", 82 - Bias}, {"Al", 86 - Bias}}; 3509 for (const Field &F : Fields) 3510 printField(F); 3511 OS << "\n"; 3512 3513 StringRef SecStrTable; 3514 if (Expected<StringRef> SecStrTableOrErr = 3515 this->Obj.getSectionStringTable(Sections, this->WarningHandler)) 3516 SecStrTable = *SecStrTableOrErr; 3517 else 3518 this->reportUniqueWarning(SecStrTableOrErr.takeError()); 3519 3520 size_t SectionIndex = 0; 3521 for (const Elf_Shdr &Sec : Sections) { 3522 Fields[0].Str = to_string(SectionIndex); 3523 if (SecStrTable.empty()) 3524 Fields[1].Str = "<no-strings>"; 3525 else 3526 Fields[1].Str = std::string(unwrapOrError<StringRef>( 3527 this->FileName, this->Obj.getSectionName(Sec, SecStrTable))); 3528 Fields[2].Str = 3529 getSectionTypeString(this->Obj.getHeader().e_machine, Sec.sh_type); 3530 Fields[3].Str = 3531 to_string(format_hex_no_prefix(Sec.sh_addr, ELFT::Is64Bits ? 16 : 8)); 3532 Fields[4].Str = to_string(format_hex_no_prefix(Sec.sh_offset, 6)); 3533 Fields[5].Str = to_string(format_hex_no_prefix(Sec.sh_size, 6)); 3534 Fields[6].Str = to_string(format_hex_no_prefix(Sec.sh_entsize, 2)); 3535 Fields[7].Str = getGNUFlags(this->Obj.getHeader().e_machine, Sec.sh_flags); 3536 Fields[8].Str = to_string(Sec.sh_link); 3537 Fields[9].Str = to_string(Sec.sh_info); 3538 Fields[10].Str = to_string(Sec.sh_addralign); 3539 3540 OS.PadToColumn(Fields[0].Column); 3541 OS << "[" << right_justify(Fields[0].Str, 2) << "]"; 3542 for (int i = 1; i < 7; i++) 3543 printField(Fields[i]); 3544 OS.PadToColumn(Fields[7].Column); 3545 OS << right_justify(Fields[7].Str, 3); 3546 OS.PadToColumn(Fields[8].Column); 3547 OS << right_justify(Fields[8].Str, 2); 3548 OS.PadToColumn(Fields[9].Column); 3549 OS << right_justify(Fields[9].Str, 3); 3550 OS.PadToColumn(Fields[10].Column); 3551 OS << right_justify(Fields[10].Str, 2); 3552 OS << "\n"; 3553 ++SectionIndex; 3554 } 3555 printSectionDescription(OS, this->Obj.getHeader().e_machine); 3556 } 3557 3558 template <class ELFT> 3559 void GNUELFDumper<ELFT>::printSymtabMessage(const Elf_Shdr *Symtab, 3560 size_t Entries, 3561 bool NonVisibilityBitsUsed) const { 3562 StringRef Name; 3563 if (Symtab) 3564 Name = this->getPrintableSectionName(*Symtab); 3565 if (!Name.empty()) 3566 OS << "\nSymbol table '" << Name << "'"; 3567 else 3568 OS << "\nSymbol table for image"; 3569 OS << " contains " << Entries << " entries:\n"; 3570 3571 if (ELFT::Is64Bits) 3572 OS << " Num: Value Size Type Bind Vis"; 3573 else 3574 OS << " Num: Value Size Type Bind Vis"; 3575 3576 if (NonVisibilityBitsUsed) 3577 OS << " "; 3578 OS << " Ndx Name\n"; 3579 } 3580 3581 template <class ELFT> 3582 std::string 3583 GNUELFDumper<ELFT>::getSymbolSectionNdx(const Elf_Sym &Symbol, 3584 unsigned SymIndex, 3585 DataRegion<Elf_Word> ShndxTable) const { 3586 unsigned SectionIndex = Symbol.st_shndx; 3587 switch (SectionIndex) { 3588 case ELF::SHN_UNDEF: 3589 return "UND"; 3590 case ELF::SHN_ABS: 3591 return "ABS"; 3592 case ELF::SHN_COMMON: 3593 return "COM"; 3594 case ELF::SHN_XINDEX: { 3595 Expected<uint32_t> IndexOrErr = 3596 object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, ShndxTable); 3597 if (!IndexOrErr) { 3598 assert(Symbol.st_shndx == SHN_XINDEX && 3599 "getExtendedSymbolTableIndex should only fail due to an invalid " 3600 "SHT_SYMTAB_SHNDX table/reference"); 3601 this->reportUniqueWarning(IndexOrErr.takeError()); 3602 return "RSV[0xffff]"; 3603 } 3604 return to_string(format_decimal(*IndexOrErr, 3)); 3605 } 3606 default: 3607 // Find if: 3608 // Processor specific 3609 if (SectionIndex >= ELF::SHN_LOPROC && SectionIndex <= ELF::SHN_HIPROC) 3610 return std::string("PRC[0x") + 3611 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]"; 3612 // OS specific 3613 if (SectionIndex >= ELF::SHN_LOOS && SectionIndex <= ELF::SHN_HIOS) 3614 return std::string("OS[0x") + 3615 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]"; 3616 // Architecture reserved: 3617 if (SectionIndex >= ELF::SHN_LORESERVE && 3618 SectionIndex <= ELF::SHN_HIRESERVE) 3619 return std::string("RSV[0x") + 3620 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]"; 3621 // A normal section with an index 3622 return to_string(format_decimal(SectionIndex, 3)); 3623 } 3624 } 3625 3626 template <class ELFT> 3627 void GNUELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex, 3628 DataRegion<Elf_Word> ShndxTable, 3629 Optional<StringRef> StrTable, 3630 bool IsDynamic, 3631 bool NonVisibilityBitsUsed) const { 3632 unsigned Bias = ELFT::Is64Bits ? 8 : 0; 3633 Field Fields[8] = {0, 8, 17 + Bias, 23 + Bias, 3634 31 + Bias, 38 + Bias, 48 + Bias, 51 + Bias}; 3635 Fields[0].Str = to_string(format_decimal(SymIndex, 6)) + ":"; 3636 Fields[1].Str = 3637 to_string(format_hex_no_prefix(Symbol.st_value, ELFT::Is64Bits ? 16 : 8)); 3638 Fields[2].Str = to_string(format_decimal(Symbol.st_size, 5)); 3639 3640 unsigned char SymbolType = Symbol.getType(); 3641 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU && 3642 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS) 3643 Fields[3].Str = printEnum(SymbolType, makeArrayRef(AMDGPUSymbolTypes)); 3644 else 3645 Fields[3].Str = printEnum(SymbolType, makeArrayRef(ElfSymbolTypes)); 3646 3647 Fields[4].Str = 3648 printEnum(Symbol.getBinding(), makeArrayRef(ElfSymbolBindings)); 3649 Fields[5].Str = 3650 printEnum(Symbol.getVisibility(), makeArrayRef(ElfSymbolVisibilities)); 3651 3652 if (Symbol.st_other & ~0x3) { 3653 if (this->Obj.getHeader().e_machine == ELF::EM_AARCH64) { 3654 uint8_t Other = Symbol.st_other & ~0x3; 3655 if (Other & STO_AARCH64_VARIANT_PCS) { 3656 Other &= ~STO_AARCH64_VARIANT_PCS; 3657 Fields[5].Str += " [VARIANT_PCS"; 3658 if (Other != 0) 3659 Fields[5].Str.append(" | " + to_hexString(Other, false)); 3660 Fields[5].Str.append("]"); 3661 } 3662 } else { 3663 Fields[5].Str += 3664 " [<other: " + to_string(format_hex(Symbol.st_other, 2)) + ">]"; 3665 } 3666 } 3667 3668 Fields[6].Column += NonVisibilityBitsUsed ? 13 : 0; 3669 Fields[6].Str = getSymbolSectionNdx(Symbol, SymIndex, ShndxTable); 3670 3671 Fields[7].Str = this->getFullSymbolName(Symbol, SymIndex, ShndxTable, 3672 StrTable, IsDynamic); 3673 for (const Field &Entry : Fields) 3674 printField(Entry); 3675 OS << "\n"; 3676 } 3677 3678 template <class ELFT> 3679 void GNUELFDumper<ELFT>::printHashedSymbol(const Elf_Sym *Symbol, 3680 unsigned SymIndex, 3681 DataRegion<Elf_Word> ShndxTable, 3682 StringRef StrTable, 3683 uint32_t Bucket) { 3684 unsigned Bias = ELFT::Is64Bits ? 8 : 0; 3685 Field Fields[9] = {0, 6, 11, 20 + Bias, 25 + Bias, 3686 34 + Bias, 41 + Bias, 49 + Bias, 53 + Bias}; 3687 Fields[0].Str = to_string(format_decimal(SymIndex, 5)); 3688 Fields[1].Str = to_string(format_decimal(Bucket, 3)) + ":"; 3689 3690 Fields[2].Str = to_string( 3691 format_hex_no_prefix(Symbol->st_value, ELFT::Is64Bits ? 16 : 8)); 3692 Fields[3].Str = to_string(format_decimal(Symbol->st_size, 5)); 3693 3694 unsigned char SymbolType = Symbol->getType(); 3695 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU && 3696 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS) 3697 Fields[4].Str = printEnum(SymbolType, makeArrayRef(AMDGPUSymbolTypes)); 3698 else 3699 Fields[4].Str = printEnum(SymbolType, makeArrayRef(ElfSymbolTypes)); 3700 3701 Fields[5].Str = 3702 printEnum(Symbol->getBinding(), makeArrayRef(ElfSymbolBindings)); 3703 Fields[6].Str = 3704 printEnum(Symbol->getVisibility(), makeArrayRef(ElfSymbolVisibilities)); 3705 Fields[7].Str = getSymbolSectionNdx(*Symbol, SymIndex, ShndxTable); 3706 Fields[8].Str = 3707 this->getFullSymbolName(*Symbol, SymIndex, ShndxTable, StrTable, true); 3708 3709 for (const Field &Entry : Fields) 3710 printField(Entry); 3711 OS << "\n"; 3712 } 3713 3714 template <class ELFT> 3715 void GNUELFDumper<ELFT>::printSymbols(bool PrintSymbols, 3716 bool PrintDynamicSymbols) { 3717 if (!PrintSymbols && !PrintDynamicSymbols) 3718 return; 3719 // GNU readelf prints both the .dynsym and .symtab with --symbols. 3720 this->printSymbolsHelper(true); 3721 if (PrintSymbols) 3722 this->printSymbolsHelper(false); 3723 } 3724 3725 template <class ELFT> 3726 void GNUELFDumper<ELFT>::printHashTableSymbols(const Elf_Hash &SysVHash) { 3727 if (this->DynamicStringTable.empty()) 3728 return; 3729 3730 if (ELFT::Is64Bits) 3731 OS << " Num Buc: Value Size Type Bind Vis Ndx Name"; 3732 else 3733 OS << " Num Buc: Value Size Type Bind Vis Ndx Name"; 3734 OS << "\n"; 3735 3736 Elf_Sym_Range DynSyms = this->dynamic_symbols(); 3737 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0]; 3738 if (!FirstSym) { 3739 this->reportUniqueWarning( 3740 Twine("unable to print symbols for the .hash table: the " 3741 "dynamic symbol table ") + 3742 (this->DynSymRegion ? "is empty" : "was not found")); 3743 return; 3744 } 3745 3746 DataRegion<Elf_Word> ShndxTable( 3747 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end()); 3748 auto Buckets = SysVHash.buckets(); 3749 auto Chains = SysVHash.chains(); 3750 for (uint32_t Buc = 0; Buc < SysVHash.nbucket; Buc++) { 3751 if (Buckets[Buc] == ELF::STN_UNDEF) 3752 continue; 3753 std::vector<bool> Visited(SysVHash.nchain); 3754 for (uint32_t Ch = Buckets[Buc]; Ch < SysVHash.nchain; Ch = Chains[Ch]) { 3755 if (Ch == ELF::STN_UNDEF) 3756 break; 3757 3758 if (Visited[Ch]) { 3759 this->reportUniqueWarning(".hash section is invalid: bucket " + 3760 Twine(Ch) + 3761 ": a cycle was detected in the linked chain"); 3762 break; 3763 } 3764 3765 printHashedSymbol(FirstSym + Ch, Ch, ShndxTable, this->DynamicStringTable, 3766 Buc); 3767 Visited[Ch] = true; 3768 } 3769 } 3770 } 3771 3772 template <class ELFT> 3773 void GNUELFDumper<ELFT>::printGnuHashTableSymbols(const Elf_GnuHash &GnuHash) { 3774 if (this->DynamicStringTable.empty()) 3775 return; 3776 3777 Elf_Sym_Range DynSyms = this->dynamic_symbols(); 3778 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0]; 3779 if (!FirstSym) { 3780 this->reportUniqueWarning( 3781 Twine("unable to print symbols for the .gnu.hash table: the " 3782 "dynamic symbol table ") + 3783 (this->DynSymRegion ? "is empty" : "was not found")); 3784 return; 3785 } 3786 3787 auto GetSymbol = [&](uint64_t SymIndex, 3788 uint64_t SymsTotal) -> const Elf_Sym * { 3789 if (SymIndex >= SymsTotal) { 3790 this->reportUniqueWarning( 3791 "unable to print hashed symbol with index " + Twine(SymIndex) + 3792 ", which is greater than or equal to the number of dynamic symbols " 3793 "(" + 3794 Twine::utohexstr(SymsTotal) + ")"); 3795 return nullptr; 3796 } 3797 return FirstSym + SymIndex; 3798 }; 3799 3800 Expected<ArrayRef<Elf_Word>> ValuesOrErr = 3801 getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHash); 3802 ArrayRef<Elf_Word> Values; 3803 if (!ValuesOrErr) 3804 this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH " 3805 "section: " + 3806 toString(ValuesOrErr.takeError())); 3807 else 3808 Values = *ValuesOrErr; 3809 3810 DataRegion<Elf_Word> ShndxTable( 3811 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end()); 3812 ArrayRef<Elf_Word> Buckets = GnuHash.buckets(); 3813 for (uint32_t Buc = 0; Buc < GnuHash.nbuckets; Buc++) { 3814 if (Buckets[Buc] == ELF::STN_UNDEF) 3815 continue; 3816 uint32_t Index = Buckets[Buc]; 3817 // Print whole chain. 3818 while (true) { 3819 uint32_t SymIndex = Index++; 3820 if (const Elf_Sym *Sym = GetSymbol(SymIndex, DynSyms.size())) 3821 printHashedSymbol(Sym, SymIndex, ShndxTable, this->DynamicStringTable, 3822 Buc); 3823 else 3824 break; 3825 3826 if (SymIndex < GnuHash.symndx) { 3827 this->reportUniqueWarning( 3828 "unable to read the hash value for symbol with index " + 3829 Twine(SymIndex) + 3830 ", which is less than the index of the first hashed symbol (" + 3831 Twine(GnuHash.symndx) + ")"); 3832 break; 3833 } 3834 3835 // Chain ends at symbol with stopper bit. 3836 if ((Values[SymIndex - GnuHash.symndx] & 1) == 1) 3837 break; 3838 } 3839 } 3840 } 3841 3842 template <class ELFT> void GNUELFDumper<ELFT>::printHashSymbols() { 3843 if (this->HashTable) { 3844 OS << "\n Symbol table of .hash for image:\n"; 3845 if (Error E = checkHashTable<ELFT>(*this, this->HashTable)) 3846 this->reportUniqueWarning(std::move(E)); 3847 else 3848 printHashTableSymbols(*this->HashTable); 3849 } 3850 3851 // Try printing the .gnu.hash table. 3852 if (this->GnuHashTable) { 3853 OS << "\n Symbol table of .gnu.hash for image:\n"; 3854 if (ELFT::Is64Bits) 3855 OS << " Num Buc: Value Size Type Bind Vis Ndx Name"; 3856 else 3857 OS << " Num Buc: Value Size Type Bind Vis Ndx Name"; 3858 OS << "\n"; 3859 3860 if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable)) 3861 this->reportUniqueWarning(std::move(E)); 3862 else 3863 printGnuHashTableSymbols(*this->GnuHashTable); 3864 } 3865 } 3866 3867 template <class ELFT> void GNUELFDumper<ELFT>::printSectionDetails() { 3868 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections()); 3869 OS << "There are " << to_string(Sections.size()) 3870 << " section headers, starting at offset " 3871 << "0x" << to_hexString(this->Obj.getHeader().e_shoff, false) << ":\n\n"; 3872 3873 OS << "Section Headers:\n"; 3874 3875 auto PrintFields = [&](ArrayRef<Field> V) { 3876 for (const Field &F : V) 3877 printField(F); 3878 OS << "\n"; 3879 }; 3880 3881 PrintFields({{"[Nr]", 2}, {"Name", 7}}); 3882 3883 constexpr bool Is64 = ELFT::Is64Bits; 3884 PrintFields({{"Type", 7}, 3885 {Is64 ? "Address" : "Addr", 23}, 3886 {"Off", Is64 ? 40 : 32}, 3887 {"Size", Is64 ? 47 : 39}, 3888 {"ES", Is64 ? 54 : 46}, 3889 {"Lk", Is64 ? 59 : 51}, 3890 {"Inf", Is64 ? 62 : 54}, 3891 {"Al", Is64 ? 66 : 57}}); 3892 PrintFields({{"Flags", 7}}); 3893 3894 StringRef SecStrTable; 3895 if (Expected<StringRef> SecStrTableOrErr = 3896 this->Obj.getSectionStringTable(Sections, this->WarningHandler)) 3897 SecStrTable = *SecStrTableOrErr; 3898 else 3899 this->reportUniqueWarning(SecStrTableOrErr.takeError()); 3900 3901 size_t SectionIndex = 0; 3902 const unsigned AddrSize = Is64 ? 16 : 8; 3903 for (const Elf_Shdr &S : Sections) { 3904 StringRef Name = "<?>"; 3905 if (Expected<StringRef> NameOrErr = 3906 this->Obj.getSectionName(S, SecStrTable)) 3907 Name = *NameOrErr; 3908 else 3909 this->reportUniqueWarning(NameOrErr.takeError()); 3910 3911 OS.PadToColumn(2); 3912 OS << "[" << right_justify(to_string(SectionIndex), 2) << "]"; 3913 PrintFields({{Name, 7}}); 3914 PrintFields( 3915 {{getSectionTypeString(this->Obj.getHeader().e_machine, S.sh_type), 7}, 3916 {to_string(format_hex_no_prefix(S.sh_addr, AddrSize)), 23}, 3917 {to_string(format_hex_no_prefix(S.sh_offset, 6)), Is64 ? 39 : 32}, 3918 {to_string(format_hex_no_prefix(S.sh_size, 6)), Is64 ? 47 : 39}, 3919 {to_string(format_hex_no_prefix(S.sh_entsize, 2)), Is64 ? 54 : 46}, 3920 {to_string(S.sh_link), Is64 ? 59 : 51}, 3921 {to_string(S.sh_info), Is64 ? 63 : 55}, 3922 {to_string(S.sh_addralign), Is64 ? 66 : 58}}); 3923 3924 OS.PadToColumn(7); 3925 OS << "[" << to_string(format_hex_no_prefix(S.sh_flags, AddrSize)) << "]: "; 3926 3927 DenseMap<unsigned, StringRef> FlagToName = { 3928 {SHF_WRITE, "WRITE"}, {SHF_ALLOC, "ALLOC"}, 3929 {SHF_EXECINSTR, "EXEC"}, {SHF_MERGE, "MERGE"}, 3930 {SHF_STRINGS, "STRINGS"}, {SHF_INFO_LINK, "INFO LINK"}, 3931 {SHF_LINK_ORDER, "LINK ORDER"}, {SHF_OS_NONCONFORMING, "OS NONCONF"}, 3932 {SHF_GROUP, "GROUP"}, {SHF_TLS, "TLS"}, 3933 {SHF_COMPRESSED, "COMPRESSED"}, {SHF_EXCLUDE, "EXCLUDE"}}; 3934 3935 uint64_t Flags = S.sh_flags; 3936 uint64_t UnknownFlags = 0; 3937 bool NeedsComma = false; 3938 while (Flags) { 3939 // Take the least significant bit as a flag. 3940 uint64_t Flag = Flags & -Flags; 3941 Flags -= Flag; 3942 3943 auto It = FlagToName.find(Flag); 3944 if (It != FlagToName.end()) { 3945 if (NeedsComma) 3946 OS << ", "; 3947 NeedsComma = true; 3948 OS << It->second; 3949 } else { 3950 UnknownFlags |= Flag; 3951 } 3952 } 3953 3954 auto PrintUnknownFlags = [&](uint64_t Mask, StringRef Name) { 3955 uint64_t FlagsToPrint = UnknownFlags & Mask; 3956 if (!FlagsToPrint) 3957 return; 3958 3959 if (NeedsComma) 3960 OS << ", "; 3961 OS << Name << " (" 3962 << to_string(format_hex_no_prefix(FlagsToPrint, AddrSize)) << ")"; 3963 UnknownFlags &= ~Mask; 3964 NeedsComma = true; 3965 }; 3966 3967 PrintUnknownFlags(SHF_MASKOS, "OS"); 3968 PrintUnknownFlags(SHF_MASKPROC, "PROC"); 3969 PrintUnknownFlags(uint64_t(-1), "UNKNOWN"); 3970 3971 OS << "\n"; 3972 ++SectionIndex; 3973 } 3974 } 3975 3976 static inline std::string printPhdrFlags(unsigned Flag) { 3977 std::string Str; 3978 Str = (Flag & PF_R) ? "R" : " "; 3979 Str += (Flag & PF_W) ? "W" : " "; 3980 Str += (Flag & PF_X) ? "E" : " "; 3981 return Str; 3982 } 3983 3984 template <class ELFT> 3985 static bool checkTLSSections(const typename ELFT::Phdr &Phdr, 3986 const typename ELFT::Shdr &Sec) { 3987 if (Sec.sh_flags & ELF::SHF_TLS) { 3988 // .tbss must only be shown in the PT_TLS segment. 3989 if (Sec.sh_type == ELF::SHT_NOBITS) 3990 return Phdr.p_type == ELF::PT_TLS; 3991 3992 // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO 3993 // segments. 3994 return (Phdr.p_type == ELF::PT_TLS) || (Phdr.p_type == ELF::PT_LOAD) || 3995 (Phdr.p_type == ELF::PT_GNU_RELRO); 3996 } 3997 3998 // PT_TLS must only have SHF_TLS sections. 3999 return Phdr.p_type != ELF::PT_TLS; 4000 } 4001 4002 template <class ELFT> 4003 static bool checkOffsets(const typename ELFT::Phdr &Phdr, 4004 const typename ELFT::Shdr &Sec) { 4005 // SHT_NOBITS sections don't need to have an offset inside the segment. 4006 if (Sec.sh_type == ELF::SHT_NOBITS) 4007 return true; 4008 4009 if (Sec.sh_offset < Phdr.p_offset) 4010 return false; 4011 4012 // Only non-empty sections can be at the end of a segment. 4013 if (Sec.sh_size == 0) 4014 return (Sec.sh_offset + 1 <= Phdr.p_offset + Phdr.p_filesz); 4015 return Sec.sh_offset + Sec.sh_size <= Phdr.p_offset + Phdr.p_filesz; 4016 } 4017 4018 // Check that an allocatable section belongs to a virtual address 4019 // space of a segment. 4020 template <class ELFT> 4021 static bool checkVMA(const typename ELFT::Phdr &Phdr, 4022 const typename ELFT::Shdr &Sec) { 4023 if (!(Sec.sh_flags & ELF::SHF_ALLOC)) 4024 return true; 4025 4026 if (Sec.sh_addr < Phdr.p_vaddr) 4027 return false; 4028 4029 bool IsTbss = 4030 (Sec.sh_type == ELF::SHT_NOBITS) && ((Sec.sh_flags & ELF::SHF_TLS) != 0); 4031 // .tbss is special, it only has memory in PT_TLS and has NOBITS properties. 4032 bool IsTbssInNonTLS = IsTbss && Phdr.p_type != ELF::PT_TLS; 4033 // Only non-empty sections can be at the end of a segment. 4034 if (Sec.sh_size == 0 || IsTbssInNonTLS) 4035 return Sec.sh_addr + 1 <= Phdr.p_vaddr + Phdr.p_memsz; 4036 return Sec.sh_addr + Sec.sh_size <= Phdr.p_vaddr + Phdr.p_memsz; 4037 } 4038 4039 template <class ELFT> 4040 static bool checkPTDynamic(const typename ELFT::Phdr &Phdr, 4041 const typename ELFT::Shdr &Sec) { 4042 if (Phdr.p_type != ELF::PT_DYNAMIC || Phdr.p_memsz == 0 || Sec.sh_size != 0) 4043 return true; 4044 4045 // We get here when we have an empty section. Only non-empty sections can be 4046 // at the start or at the end of PT_DYNAMIC. 4047 // Is section within the phdr both based on offset and VMA? 4048 bool CheckOffset = (Sec.sh_type == ELF::SHT_NOBITS) || 4049 (Sec.sh_offset > Phdr.p_offset && 4050 Sec.sh_offset < Phdr.p_offset + Phdr.p_filesz); 4051 bool CheckVA = !(Sec.sh_flags & ELF::SHF_ALLOC) || 4052 (Sec.sh_addr > Phdr.p_vaddr && Sec.sh_addr < Phdr.p_memsz); 4053 return CheckOffset && CheckVA; 4054 } 4055 4056 template <class ELFT> 4057 void GNUELFDumper<ELFT>::printProgramHeaders( 4058 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) { 4059 if (PrintProgramHeaders) 4060 printProgramHeaders(); 4061 4062 // Display the section mapping along with the program headers, unless 4063 // -section-mapping is explicitly set to false. 4064 if (PrintSectionMapping != cl::BOU_FALSE) 4065 printSectionMapping(); 4066 } 4067 4068 template <class ELFT> void GNUELFDumper<ELFT>::printProgramHeaders() { 4069 unsigned Bias = ELFT::Is64Bits ? 8 : 0; 4070 const Elf_Ehdr &Header = this->Obj.getHeader(); 4071 Field Fields[8] = {2, 17, 26, 37 + Bias, 4072 48 + Bias, 56 + Bias, 64 + Bias, 68 + Bias}; 4073 OS << "\nElf file type is " 4074 << printEnum(Header.e_type, makeArrayRef(ElfObjectFileType)) << "\n" 4075 << "Entry point " << format_hex(Header.e_entry, 3) << "\n" 4076 << "There are " << Header.e_phnum << " program headers," 4077 << " starting at offset " << Header.e_phoff << "\n\n" 4078 << "Program Headers:\n"; 4079 if (ELFT::Is64Bits) 4080 OS << " Type Offset VirtAddr PhysAddr " 4081 << " FileSiz MemSiz Flg Align\n"; 4082 else 4083 OS << " Type Offset VirtAddr PhysAddr FileSiz " 4084 << "MemSiz Flg Align\n"; 4085 4086 unsigned Width = ELFT::Is64Bits ? 18 : 10; 4087 unsigned SizeWidth = ELFT::Is64Bits ? 8 : 7; 4088 4089 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers(); 4090 if (!PhdrsOrErr) { 4091 this->reportUniqueWarning("unable to dump program headers: " + 4092 toString(PhdrsOrErr.takeError())); 4093 return; 4094 } 4095 4096 for (const Elf_Phdr &Phdr : *PhdrsOrErr) { 4097 Fields[0].Str = getGNUPtType(Header.e_machine, Phdr.p_type); 4098 Fields[1].Str = to_string(format_hex(Phdr.p_offset, 8)); 4099 Fields[2].Str = to_string(format_hex(Phdr.p_vaddr, Width)); 4100 Fields[3].Str = to_string(format_hex(Phdr.p_paddr, Width)); 4101 Fields[4].Str = to_string(format_hex(Phdr.p_filesz, SizeWidth)); 4102 Fields[5].Str = to_string(format_hex(Phdr.p_memsz, SizeWidth)); 4103 Fields[6].Str = printPhdrFlags(Phdr.p_flags); 4104 Fields[7].Str = to_string(format_hex(Phdr.p_align, 1)); 4105 for (const Field &F : Fields) 4106 printField(F); 4107 if (Phdr.p_type == ELF::PT_INTERP) { 4108 OS << "\n"; 4109 auto ReportBadInterp = [&](const Twine &Msg) { 4110 this->reportUniqueWarning( 4111 "unable to read program interpreter name at offset 0x" + 4112 Twine::utohexstr(Phdr.p_offset) + ": " + Msg); 4113 }; 4114 4115 if (Phdr.p_offset >= this->Obj.getBufSize()) { 4116 ReportBadInterp("it goes past the end of the file (0x" + 4117 Twine::utohexstr(this->Obj.getBufSize()) + ")"); 4118 continue; 4119 } 4120 4121 const char *Data = 4122 reinterpret_cast<const char *>(this->Obj.base()) + Phdr.p_offset; 4123 size_t MaxSize = this->Obj.getBufSize() - Phdr.p_offset; 4124 size_t Len = strnlen(Data, MaxSize); 4125 if (Len == MaxSize) { 4126 ReportBadInterp("it is not null-terminated"); 4127 continue; 4128 } 4129 4130 OS << " [Requesting program interpreter: "; 4131 OS << StringRef(Data, Len) << "]"; 4132 } 4133 OS << "\n"; 4134 } 4135 } 4136 4137 template <class ELFT> void GNUELFDumper<ELFT>::printSectionMapping() { 4138 OS << "\n Section to Segment mapping:\n Segment Sections...\n"; 4139 DenseSet<const Elf_Shdr *> BelongsToSegment; 4140 int Phnum = 0; 4141 4142 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers(); 4143 if (!PhdrsOrErr) { 4144 this->reportUniqueWarning( 4145 "can't read program headers to build section to segment mapping: " + 4146 toString(PhdrsOrErr.takeError())); 4147 return; 4148 } 4149 4150 for (const Elf_Phdr &Phdr : *PhdrsOrErr) { 4151 std::string Sections; 4152 OS << format(" %2.2d ", Phnum++); 4153 // Check if each section is in a segment and then print mapping. 4154 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) { 4155 if (Sec.sh_type == ELF::SHT_NULL) 4156 continue; 4157 4158 // readelf additionally makes sure it does not print zero sized sections 4159 // at end of segments and for PT_DYNAMIC both start and end of section 4160 // .tbss must only be shown in PT_TLS section. 4161 if (checkTLSSections<ELFT>(Phdr, Sec) && checkOffsets<ELFT>(Phdr, Sec) && 4162 checkVMA<ELFT>(Phdr, Sec) && checkPTDynamic<ELFT>(Phdr, Sec)) { 4163 Sections += 4164 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() + 4165 " "; 4166 BelongsToSegment.insert(&Sec); 4167 } 4168 } 4169 OS << Sections << "\n"; 4170 OS.flush(); 4171 } 4172 4173 // Display sections that do not belong to a segment. 4174 std::string Sections; 4175 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) { 4176 if (BelongsToSegment.find(&Sec) == BelongsToSegment.end()) 4177 Sections += 4178 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() + 4179 ' '; 4180 } 4181 if (!Sections.empty()) { 4182 OS << " None " << Sections << '\n'; 4183 OS.flush(); 4184 } 4185 } 4186 4187 namespace { 4188 4189 template <class ELFT> 4190 RelSymbol<ELFT> getSymbolForReloc(const ELFDumper<ELFT> &Dumper, 4191 const Relocation<ELFT> &Reloc) { 4192 using Elf_Sym = typename ELFT::Sym; 4193 auto WarnAndReturn = [&](const Elf_Sym *Sym, 4194 const Twine &Reason) -> RelSymbol<ELFT> { 4195 Dumper.reportUniqueWarning( 4196 "unable to get name of the dynamic symbol with index " + 4197 Twine(Reloc.Symbol) + ": " + Reason); 4198 return {Sym, "<corrupt>"}; 4199 }; 4200 4201 ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols(); 4202 const Elf_Sym *FirstSym = Symbols.begin(); 4203 if (!FirstSym) 4204 return WarnAndReturn(nullptr, "no dynamic symbol table found"); 4205 4206 // We might have an object without a section header. In this case the size of 4207 // Symbols is zero, because there is no way to know the size of the dynamic 4208 // table. We should allow this case and not print a warning. 4209 if (!Symbols.empty() && Reloc.Symbol >= Symbols.size()) 4210 return WarnAndReturn( 4211 nullptr, 4212 "index is greater than or equal to the number of dynamic symbols (" + 4213 Twine(Symbols.size()) + ")"); 4214 4215 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile(); 4216 const uint64_t FileSize = Obj.getBufSize(); 4217 const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) + 4218 (uint64_t)Reloc.Symbol * sizeof(Elf_Sym); 4219 if (SymOffset + sizeof(Elf_Sym) > FileSize) 4220 return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(SymOffset) + 4221 " goes past the end of the file (0x" + 4222 Twine::utohexstr(FileSize) + ")"); 4223 4224 const Elf_Sym *Sym = FirstSym + Reloc.Symbol; 4225 Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable()); 4226 if (!ErrOrName) 4227 return WarnAndReturn(Sym, toString(ErrOrName.takeError())); 4228 4229 return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(*ErrOrName)}; 4230 } 4231 } // namespace 4232 4233 template <class ELFT> 4234 static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj, 4235 typename ELFT::DynRange Tags) { 4236 size_t Max = 0; 4237 for (const typename ELFT::Dyn &Dyn : Tags) 4238 Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size()); 4239 return Max; 4240 } 4241 4242 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicTable() { 4243 Elf_Dyn_Range Table = this->dynamic_table(); 4244 if (Table.empty()) 4245 return; 4246 4247 OS << "Dynamic section at offset " 4248 << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable.Addr) - 4249 this->Obj.base(), 4250 1) 4251 << " contains " << Table.size() << " entries:\n"; 4252 4253 // The type name is surrounded with round brackets, hence add 2. 4254 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2; 4255 // The "Name/Value" column should be indented from the "Type" column by N 4256 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing 4257 // space (1) = 3. 4258 OS << " Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type" 4259 << std::string(MaxTagSize - 3, ' ') << "Name/Value\n"; 4260 4261 std::string ValueFmt = " %-" + std::to_string(MaxTagSize) + "s "; 4262 for (auto Entry : Table) { 4263 uintX_t Tag = Entry.getTag(); 4264 std::string Type = 4265 std::string("(") + this->Obj.getDynamicTagAsString(Tag).c_str() + ")"; 4266 std::string Value = this->getDynamicEntry(Tag, Entry.getVal()); 4267 OS << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10) 4268 << format(ValueFmt.c_str(), Type.c_str()) << Value << "\n"; 4269 } 4270 } 4271 4272 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicRelocations() { 4273 this->printDynamicRelocationsHelper(); 4274 } 4275 4276 template <class ELFT> 4277 void ELFDumper<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) { 4278 printRelRelaReloc(R, getSymbolForReloc(*this, R)); 4279 } 4280 4281 template <class ELFT> 4282 void ELFDumper<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) { 4283 this->forEachRelocationDo( 4284 Sec, opts::RawRelr, 4285 [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec, 4286 const Elf_Shdr *SymTab) { printReloc(R, Ndx, Sec, SymTab); }, 4287 [&](const Elf_Relr &R) { printRelrReloc(R); }); 4288 } 4289 4290 template <class ELFT> void ELFDumper<ELFT>::printDynamicRelocationsHelper() { 4291 const bool IsMips64EL = this->Obj.isMips64EL(); 4292 if (this->DynRelaRegion.Size > 0) { 4293 printDynamicRelocHeader(ELF::SHT_RELA, "RELA", this->DynRelaRegion); 4294 for (const Elf_Rela &Rela : 4295 this->DynRelaRegion.template getAsArrayRef<Elf_Rela>()) 4296 printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL)); 4297 } 4298 4299 if (this->DynRelRegion.Size > 0) { 4300 printDynamicRelocHeader(ELF::SHT_REL, "REL", this->DynRelRegion); 4301 for (const Elf_Rel &Rel : 4302 this->DynRelRegion.template getAsArrayRef<Elf_Rel>()) 4303 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL)); 4304 } 4305 4306 if (this->DynRelrRegion.Size > 0) { 4307 printDynamicRelocHeader(ELF::SHT_REL, "RELR", this->DynRelrRegion); 4308 Elf_Relr_Range Relrs = 4309 this->DynRelrRegion.template getAsArrayRef<Elf_Relr>(); 4310 for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs)) 4311 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL)); 4312 } 4313 4314 if (this->DynPLTRelRegion.Size) { 4315 if (this->DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) { 4316 printDynamicRelocHeader(ELF::SHT_RELA, "PLT", this->DynPLTRelRegion); 4317 for (const Elf_Rela &Rela : 4318 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rela>()) 4319 printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL)); 4320 } else { 4321 printDynamicRelocHeader(ELF::SHT_REL, "PLT", this->DynPLTRelRegion); 4322 for (const Elf_Rel &Rel : 4323 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rel>()) 4324 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL)); 4325 } 4326 } 4327 } 4328 4329 template <class ELFT> 4330 void GNUELFDumper<ELFT>::printGNUVersionSectionProlog( 4331 const typename ELFT::Shdr &Sec, const Twine &Label, unsigned EntriesNum) { 4332 // Don't inline the SecName, because it might report a warning to stderr and 4333 // corrupt the output. 4334 StringRef SecName = this->getPrintableSectionName(Sec); 4335 OS << Label << " section '" << SecName << "' " 4336 << "contains " << EntriesNum << " entries:\n"; 4337 4338 StringRef LinkedSecName = "<corrupt>"; 4339 if (Expected<const typename ELFT::Shdr *> LinkedSecOrErr = 4340 this->Obj.getSection(Sec.sh_link)) 4341 LinkedSecName = this->getPrintableSectionName(**LinkedSecOrErr); 4342 else 4343 this->reportUniqueWarning("invalid section linked to " + 4344 this->describe(Sec) + ": " + 4345 toString(LinkedSecOrErr.takeError())); 4346 4347 OS << " Addr: " << format_hex_no_prefix(Sec.sh_addr, 16) 4348 << " Offset: " << format_hex(Sec.sh_offset, 8) 4349 << " Link: " << Sec.sh_link << " (" << LinkedSecName << ")\n"; 4350 } 4351 4352 template <class ELFT> 4353 void GNUELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) { 4354 if (!Sec) 4355 return; 4356 4357 printGNUVersionSectionProlog(*Sec, "Version symbols", 4358 Sec->sh_size / sizeof(Elf_Versym)); 4359 Expected<ArrayRef<Elf_Versym>> VerTableOrErr = 4360 this->getVersionTable(*Sec, /*SymTab=*/nullptr, 4361 /*StrTab=*/nullptr, /*SymTabSec=*/nullptr); 4362 if (!VerTableOrErr) { 4363 this->reportUniqueWarning(VerTableOrErr.takeError()); 4364 return; 4365 } 4366 4367 SmallVector<Optional<VersionEntry>, 0> *VersionMap = nullptr; 4368 if (Expected<SmallVector<Optional<VersionEntry>, 0> *> MapOrErr = 4369 this->getVersionMap()) 4370 VersionMap = *MapOrErr; 4371 else 4372 this->reportUniqueWarning(MapOrErr.takeError()); 4373 4374 ArrayRef<Elf_Versym> VerTable = *VerTableOrErr; 4375 std::vector<StringRef> Versions; 4376 for (size_t I = 0, E = VerTable.size(); I < E; ++I) { 4377 unsigned Ndx = VerTable[I].vs_index; 4378 if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) { 4379 Versions.emplace_back(Ndx == VER_NDX_LOCAL ? "*local*" : "*global*"); 4380 continue; 4381 } 4382 4383 if (!VersionMap) { 4384 Versions.emplace_back("<corrupt>"); 4385 continue; 4386 } 4387 4388 bool IsDefault; 4389 Expected<StringRef> NameOrErr = this->Obj.getSymbolVersionByIndex( 4390 Ndx, IsDefault, *VersionMap, /*IsSymHidden=*/None); 4391 if (!NameOrErr) { 4392 this->reportUniqueWarning("unable to get a version for entry " + 4393 Twine(I) + " of " + this->describe(*Sec) + 4394 ": " + toString(NameOrErr.takeError())); 4395 Versions.emplace_back("<corrupt>"); 4396 continue; 4397 } 4398 Versions.emplace_back(*NameOrErr); 4399 } 4400 4401 // readelf prints 4 entries per line. 4402 uint64_t Entries = VerTable.size(); 4403 for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) { 4404 OS << " " << format_hex_no_prefix(VersymRow, 3) << ":"; 4405 for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) { 4406 unsigned Ndx = VerTable[VersymRow + I].vs_index; 4407 OS << format("%4x%c", Ndx & VERSYM_VERSION, 4408 Ndx & VERSYM_HIDDEN ? 'h' : ' '); 4409 OS << left_justify("(" + std::string(Versions[VersymRow + I]) + ")", 13); 4410 } 4411 OS << '\n'; 4412 } 4413 OS << '\n'; 4414 } 4415 4416 static std::string versionFlagToString(unsigned Flags) { 4417 if (Flags == 0) 4418 return "none"; 4419 4420 std::string Ret; 4421 auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) { 4422 if (!(Flags & Flag)) 4423 return; 4424 if (!Ret.empty()) 4425 Ret += " | "; 4426 Ret += Name; 4427 Flags &= ~Flag; 4428 }; 4429 4430 AddFlag(VER_FLG_BASE, "BASE"); 4431 AddFlag(VER_FLG_WEAK, "WEAK"); 4432 AddFlag(VER_FLG_INFO, "INFO"); 4433 AddFlag(~0, "<unknown>"); 4434 return Ret; 4435 } 4436 4437 template <class ELFT> 4438 void GNUELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) { 4439 if (!Sec) 4440 return; 4441 4442 printGNUVersionSectionProlog(*Sec, "Version definition", Sec->sh_info); 4443 4444 Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec); 4445 if (!V) { 4446 this->reportUniqueWarning(V.takeError()); 4447 return; 4448 } 4449 4450 for (const VerDef &Def : *V) { 4451 OS << format(" 0x%04x: Rev: %u Flags: %s Index: %u Cnt: %u Name: %s\n", 4452 Def.Offset, Def.Version, 4453 versionFlagToString(Def.Flags).c_str(), Def.Ndx, Def.Cnt, 4454 Def.Name.data()); 4455 unsigned I = 0; 4456 for (const VerdAux &Aux : Def.AuxV) 4457 OS << format(" 0x%04x: Parent %u: %s\n", Aux.Offset, ++I, 4458 Aux.Name.data()); 4459 } 4460 4461 OS << '\n'; 4462 } 4463 4464 template <class ELFT> 4465 void GNUELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) { 4466 if (!Sec) 4467 return; 4468 4469 unsigned VerneedNum = Sec->sh_info; 4470 printGNUVersionSectionProlog(*Sec, "Version needs", VerneedNum); 4471 4472 Expected<std::vector<VerNeed>> V = 4473 this->Obj.getVersionDependencies(*Sec, this->WarningHandler); 4474 if (!V) { 4475 this->reportUniqueWarning(V.takeError()); 4476 return; 4477 } 4478 4479 for (const VerNeed &VN : *V) { 4480 OS << format(" 0x%04x: Version: %u File: %s Cnt: %u\n", VN.Offset, 4481 VN.Version, VN.File.data(), VN.Cnt); 4482 for (const VernAux &Aux : VN.AuxV) 4483 OS << format(" 0x%04x: Name: %s Flags: %s Version: %u\n", Aux.Offset, 4484 Aux.Name.data(), versionFlagToString(Aux.Flags).c_str(), 4485 Aux.Other); 4486 } 4487 OS << '\n'; 4488 } 4489 4490 template <class ELFT> 4491 void GNUELFDumper<ELFT>::printHashHistogram(const Elf_Hash &HashTable) { 4492 size_t NBucket = HashTable.nbucket; 4493 size_t NChain = HashTable.nchain; 4494 ArrayRef<Elf_Word> Buckets = HashTable.buckets(); 4495 ArrayRef<Elf_Word> Chains = HashTable.chains(); 4496 size_t TotalSyms = 0; 4497 // If hash table is correct, we have at least chains with 0 length 4498 size_t MaxChain = 1; 4499 size_t CumulativeNonZero = 0; 4500 4501 if (NChain == 0 || NBucket == 0) 4502 return; 4503 4504 std::vector<size_t> ChainLen(NBucket, 0); 4505 // Go over all buckets and and note chain lengths of each bucket (total 4506 // unique chain lengths). 4507 for (size_t B = 0; B < NBucket; B++) { 4508 std::vector<bool> Visited(NChain); 4509 for (size_t C = Buckets[B]; C < NChain; C = Chains[C]) { 4510 if (C == ELF::STN_UNDEF) 4511 break; 4512 if (Visited[C]) { 4513 this->reportUniqueWarning(".hash section is invalid: bucket " + 4514 Twine(C) + 4515 ": a cycle was detected in the linked chain"); 4516 break; 4517 } 4518 Visited[C] = true; 4519 if (MaxChain <= ++ChainLen[B]) 4520 MaxChain++; 4521 } 4522 TotalSyms += ChainLen[B]; 4523 } 4524 4525 if (!TotalSyms) 4526 return; 4527 4528 std::vector<size_t> Count(MaxChain, 0); 4529 // Count how long is the chain for each bucket 4530 for (size_t B = 0; B < NBucket; B++) 4531 ++Count[ChainLen[B]]; 4532 // Print Number of buckets with each chain lengths and their cumulative 4533 // coverage of the symbols 4534 OS << "Histogram for bucket list length (total of " << NBucket 4535 << " buckets)\n" 4536 << " Length Number % of total Coverage\n"; 4537 for (size_t I = 0; I < MaxChain; I++) { 4538 CumulativeNonZero += Count[I] * I; 4539 OS << format("%7lu %-10lu (%5.1f%%) %5.1f%%\n", I, Count[I], 4540 (Count[I] * 100.0) / NBucket, 4541 (CumulativeNonZero * 100.0) / TotalSyms); 4542 } 4543 } 4544 4545 template <class ELFT> 4546 void GNUELFDumper<ELFT>::printGnuHashHistogram( 4547 const Elf_GnuHash &GnuHashTable) { 4548 Expected<ArrayRef<Elf_Word>> ChainsOrErr = 4549 getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHashTable); 4550 if (!ChainsOrErr) { 4551 this->reportUniqueWarning("unable to print the GNU hash table histogram: " + 4552 toString(ChainsOrErr.takeError())); 4553 return; 4554 } 4555 4556 ArrayRef<Elf_Word> Chains = *ChainsOrErr; 4557 size_t Symndx = GnuHashTable.symndx; 4558 size_t TotalSyms = 0; 4559 size_t MaxChain = 1; 4560 size_t CumulativeNonZero = 0; 4561 4562 size_t NBucket = GnuHashTable.nbuckets; 4563 if (Chains.empty() || NBucket == 0) 4564 return; 4565 4566 ArrayRef<Elf_Word> Buckets = GnuHashTable.buckets(); 4567 std::vector<size_t> ChainLen(NBucket, 0); 4568 for (size_t B = 0; B < NBucket; B++) { 4569 if (!Buckets[B]) 4570 continue; 4571 size_t Len = 1; 4572 for (size_t C = Buckets[B] - Symndx; 4573 C < Chains.size() && (Chains[C] & 1) == 0; C++) 4574 if (MaxChain < ++Len) 4575 MaxChain++; 4576 ChainLen[B] = Len; 4577 TotalSyms += Len; 4578 } 4579 MaxChain++; 4580 4581 if (!TotalSyms) 4582 return; 4583 4584 std::vector<size_t> Count(MaxChain, 0); 4585 for (size_t B = 0; B < NBucket; B++) 4586 ++Count[ChainLen[B]]; 4587 // Print Number of buckets with each chain lengths and their cumulative 4588 // coverage of the symbols 4589 OS << "Histogram for `.gnu.hash' bucket list length (total of " << NBucket 4590 << " buckets)\n" 4591 << " Length Number % of total Coverage\n"; 4592 for (size_t I = 0; I < MaxChain; I++) { 4593 CumulativeNonZero += Count[I] * I; 4594 OS << format("%7lu %-10lu (%5.1f%%) %5.1f%%\n", I, Count[I], 4595 (Count[I] * 100.0) / NBucket, 4596 (CumulativeNonZero * 100.0) / TotalSyms); 4597 } 4598 } 4599 4600 // Hash histogram shows statistics of how efficient the hash was for the 4601 // dynamic symbol table. The table shows the number of hash buckets for 4602 // different lengths of chains as an absolute number and percentage of the total 4603 // buckets, and the cumulative coverage of symbols for each set of buckets. 4604 template <class ELFT> void GNUELFDumper<ELFT>::printHashHistograms() { 4605 // Print histogram for the .hash section. 4606 if (this->HashTable) { 4607 if (Error E = checkHashTable<ELFT>(*this, this->HashTable)) 4608 this->reportUniqueWarning(std::move(E)); 4609 else 4610 printHashHistogram(*this->HashTable); 4611 } 4612 4613 // Print histogram for the .gnu.hash section. 4614 if (this->GnuHashTable) { 4615 if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable)) 4616 this->reportUniqueWarning(std::move(E)); 4617 else 4618 printGnuHashHistogram(*this->GnuHashTable); 4619 } 4620 } 4621 4622 template <class ELFT> void GNUELFDumper<ELFT>::printCGProfile() { 4623 OS << "GNUStyle::printCGProfile 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>::printAddrsig() { 6530 ListScope L(W, "Addrsig"); 6531 if (!this->DotAddrsigSec) 6532 return; 6533 6534 Expected<std::vector<uint64_t>> SymsOrErr = 6535 decodeAddrsigSection(this->Obj, *this->DotAddrsigSec); 6536 if (!SymsOrErr) { 6537 this->reportUniqueWarning(SymsOrErr.takeError()); 6538 return; 6539 } 6540 6541 for (uint64_t Sym : *SymsOrErr) 6542 W.printNumber("Sym", this->getStaticSymbolName(Sym), Sym); 6543 } 6544 6545 template <typename ELFT> 6546 static bool printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc, 6547 ScopedPrinter &W) { 6548 // Return true if we were able to pretty-print the note, false otherwise. 6549 switch (NoteType) { 6550 default: 6551 return false; 6552 case ELF::NT_GNU_ABI_TAG: { 6553 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc); 6554 if (!AbiTag.IsValid) { 6555 W.printString("ABI", "<corrupt GNU_ABI_TAG>"); 6556 return false; 6557 } else { 6558 W.printString("OS", AbiTag.OSName); 6559 W.printString("ABI", AbiTag.ABI); 6560 } 6561 break; 6562 } 6563 case ELF::NT_GNU_BUILD_ID: { 6564 W.printString("Build ID", getGNUBuildId(Desc)); 6565 break; 6566 } 6567 case ELF::NT_GNU_GOLD_VERSION: 6568 W.printString("Version", getGNUGoldVersion(Desc)); 6569 break; 6570 case ELF::NT_GNU_PROPERTY_TYPE_0: 6571 ListScope D(W, "Property"); 6572 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc)) 6573 W.printString(Property); 6574 break; 6575 } 6576 return true; 6577 } 6578 6579 static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) { 6580 W.printNumber("Page Size", Note.PageSize); 6581 for (const CoreFileMapping &Mapping : Note.Mappings) { 6582 ListScope D(W, "Mapping"); 6583 W.printHex("Start", Mapping.Start); 6584 W.printHex("End", Mapping.End); 6585 W.printHex("Offset", Mapping.Offset); 6586 W.printString("Filename", Mapping.Filename); 6587 } 6588 } 6589 6590 template <class ELFT> void LLVMELFDumper<ELFT>::printNotes() { 6591 ListScope L(W, "Notes"); 6592 6593 std::unique_ptr<DictScope> NoteScope; 6594 auto StartNotes = [&](Optional<StringRef> SecName, 6595 const typename ELFT::Off Offset, 6596 const typename ELFT::Addr Size) { 6597 NoteScope = std::make_unique<DictScope>(W, "NoteSection"); 6598 W.printString("Name", SecName ? *SecName : "<?>"); 6599 W.printHex("Offset", Offset); 6600 W.printHex("Size", Size); 6601 }; 6602 6603 auto EndNotes = [&] { NoteScope.reset(); }; 6604 6605 auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error { 6606 DictScope D2(W, "Note"); 6607 StringRef Name = Note.getName(); 6608 ArrayRef<uint8_t> Descriptor = Note.getDesc(); 6609 Elf_Word Type = Note.getType(); 6610 6611 // Print the note owner/type. 6612 W.printString("Owner", Name); 6613 W.printHex("Data size", Descriptor.size()); 6614 6615 StringRef NoteType = 6616 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type); 6617 if (!NoteType.empty()) 6618 W.printString("Type", NoteType); 6619 else 6620 W.printString("Type", 6621 "Unknown (" + to_string(format_hex(Type, 10)) + ")"); 6622 6623 // Print the description, or fallback to printing raw bytes for unknown 6624 // owners/if we fail to pretty-print the contents. 6625 if (Name == "GNU") { 6626 if (printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W)) 6627 return Error::success(); 6628 } else if (Name == "FreeBSD") { 6629 if (Optional<FreeBSDNote> N = 6630 getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) { 6631 W.printString(N->Type, N->Value); 6632 return Error::success(); 6633 } 6634 } else if (Name == "AMD") { 6635 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor); 6636 if (!N.Type.empty()) { 6637 W.printString(N.Type, N.Value); 6638 return Error::success(); 6639 } 6640 } else if (Name == "AMDGPU") { 6641 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor); 6642 if (!N.Type.empty()) { 6643 W.printString(N.Type, N.Value); 6644 return Error::success(); 6645 } 6646 } else if (Name == "CORE") { 6647 if (Type == ELF::NT_FILE) { 6648 DataExtractor DescExtractor(Descriptor, 6649 ELFT::TargetEndianness == support::little, 6650 sizeof(Elf_Addr)); 6651 if (Expected<CoreNote> N = readCoreNote(DescExtractor)) { 6652 printCoreNoteLLVMStyle(*N, W); 6653 return Error::success(); 6654 } else { 6655 return N.takeError(); 6656 } 6657 } 6658 } 6659 if (!Descriptor.empty()) { 6660 W.printBinaryBlock("Description data", Descriptor); 6661 } 6662 return Error::success(); 6663 }; 6664 6665 printNotesHelper(*this, StartNotes, ProcessNote, EndNotes); 6666 } 6667 6668 template <class ELFT> void LLVMELFDumper<ELFT>::printELFLinkerOptions() { 6669 ListScope L(W, "LinkerOptions"); 6670 6671 unsigned I = -1; 6672 for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) { 6673 ++I; 6674 if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS) 6675 continue; 6676 6677 Expected<ArrayRef<uint8_t>> ContentsOrErr = 6678 this->Obj.getSectionContents(Shdr); 6679 if (!ContentsOrErr) { 6680 this->reportUniqueWarning("unable to read the content of the " 6681 "SHT_LLVM_LINKER_OPTIONS section: " + 6682 toString(ContentsOrErr.takeError())); 6683 continue; 6684 } 6685 if (ContentsOrErr->empty()) 6686 continue; 6687 6688 if (ContentsOrErr->back() != 0) { 6689 this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " + 6690 Twine(I) + 6691 " is broken: the " 6692 "content is not null-terminated"); 6693 continue; 6694 } 6695 6696 SmallVector<StringRef, 16> Strings; 6697 toStringRef(ContentsOrErr->drop_back()).split(Strings, '\0'); 6698 if (Strings.size() % 2 != 0) { 6699 this->reportUniqueWarning( 6700 "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) + 6701 " is broken: an incomplete " 6702 "key-value pair was found. The last possible key was: \"" + 6703 Strings.back() + "\""); 6704 continue; 6705 } 6706 6707 for (size_t I = 0; I < Strings.size(); I += 2) 6708 W.printString(Strings[I], Strings[I + 1]); 6709 } 6710 } 6711 6712 template <class ELFT> void LLVMELFDumper<ELFT>::printDependentLibs() { 6713 ListScope L(W, "DependentLibs"); 6714 this->printDependentLibsHelper( 6715 [](const Elf_Shdr &) {}, 6716 [this](StringRef Lib, uint64_t) { W.printString(Lib); }); 6717 } 6718 6719 template <class ELFT> void LLVMELFDumper<ELFT>::printStackSizes() { 6720 ListScope L(W, "StackSizes"); 6721 if (this->Obj.getHeader().e_type == ELF::ET_REL) 6722 this->printRelocatableStackSizes([]() {}); 6723 else 6724 this->printNonRelocatableStackSizes([]() {}); 6725 } 6726 6727 template <class ELFT> 6728 void LLVMELFDumper<ELFT>::printStackSizeEntry(uint64_t Size, StringRef FuncName) { 6729 DictScope D(W, "Entry"); 6730 W.printString("Function", FuncName); 6731 W.printHex("Size", Size); 6732 } 6733 6734 template <class ELFT> 6735 void LLVMELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) { 6736 auto PrintEntry = [&](const Elf_Addr *E) { 6737 W.printHex("Address", Parser.getGotAddress(E)); 6738 W.printNumber("Access", Parser.getGotOffset(E)); 6739 W.printHex("Initial", *E); 6740 }; 6741 6742 DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT"); 6743 6744 W.printHex("Canonical gp value", Parser.getGp()); 6745 { 6746 ListScope RS(W, "Reserved entries"); 6747 { 6748 DictScope D(W, "Entry"); 6749 PrintEntry(Parser.getGotLazyResolver()); 6750 W.printString("Purpose", StringRef("Lazy resolver")); 6751 } 6752 6753 if (Parser.getGotModulePointer()) { 6754 DictScope D(W, "Entry"); 6755 PrintEntry(Parser.getGotModulePointer()); 6756 W.printString("Purpose", StringRef("Module pointer (GNU extension)")); 6757 } 6758 } 6759 { 6760 ListScope LS(W, "Local entries"); 6761 for (auto &E : Parser.getLocalEntries()) { 6762 DictScope D(W, "Entry"); 6763 PrintEntry(&E); 6764 } 6765 } 6766 6767 if (Parser.IsStatic) 6768 return; 6769 6770 { 6771 ListScope GS(W, "Global entries"); 6772 for (auto &E : Parser.getGlobalEntries()) { 6773 DictScope D(W, "Entry"); 6774 6775 PrintEntry(&E); 6776 6777 const Elf_Sym &Sym = *Parser.getGotSym(&E); 6778 W.printHex("Value", Sym.st_value); 6779 W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes)); 6780 6781 const unsigned SymIndex = &Sym - this->dynamic_symbols().begin(); 6782 DataRegion<Elf_Word> ShndxTable( 6783 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end()); 6784 printSymbolSection(Sym, SymIndex, ShndxTable); 6785 6786 std::string SymName = this->getFullSymbolName( 6787 Sym, SymIndex, ShndxTable, this->DynamicStringTable, true); 6788 W.printNumber("Name", SymName, Sym.st_name); 6789 } 6790 } 6791 6792 W.printNumber("Number of TLS and multi-GOT entries", 6793 uint64_t(Parser.getOtherEntries().size())); 6794 } 6795 6796 template <class ELFT> 6797 void LLVMELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) { 6798 auto PrintEntry = [&](const Elf_Addr *E) { 6799 W.printHex("Address", Parser.getPltAddress(E)); 6800 W.printHex("Initial", *E); 6801 }; 6802 6803 DictScope GS(W, "PLT GOT"); 6804 6805 { 6806 ListScope RS(W, "Reserved entries"); 6807 { 6808 DictScope D(W, "Entry"); 6809 PrintEntry(Parser.getPltLazyResolver()); 6810 W.printString("Purpose", StringRef("PLT lazy resolver")); 6811 } 6812 6813 if (auto E = Parser.getPltModulePointer()) { 6814 DictScope D(W, "Entry"); 6815 PrintEntry(E); 6816 W.printString("Purpose", StringRef("Module pointer")); 6817 } 6818 } 6819 { 6820 ListScope LS(W, "Entries"); 6821 DataRegion<Elf_Word> ShndxTable( 6822 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end()); 6823 for (auto &E : Parser.getPltEntries()) { 6824 DictScope D(W, "Entry"); 6825 PrintEntry(&E); 6826 6827 const Elf_Sym &Sym = *Parser.getPltSym(&E); 6828 W.printHex("Value", Sym.st_value); 6829 W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes)); 6830 printSymbolSection(Sym, &Sym - this->dynamic_symbols().begin(), 6831 ShndxTable); 6832 6833 const Elf_Sym *FirstSym = cantFail( 6834 this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0)); 6835 std::string SymName = this->getFullSymbolName( 6836 Sym, &Sym - FirstSym, ShndxTable, Parser.getPltStrTable(), true); 6837 W.printNumber("Name", SymName, Sym.st_name); 6838 } 6839 } 6840 } 6841 6842 template <class ELFT> void LLVMELFDumper<ELFT>::printMipsABIFlags() { 6843 const Elf_Mips_ABIFlags<ELFT> *Flags; 6844 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr = 6845 getMipsAbiFlagsSection(*this)) { 6846 Flags = *SecOrErr; 6847 if (!Flags) { 6848 W.startLine() << "There is no .MIPS.abiflags section in the file.\n"; 6849 return; 6850 } 6851 } else { 6852 this->reportUniqueWarning(SecOrErr.takeError()); 6853 return; 6854 } 6855 6856 raw_ostream &OS = W.getOStream(); 6857 DictScope GS(W, "MIPS ABI Flags"); 6858 6859 W.printNumber("Version", Flags->version); 6860 W.startLine() << "ISA: "; 6861 if (Flags->isa_rev <= 1) 6862 OS << format("MIPS%u", Flags->isa_level); 6863 else 6864 OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev); 6865 OS << "\n"; 6866 W.printEnum("ISA Extension", Flags->isa_ext, makeArrayRef(ElfMipsISAExtType)); 6867 W.printFlags("ASEs", Flags->ases, makeArrayRef(ElfMipsASEFlags)); 6868 W.printEnum("FP ABI", Flags->fp_abi, makeArrayRef(ElfMipsFpABIType)); 6869 W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size)); 6870 W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size)); 6871 W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size)); 6872 W.printFlags("Flags 1", Flags->flags1, makeArrayRef(ElfMipsFlags1)); 6873 W.printHex("Flags 2", Flags->flags2); 6874 } 6875