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