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