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