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