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