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