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 const EnumEntry<unsigned> ElfHeaderLoongArchFlags[] = { 1652 ENUM_ENT(EF_LOONGARCH_BASE_ABI_ILP32S, "ILP32, SOFT-FLOAT"), 1653 ENUM_ENT(EF_LOONGARCH_BASE_ABI_ILP32F, "ILP32, SINGLE-FLOAT"), 1654 ENUM_ENT(EF_LOONGARCH_BASE_ABI_ILP32D, "ILP32, DOUBLE-FLOAT"), 1655 ENUM_ENT(EF_LOONGARCH_BASE_ABI_LP64S, "LP64, SOFT-FLOAT"), 1656 ENUM_ENT(EF_LOONGARCH_BASE_ABI_LP64F, "LP64, SINGLE-FLOAT"), 1657 ENUM_ENT(EF_LOONGARCH_BASE_ABI_LP64D, "LP64, DOUBLE-FLOAT"), 1658 }; 1659 1660 1661 const EnumEntry<unsigned> ElfSymOtherFlags[] = { 1662 LLVM_READOBJ_ENUM_ENT(ELF, STV_INTERNAL), 1663 LLVM_READOBJ_ENUM_ENT(ELF, STV_HIDDEN), 1664 LLVM_READOBJ_ENUM_ENT(ELF, STV_PROTECTED) 1665 }; 1666 1667 const EnumEntry<unsigned> ElfMipsSymOtherFlags[] = { 1668 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL), 1669 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT), 1670 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PIC), 1671 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MICROMIPS) 1672 }; 1673 1674 const EnumEntry<unsigned> ElfAArch64SymOtherFlags[] = { 1675 LLVM_READOBJ_ENUM_ENT(ELF, STO_AARCH64_VARIANT_PCS) 1676 }; 1677 1678 const EnumEntry<unsigned> ElfMips16SymOtherFlags[] = { 1679 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_OPTIONAL), 1680 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_PLT), 1681 LLVM_READOBJ_ENUM_ENT(ELF, STO_MIPS_MIPS16) 1682 }; 1683 1684 const EnumEntry<unsigned> ElfRISCVSymOtherFlags[] = { 1685 LLVM_READOBJ_ENUM_ENT(ELF, STO_RISCV_VARIANT_CC)}; 1686 1687 static const char *getElfMipsOptionsOdkType(unsigned Odk) { 1688 switch (Odk) { 1689 LLVM_READOBJ_ENUM_CASE(ELF, ODK_NULL); 1690 LLVM_READOBJ_ENUM_CASE(ELF, ODK_REGINFO); 1691 LLVM_READOBJ_ENUM_CASE(ELF, ODK_EXCEPTIONS); 1692 LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAD); 1693 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWPATCH); 1694 LLVM_READOBJ_ENUM_CASE(ELF, ODK_FILL); 1695 LLVM_READOBJ_ENUM_CASE(ELF, ODK_TAGS); 1696 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWAND); 1697 LLVM_READOBJ_ENUM_CASE(ELF, ODK_HWOR); 1698 LLVM_READOBJ_ENUM_CASE(ELF, ODK_GP_GROUP); 1699 LLVM_READOBJ_ENUM_CASE(ELF, ODK_IDENT); 1700 LLVM_READOBJ_ENUM_CASE(ELF, ODK_PAGESIZE); 1701 default: 1702 return "Unknown"; 1703 } 1704 } 1705 1706 template <typename ELFT> 1707 std::pair<const typename ELFT::Phdr *, const typename ELFT::Shdr *> 1708 ELFDumper<ELFT>::findDynamic() { 1709 // Try to locate the PT_DYNAMIC header. 1710 const Elf_Phdr *DynamicPhdr = nullptr; 1711 if (Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = Obj.program_headers()) { 1712 for (const Elf_Phdr &Phdr : *PhdrsOrErr) { 1713 if (Phdr.p_type != ELF::PT_DYNAMIC) 1714 continue; 1715 DynamicPhdr = &Phdr; 1716 break; 1717 } 1718 } else { 1719 reportUniqueWarning( 1720 "unable to read program headers to locate the PT_DYNAMIC segment: " + 1721 toString(PhdrsOrErr.takeError())); 1722 } 1723 1724 // Try to locate the .dynamic section in the sections header table. 1725 const Elf_Shdr *DynamicSec = nullptr; 1726 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) { 1727 if (Sec.sh_type != ELF::SHT_DYNAMIC) 1728 continue; 1729 DynamicSec = &Sec; 1730 break; 1731 } 1732 1733 if (DynamicPhdr && ((DynamicPhdr->p_offset + DynamicPhdr->p_filesz > 1734 ObjF.getMemoryBufferRef().getBufferSize()) || 1735 (DynamicPhdr->p_offset + DynamicPhdr->p_filesz < 1736 DynamicPhdr->p_offset))) { 1737 reportUniqueWarning( 1738 "PT_DYNAMIC segment offset (0x" + 1739 Twine::utohexstr(DynamicPhdr->p_offset) + ") + file size (0x" + 1740 Twine::utohexstr(DynamicPhdr->p_filesz) + 1741 ") exceeds the size of the file (0x" + 1742 Twine::utohexstr(ObjF.getMemoryBufferRef().getBufferSize()) + ")"); 1743 // Don't use the broken dynamic header. 1744 DynamicPhdr = nullptr; 1745 } 1746 1747 if (DynamicPhdr && DynamicSec) { 1748 if (DynamicSec->sh_addr + DynamicSec->sh_size > 1749 DynamicPhdr->p_vaddr + DynamicPhdr->p_memsz || 1750 DynamicSec->sh_addr < DynamicPhdr->p_vaddr) 1751 reportUniqueWarning(describe(*DynamicSec) + 1752 " is not contained within the " 1753 "PT_DYNAMIC segment"); 1754 1755 if (DynamicSec->sh_addr != DynamicPhdr->p_vaddr) 1756 reportUniqueWarning(describe(*DynamicSec) + " is not at the start of " 1757 "PT_DYNAMIC segment"); 1758 } 1759 1760 return std::make_pair(DynamicPhdr, DynamicSec); 1761 } 1762 1763 template <typename ELFT> 1764 void ELFDumper<ELFT>::loadDynamicTable() { 1765 const Elf_Phdr *DynamicPhdr; 1766 const Elf_Shdr *DynamicSec; 1767 std::tie(DynamicPhdr, DynamicSec) = findDynamic(); 1768 if (!DynamicPhdr && !DynamicSec) 1769 return; 1770 1771 DynRegionInfo FromPhdr(ObjF, *this); 1772 bool IsPhdrTableValid = false; 1773 if (DynamicPhdr) { 1774 // Use cantFail(), because p_offset/p_filesz fields of a PT_DYNAMIC are 1775 // validated in findDynamic() and so createDRI() is not expected to fail. 1776 FromPhdr = cantFail(createDRI(DynamicPhdr->p_offset, DynamicPhdr->p_filesz, 1777 sizeof(Elf_Dyn))); 1778 FromPhdr.SizePrintName = "PT_DYNAMIC size"; 1779 FromPhdr.EntSizePrintName = ""; 1780 IsPhdrTableValid = !FromPhdr.template getAsArrayRef<Elf_Dyn>().empty(); 1781 } 1782 1783 // Locate the dynamic table described in a section header. 1784 // Ignore sh_entsize and use the expected value for entry size explicitly. 1785 // This allows us to dump dynamic sections with a broken sh_entsize 1786 // field. 1787 DynRegionInfo FromSec(ObjF, *this); 1788 bool IsSecTableValid = false; 1789 if (DynamicSec) { 1790 Expected<DynRegionInfo> RegOrErr = 1791 createDRI(DynamicSec->sh_offset, DynamicSec->sh_size, sizeof(Elf_Dyn)); 1792 if (RegOrErr) { 1793 FromSec = *RegOrErr; 1794 FromSec.Context = describe(*DynamicSec); 1795 FromSec.EntSizePrintName = ""; 1796 IsSecTableValid = !FromSec.template getAsArrayRef<Elf_Dyn>().empty(); 1797 } else { 1798 reportUniqueWarning("unable to read the dynamic table from " + 1799 describe(*DynamicSec) + ": " + 1800 toString(RegOrErr.takeError())); 1801 } 1802 } 1803 1804 // When we only have information from one of the SHT_DYNAMIC section header or 1805 // PT_DYNAMIC program header, just use that. 1806 if (!DynamicPhdr || !DynamicSec) { 1807 if ((DynamicPhdr && IsPhdrTableValid) || (DynamicSec && IsSecTableValid)) { 1808 DynamicTable = DynamicPhdr ? FromPhdr : FromSec; 1809 parseDynamicTable(); 1810 } else { 1811 reportUniqueWarning("no valid dynamic table was found"); 1812 } 1813 return; 1814 } 1815 1816 // At this point we have tables found from the section header and from the 1817 // dynamic segment. Usually they match, but we have to do sanity checks to 1818 // verify that. 1819 1820 if (FromPhdr.Addr != FromSec.Addr) 1821 reportUniqueWarning("SHT_DYNAMIC section header and PT_DYNAMIC " 1822 "program header disagree about " 1823 "the location of the dynamic table"); 1824 1825 if (!IsPhdrTableValid && !IsSecTableValid) { 1826 reportUniqueWarning("no valid dynamic table was found"); 1827 return; 1828 } 1829 1830 // Information in the PT_DYNAMIC program header has priority over the 1831 // information in a section header. 1832 if (IsPhdrTableValid) { 1833 if (!IsSecTableValid) 1834 reportUniqueWarning( 1835 "SHT_DYNAMIC dynamic table is invalid: PT_DYNAMIC will be used"); 1836 DynamicTable = FromPhdr; 1837 } else { 1838 reportUniqueWarning( 1839 "PT_DYNAMIC dynamic table is invalid: SHT_DYNAMIC will be used"); 1840 DynamicTable = FromSec; 1841 } 1842 1843 parseDynamicTable(); 1844 } 1845 1846 template <typename ELFT> 1847 ELFDumper<ELFT>::ELFDumper(const object::ELFObjectFile<ELFT> &O, 1848 ScopedPrinter &Writer) 1849 : ObjDumper(Writer, O.getFileName()), ObjF(O), Obj(O.getELFFile()), 1850 FileName(O.getFileName()), DynRelRegion(O, *this), 1851 DynRelaRegion(O, *this), DynRelrRegion(O, *this), 1852 DynPLTRelRegion(O, *this), DynSymTabShndxRegion(O, *this), 1853 DynamicTable(O, *this) { 1854 if (!O.IsContentValid()) 1855 return; 1856 1857 typename ELFT::ShdrRange Sections = cantFail(Obj.sections()); 1858 for (const Elf_Shdr &Sec : Sections) { 1859 switch (Sec.sh_type) { 1860 case ELF::SHT_SYMTAB: 1861 if (!DotSymtabSec) 1862 DotSymtabSec = &Sec; 1863 break; 1864 case ELF::SHT_DYNSYM: 1865 if (!DotDynsymSec) 1866 DotDynsymSec = &Sec; 1867 1868 if (!DynSymRegion) { 1869 Expected<DynRegionInfo> RegOrErr = 1870 createDRI(Sec.sh_offset, Sec.sh_size, Sec.sh_entsize); 1871 if (RegOrErr) { 1872 DynSymRegion = *RegOrErr; 1873 DynSymRegion->Context = describe(Sec); 1874 1875 if (Expected<StringRef> E = Obj.getStringTableForSymtab(Sec)) 1876 DynamicStringTable = *E; 1877 else 1878 reportUniqueWarning("unable to get the string table for the " + 1879 describe(Sec) + ": " + toString(E.takeError())); 1880 } else { 1881 reportUniqueWarning("unable to read dynamic symbols from " + 1882 describe(Sec) + ": " + 1883 toString(RegOrErr.takeError())); 1884 } 1885 } 1886 break; 1887 case ELF::SHT_SYMTAB_SHNDX: { 1888 uint32_t SymtabNdx = Sec.sh_link; 1889 if (SymtabNdx >= Sections.size()) { 1890 reportUniqueWarning( 1891 "unable to get the associated symbol table for " + describe(Sec) + 1892 ": sh_link (" + Twine(SymtabNdx) + 1893 ") is greater than or equal to the total number of sections (" + 1894 Twine(Sections.size()) + ")"); 1895 continue; 1896 } 1897 1898 if (Expected<ArrayRef<Elf_Word>> ShndxTableOrErr = 1899 Obj.getSHNDXTable(Sec)) { 1900 if (!ShndxTables.insert({&Sections[SymtabNdx], *ShndxTableOrErr}) 1901 .second) 1902 reportUniqueWarning( 1903 "multiple SHT_SYMTAB_SHNDX sections are linked to " + 1904 describe(Sec)); 1905 } else { 1906 reportUniqueWarning(ShndxTableOrErr.takeError()); 1907 } 1908 break; 1909 } 1910 case ELF::SHT_GNU_versym: 1911 if (!SymbolVersionSection) 1912 SymbolVersionSection = &Sec; 1913 break; 1914 case ELF::SHT_GNU_verdef: 1915 if (!SymbolVersionDefSection) 1916 SymbolVersionDefSection = &Sec; 1917 break; 1918 case ELF::SHT_GNU_verneed: 1919 if (!SymbolVersionNeedSection) 1920 SymbolVersionNeedSection = &Sec; 1921 break; 1922 case ELF::SHT_LLVM_ADDRSIG: 1923 if (!DotAddrsigSec) 1924 DotAddrsigSec = &Sec; 1925 break; 1926 } 1927 } 1928 1929 loadDynamicTable(); 1930 } 1931 1932 template <typename ELFT> void ELFDumper<ELFT>::parseDynamicTable() { 1933 auto toMappedAddr = [&](uint64_t Tag, uint64_t VAddr) -> const uint8_t * { 1934 auto MappedAddrOrError = Obj.toMappedAddr(VAddr, [&](const Twine &Msg) { 1935 this->reportUniqueWarning(Msg); 1936 return Error::success(); 1937 }); 1938 if (!MappedAddrOrError) { 1939 this->reportUniqueWarning("unable to parse DT_" + 1940 Obj.getDynamicTagAsString(Tag) + ": " + 1941 llvm::toString(MappedAddrOrError.takeError())); 1942 return nullptr; 1943 } 1944 return MappedAddrOrError.get(); 1945 }; 1946 1947 const char *StringTableBegin = nullptr; 1948 uint64_t StringTableSize = 0; 1949 Optional<DynRegionInfo> DynSymFromTable; 1950 for (const Elf_Dyn &Dyn : dynamic_table()) { 1951 switch (Dyn.d_tag) { 1952 case ELF::DT_HASH: 1953 HashTable = reinterpret_cast<const Elf_Hash *>( 1954 toMappedAddr(Dyn.getTag(), Dyn.getPtr())); 1955 break; 1956 case ELF::DT_GNU_HASH: 1957 GnuHashTable = reinterpret_cast<const Elf_GnuHash *>( 1958 toMappedAddr(Dyn.getTag(), Dyn.getPtr())); 1959 break; 1960 case ELF::DT_STRTAB: 1961 StringTableBegin = reinterpret_cast<const char *>( 1962 toMappedAddr(Dyn.getTag(), Dyn.getPtr())); 1963 break; 1964 case ELF::DT_STRSZ: 1965 StringTableSize = Dyn.getVal(); 1966 break; 1967 case ELF::DT_SYMTAB: { 1968 // If we can't map the DT_SYMTAB value to an address (e.g. when there are 1969 // no program headers), we ignore its value. 1970 if (const uint8_t *VA = toMappedAddr(Dyn.getTag(), Dyn.getPtr())) { 1971 DynSymFromTable.emplace(ObjF, *this); 1972 DynSymFromTable->Addr = VA; 1973 DynSymFromTable->EntSize = sizeof(Elf_Sym); 1974 DynSymFromTable->EntSizePrintName = ""; 1975 } 1976 break; 1977 } 1978 case ELF::DT_SYMENT: { 1979 uint64_t Val = Dyn.getVal(); 1980 if (Val != sizeof(Elf_Sym)) 1981 this->reportUniqueWarning("DT_SYMENT value of 0x" + 1982 Twine::utohexstr(Val) + 1983 " is not the size of a symbol (0x" + 1984 Twine::utohexstr(sizeof(Elf_Sym)) + ")"); 1985 break; 1986 } 1987 case ELF::DT_RELA: 1988 DynRelaRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr()); 1989 break; 1990 case ELF::DT_RELASZ: 1991 DynRelaRegion.Size = Dyn.getVal(); 1992 DynRelaRegion.SizePrintName = "DT_RELASZ value"; 1993 break; 1994 case ELF::DT_RELAENT: 1995 DynRelaRegion.EntSize = Dyn.getVal(); 1996 DynRelaRegion.EntSizePrintName = "DT_RELAENT value"; 1997 break; 1998 case ELF::DT_SONAME: 1999 SONameOffset = Dyn.getVal(); 2000 break; 2001 case ELF::DT_REL: 2002 DynRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr()); 2003 break; 2004 case ELF::DT_RELSZ: 2005 DynRelRegion.Size = Dyn.getVal(); 2006 DynRelRegion.SizePrintName = "DT_RELSZ value"; 2007 break; 2008 case ELF::DT_RELENT: 2009 DynRelRegion.EntSize = Dyn.getVal(); 2010 DynRelRegion.EntSizePrintName = "DT_RELENT value"; 2011 break; 2012 case ELF::DT_RELR: 2013 case ELF::DT_ANDROID_RELR: 2014 DynRelrRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr()); 2015 break; 2016 case ELF::DT_RELRSZ: 2017 case ELF::DT_ANDROID_RELRSZ: 2018 DynRelrRegion.Size = Dyn.getVal(); 2019 DynRelrRegion.SizePrintName = Dyn.d_tag == ELF::DT_RELRSZ 2020 ? "DT_RELRSZ value" 2021 : "DT_ANDROID_RELRSZ value"; 2022 break; 2023 case ELF::DT_RELRENT: 2024 case ELF::DT_ANDROID_RELRENT: 2025 DynRelrRegion.EntSize = Dyn.getVal(); 2026 DynRelrRegion.EntSizePrintName = Dyn.d_tag == ELF::DT_RELRENT 2027 ? "DT_RELRENT value" 2028 : "DT_ANDROID_RELRENT value"; 2029 break; 2030 case ELF::DT_PLTREL: 2031 if (Dyn.getVal() == DT_REL) 2032 DynPLTRelRegion.EntSize = sizeof(Elf_Rel); 2033 else if (Dyn.getVal() == DT_RELA) 2034 DynPLTRelRegion.EntSize = sizeof(Elf_Rela); 2035 else 2036 reportUniqueWarning(Twine("unknown DT_PLTREL value of ") + 2037 Twine((uint64_t)Dyn.getVal())); 2038 DynPLTRelRegion.EntSizePrintName = "PLTREL entry size"; 2039 break; 2040 case ELF::DT_JMPREL: 2041 DynPLTRelRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr()); 2042 break; 2043 case ELF::DT_PLTRELSZ: 2044 DynPLTRelRegion.Size = Dyn.getVal(); 2045 DynPLTRelRegion.SizePrintName = "DT_PLTRELSZ value"; 2046 break; 2047 case ELF::DT_SYMTAB_SHNDX: 2048 DynSymTabShndxRegion.Addr = toMappedAddr(Dyn.getTag(), Dyn.getPtr()); 2049 DynSymTabShndxRegion.EntSize = sizeof(Elf_Word); 2050 break; 2051 } 2052 } 2053 2054 if (StringTableBegin) { 2055 const uint64_t FileSize = Obj.getBufSize(); 2056 const uint64_t Offset = (const uint8_t *)StringTableBegin - Obj.base(); 2057 if (StringTableSize > FileSize - Offset) 2058 reportUniqueWarning( 2059 "the dynamic string table at 0x" + Twine::utohexstr(Offset) + 2060 " goes past the end of the file (0x" + Twine::utohexstr(FileSize) + 2061 ") with DT_STRSZ = 0x" + Twine::utohexstr(StringTableSize)); 2062 else 2063 DynamicStringTable = StringRef(StringTableBegin, StringTableSize); 2064 } 2065 2066 const bool IsHashTableSupported = getHashTableEntSize() == 4; 2067 if (DynSymRegion) { 2068 // Often we find the information about the dynamic symbol table 2069 // location in the SHT_DYNSYM section header. However, the value in 2070 // DT_SYMTAB has priority, because it is used by dynamic loaders to 2071 // locate .dynsym at runtime. The location we find in the section header 2072 // and the location we find here should match. 2073 if (DynSymFromTable && DynSymFromTable->Addr != DynSymRegion->Addr) 2074 reportUniqueWarning( 2075 createError("SHT_DYNSYM section header and DT_SYMTAB disagree about " 2076 "the location of the dynamic symbol table")); 2077 2078 // According to the ELF gABI: "The number of symbol table entries should 2079 // equal nchain". Check to see if the DT_HASH hash table nchain value 2080 // conflicts with the number of symbols in the dynamic symbol table 2081 // according to the section header. 2082 if (HashTable && IsHashTableSupported) { 2083 if (DynSymRegion->EntSize == 0) 2084 reportUniqueWarning("SHT_DYNSYM section has sh_entsize == 0"); 2085 else if (HashTable->nchain != DynSymRegion->Size / DynSymRegion->EntSize) 2086 reportUniqueWarning( 2087 "hash table nchain (" + Twine(HashTable->nchain) + 2088 ") differs from symbol count derived from SHT_DYNSYM section " 2089 "header (" + 2090 Twine(DynSymRegion->Size / DynSymRegion->EntSize) + ")"); 2091 } 2092 } 2093 2094 // Delay the creation of the actual dynamic symbol table until now, so that 2095 // checks can always be made against the section header-based properties, 2096 // without worrying about tag order. 2097 if (DynSymFromTable) { 2098 if (!DynSymRegion) { 2099 DynSymRegion = DynSymFromTable; 2100 } else { 2101 DynSymRegion->Addr = DynSymFromTable->Addr; 2102 DynSymRegion->EntSize = DynSymFromTable->EntSize; 2103 DynSymRegion->EntSizePrintName = DynSymFromTable->EntSizePrintName; 2104 } 2105 } 2106 2107 // Derive the dynamic symbol table size from the DT_HASH hash table, if 2108 // present. 2109 if (HashTable && IsHashTableSupported && DynSymRegion) { 2110 const uint64_t FileSize = Obj.getBufSize(); 2111 const uint64_t DerivedSize = 2112 (uint64_t)HashTable->nchain * DynSymRegion->EntSize; 2113 const uint64_t Offset = (const uint8_t *)DynSymRegion->Addr - Obj.base(); 2114 if (DerivedSize > FileSize - Offset) 2115 reportUniqueWarning( 2116 "the size (0x" + Twine::utohexstr(DerivedSize) + 2117 ") of the dynamic symbol table at 0x" + Twine::utohexstr(Offset) + 2118 ", derived from the hash table, goes past the end of the file (0x" + 2119 Twine::utohexstr(FileSize) + ") and will be ignored"); 2120 else 2121 DynSymRegion->Size = HashTable->nchain * DynSymRegion->EntSize; 2122 } 2123 } 2124 2125 template <typename ELFT> void ELFDumper<ELFT>::printVersionInfo() { 2126 // Dump version symbol section. 2127 printVersionSymbolSection(SymbolVersionSection); 2128 2129 // Dump version definition section. 2130 printVersionDefinitionSection(SymbolVersionDefSection); 2131 2132 // Dump version dependency section. 2133 printVersionDependencySection(SymbolVersionNeedSection); 2134 } 2135 2136 #define LLVM_READOBJ_DT_FLAG_ENT(prefix, enum) \ 2137 { #enum, prefix##_##enum } 2138 2139 const EnumEntry<unsigned> ElfDynamicDTFlags[] = { 2140 LLVM_READOBJ_DT_FLAG_ENT(DF, ORIGIN), 2141 LLVM_READOBJ_DT_FLAG_ENT(DF, SYMBOLIC), 2142 LLVM_READOBJ_DT_FLAG_ENT(DF, TEXTREL), 2143 LLVM_READOBJ_DT_FLAG_ENT(DF, BIND_NOW), 2144 LLVM_READOBJ_DT_FLAG_ENT(DF, STATIC_TLS) 2145 }; 2146 2147 const EnumEntry<unsigned> ElfDynamicDTFlags1[] = { 2148 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOW), 2149 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAL), 2150 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GROUP), 2151 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODELETE), 2152 LLVM_READOBJ_DT_FLAG_ENT(DF_1, LOADFLTR), 2153 LLVM_READOBJ_DT_FLAG_ENT(DF_1, INITFIRST), 2154 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOOPEN), 2155 LLVM_READOBJ_DT_FLAG_ENT(DF_1, ORIGIN), 2156 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DIRECT), 2157 LLVM_READOBJ_DT_FLAG_ENT(DF_1, TRANS), 2158 LLVM_READOBJ_DT_FLAG_ENT(DF_1, INTERPOSE), 2159 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODEFLIB), 2160 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODUMP), 2161 LLVM_READOBJ_DT_FLAG_ENT(DF_1, CONFALT), 2162 LLVM_READOBJ_DT_FLAG_ENT(DF_1, ENDFILTEE), 2163 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELDNE), 2164 LLVM_READOBJ_DT_FLAG_ENT(DF_1, DISPRELPND), 2165 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NODIRECT), 2166 LLVM_READOBJ_DT_FLAG_ENT(DF_1, IGNMULDEF), 2167 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOKSYMS), 2168 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NOHDR), 2169 LLVM_READOBJ_DT_FLAG_ENT(DF_1, EDITED), 2170 LLVM_READOBJ_DT_FLAG_ENT(DF_1, NORELOC), 2171 LLVM_READOBJ_DT_FLAG_ENT(DF_1, SYMINTPOSE), 2172 LLVM_READOBJ_DT_FLAG_ENT(DF_1, GLOBAUDIT), 2173 LLVM_READOBJ_DT_FLAG_ENT(DF_1, SINGLETON), 2174 LLVM_READOBJ_DT_FLAG_ENT(DF_1, PIE), 2175 }; 2176 2177 const EnumEntry<unsigned> ElfDynamicDTMipsFlags[] = { 2178 LLVM_READOBJ_DT_FLAG_ENT(RHF, NONE), 2179 LLVM_READOBJ_DT_FLAG_ENT(RHF, QUICKSTART), 2180 LLVM_READOBJ_DT_FLAG_ENT(RHF, NOTPOT), 2181 LLVM_READOBJ_DT_FLAG_ENT(RHS, NO_LIBRARY_REPLACEMENT), 2182 LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_MOVE), 2183 LLVM_READOBJ_DT_FLAG_ENT(RHF, SGI_ONLY), 2184 LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_INIT), 2185 LLVM_READOBJ_DT_FLAG_ENT(RHF, DELTA_C_PLUS_PLUS), 2186 LLVM_READOBJ_DT_FLAG_ENT(RHF, GUARANTEE_START_INIT), 2187 LLVM_READOBJ_DT_FLAG_ENT(RHF, PIXIE), 2188 LLVM_READOBJ_DT_FLAG_ENT(RHF, DEFAULT_DELAY_LOAD), 2189 LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTART), 2190 LLVM_READOBJ_DT_FLAG_ENT(RHF, REQUICKSTARTED), 2191 LLVM_READOBJ_DT_FLAG_ENT(RHF, CORD), 2192 LLVM_READOBJ_DT_FLAG_ENT(RHF, NO_UNRES_UNDEF), 2193 LLVM_READOBJ_DT_FLAG_ENT(RHF, RLD_ORDER_SAFE) 2194 }; 2195 2196 #undef LLVM_READOBJ_DT_FLAG_ENT 2197 2198 template <typename T, typename TFlag> 2199 void printFlags(T Value, ArrayRef<EnumEntry<TFlag>> Flags, raw_ostream &OS) { 2200 SmallVector<EnumEntry<TFlag>, 10> SetFlags; 2201 for (const EnumEntry<TFlag> &Flag : Flags) 2202 if (Flag.Value != 0 && (Value & Flag.Value) == Flag.Value) 2203 SetFlags.push_back(Flag); 2204 2205 for (const EnumEntry<TFlag> &Flag : SetFlags) 2206 OS << Flag.Name << " "; 2207 } 2208 2209 template <class ELFT> 2210 const typename ELFT::Shdr * 2211 ELFDumper<ELFT>::findSectionByName(StringRef Name) const { 2212 for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) { 2213 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Shdr)) { 2214 if (*NameOrErr == Name) 2215 return &Shdr; 2216 } else { 2217 reportUniqueWarning("unable to read the name of " + describe(Shdr) + 2218 ": " + toString(NameOrErr.takeError())); 2219 } 2220 } 2221 return nullptr; 2222 } 2223 2224 template <class ELFT> 2225 std::string ELFDumper<ELFT>::getDynamicEntry(uint64_t Type, 2226 uint64_t Value) const { 2227 auto FormatHexValue = [](uint64_t V) { 2228 std::string Str; 2229 raw_string_ostream OS(Str); 2230 const char *ConvChar = 2231 (opts::Output == opts::GNU) ? "0x%" PRIx64 : "0x%" PRIX64; 2232 OS << format(ConvChar, V); 2233 return OS.str(); 2234 }; 2235 2236 auto FormatFlags = [](uint64_t V, 2237 llvm::ArrayRef<llvm::EnumEntry<unsigned int>> Array) { 2238 std::string Str; 2239 raw_string_ostream OS(Str); 2240 printFlags(V, Array, OS); 2241 return OS.str(); 2242 }; 2243 2244 // Handle custom printing of architecture specific tags 2245 switch (Obj.getHeader().e_machine) { 2246 case EM_AARCH64: 2247 switch (Type) { 2248 case DT_AARCH64_BTI_PLT: 2249 case DT_AARCH64_PAC_PLT: 2250 case DT_AARCH64_VARIANT_PCS: 2251 return std::to_string(Value); 2252 default: 2253 break; 2254 } 2255 break; 2256 case EM_HEXAGON: 2257 switch (Type) { 2258 case DT_HEXAGON_VER: 2259 return std::to_string(Value); 2260 case DT_HEXAGON_SYMSZ: 2261 case DT_HEXAGON_PLT: 2262 return FormatHexValue(Value); 2263 default: 2264 break; 2265 } 2266 break; 2267 case EM_MIPS: 2268 switch (Type) { 2269 case DT_MIPS_RLD_VERSION: 2270 case DT_MIPS_LOCAL_GOTNO: 2271 case DT_MIPS_SYMTABNO: 2272 case DT_MIPS_UNREFEXTNO: 2273 return std::to_string(Value); 2274 case DT_MIPS_TIME_STAMP: 2275 case DT_MIPS_ICHECKSUM: 2276 case DT_MIPS_IVERSION: 2277 case DT_MIPS_BASE_ADDRESS: 2278 case DT_MIPS_MSYM: 2279 case DT_MIPS_CONFLICT: 2280 case DT_MIPS_LIBLIST: 2281 case DT_MIPS_CONFLICTNO: 2282 case DT_MIPS_LIBLISTNO: 2283 case DT_MIPS_GOTSYM: 2284 case DT_MIPS_HIPAGENO: 2285 case DT_MIPS_RLD_MAP: 2286 case DT_MIPS_DELTA_CLASS: 2287 case DT_MIPS_DELTA_CLASS_NO: 2288 case DT_MIPS_DELTA_INSTANCE: 2289 case DT_MIPS_DELTA_RELOC: 2290 case DT_MIPS_DELTA_RELOC_NO: 2291 case DT_MIPS_DELTA_SYM: 2292 case DT_MIPS_DELTA_SYM_NO: 2293 case DT_MIPS_DELTA_CLASSSYM: 2294 case DT_MIPS_DELTA_CLASSSYM_NO: 2295 case DT_MIPS_CXX_FLAGS: 2296 case DT_MIPS_PIXIE_INIT: 2297 case DT_MIPS_SYMBOL_LIB: 2298 case DT_MIPS_LOCALPAGE_GOTIDX: 2299 case DT_MIPS_LOCAL_GOTIDX: 2300 case DT_MIPS_HIDDEN_GOTIDX: 2301 case DT_MIPS_PROTECTED_GOTIDX: 2302 case DT_MIPS_OPTIONS: 2303 case DT_MIPS_INTERFACE: 2304 case DT_MIPS_DYNSTR_ALIGN: 2305 case DT_MIPS_INTERFACE_SIZE: 2306 case DT_MIPS_RLD_TEXT_RESOLVE_ADDR: 2307 case DT_MIPS_PERF_SUFFIX: 2308 case DT_MIPS_COMPACT_SIZE: 2309 case DT_MIPS_GP_VALUE: 2310 case DT_MIPS_AUX_DYNAMIC: 2311 case DT_MIPS_PLTGOT: 2312 case DT_MIPS_RWPLT: 2313 case DT_MIPS_RLD_MAP_REL: 2314 case DT_MIPS_XHASH: 2315 return FormatHexValue(Value); 2316 case DT_MIPS_FLAGS: 2317 return FormatFlags(Value, makeArrayRef(ElfDynamicDTMipsFlags)); 2318 default: 2319 break; 2320 } 2321 break; 2322 default: 2323 break; 2324 } 2325 2326 switch (Type) { 2327 case DT_PLTREL: 2328 if (Value == DT_REL) 2329 return "REL"; 2330 if (Value == DT_RELA) 2331 return "RELA"; 2332 LLVM_FALLTHROUGH; 2333 case DT_PLTGOT: 2334 case DT_HASH: 2335 case DT_STRTAB: 2336 case DT_SYMTAB: 2337 case DT_RELA: 2338 case DT_INIT: 2339 case DT_FINI: 2340 case DT_REL: 2341 case DT_JMPREL: 2342 case DT_INIT_ARRAY: 2343 case DT_FINI_ARRAY: 2344 case DT_PREINIT_ARRAY: 2345 case DT_DEBUG: 2346 case DT_VERDEF: 2347 case DT_VERNEED: 2348 case DT_VERSYM: 2349 case DT_GNU_HASH: 2350 case DT_NULL: 2351 return FormatHexValue(Value); 2352 case DT_RELACOUNT: 2353 case DT_RELCOUNT: 2354 case DT_VERDEFNUM: 2355 case DT_VERNEEDNUM: 2356 return std::to_string(Value); 2357 case DT_PLTRELSZ: 2358 case DT_RELASZ: 2359 case DT_RELAENT: 2360 case DT_STRSZ: 2361 case DT_SYMENT: 2362 case DT_RELSZ: 2363 case DT_RELENT: 2364 case DT_INIT_ARRAYSZ: 2365 case DT_FINI_ARRAYSZ: 2366 case DT_PREINIT_ARRAYSZ: 2367 case DT_RELRSZ: 2368 case DT_RELRENT: 2369 case DT_ANDROID_RELSZ: 2370 case DT_ANDROID_RELASZ: 2371 return std::to_string(Value) + " (bytes)"; 2372 case DT_NEEDED: 2373 case DT_SONAME: 2374 case DT_AUXILIARY: 2375 case DT_USED: 2376 case DT_FILTER: 2377 case DT_RPATH: 2378 case DT_RUNPATH: { 2379 const std::map<uint64_t, const char *> TagNames = { 2380 {DT_NEEDED, "Shared library"}, {DT_SONAME, "Library soname"}, 2381 {DT_AUXILIARY, "Auxiliary library"}, {DT_USED, "Not needed object"}, 2382 {DT_FILTER, "Filter library"}, {DT_RPATH, "Library rpath"}, 2383 {DT_RUNPATH, "Library runpath"}, 2384 }; 2385 2386 return (Twine(TagNames.at(Type)) + ": [" + getDynamicString(Value) + "]") 2387 .str(); 2388 } 2389 case DT_FLAGS: 2390 return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags)); 2391 case DT_FLAGS_1: 2392 return FormatFlags(Value, makeArrayRef(ElfDynamicDTFlags1)); 2393 default: 2394 return FormatHexValue(Value); 2395 } 2396 } 2397 2398 template <class ELFT> 2399 StringRef ELFDumper<ELFT>::getDynamicString(uint64_t Value) const { 2400 if (DynamicStringTable.empty() && !DynamicStringTable.data()) { 2401 reportUniqueWarning("string table was not found"); 2402 return "<?>"; 2403 } 2404 2405 auto WarnAndReturn = [this](const Twine &Msg, uint64_t Offset) { 2406 reportUniqueWarning("string table at offset 0x" + Twine::utohexstr(Offset) + 2407 Msg); 2408 return "<?>"; 2409 }; 2410 2411 const uint64_t FileSize = Obj.getBufSize(); 2412 const uint64_t Offset = 2413 (const uint8_t *)DynamicStringTable.data() - Obj.base(); 2414 if (DynamicStringTable.size() > FileSize - Offset) 2415 return WarnAndReturn(" with size 0x" + 2416 Twine::utohexstr(DynamicStringTable.size()) + 2417 " goes past the end of the file (0x" + 2418 Twine::utohexstr(FileSize) + ")", 2419 Offset); 2420 2421 if (Value >= DynamicStringTable.size()) 2422 return WarnAndReturn( 2423 ": unable to read the string at 0x" + Twine::utohexstr(Offset + Value) + 2424 ": it goes past the end of the table (0x" + 2425 Twine::utohexstr(Offset + DynamicStringTable.size()) + ")", 2426 Offset); 2427 2428 if (DynamicStringTable.back() != '\0') 2429 return WarnAndReturn(": unable to read the string at 0x" + 2430 Twine::utohexstr(Offset + Value) + 2431 ": the string table is not null-terminated", 2432 Offset); 2433 2434 return DynamicStringTable.data() + Value; 2435 } 2436 2437 template <class ELFT> void ELFDumper<ELFT>::printUnwindInfo() { 2438 DwarfCFIEH::PrinterContext<ELFT> Ctx(W, ObjF); 2439 Ctx.printUnwindInformation(); 2440 } 2441 2442 // The namespace is needed to fix the compilation with GCC older than 7.0+. 2443 namespace { 2444 template <> void ELFDumper<ELF32LE>::printUnwindInfo() { 2445 if (Obj.getHeader().e_machine == EM_ARM) { 2446 ARM::EHABI::PrinterContext<ELF32LE> Ctx(W, Obj, ObjF.getFileName(), 2447 DotSymtabSec); 2448 Ctx.PrintUnwindInformation(); 2449 } 2450 DwarfCFIEH::PrinterContext<ELF32LE> Ctx(W, ObjF); 2451 Ctx.printUnwindInformation(); 2452 } 2453 } // namespace 2454 2455 template <class ELFT> void ELFDumper<ELFT>::printNeededLibraries() { 2456 ListScope D(W, "NeededLibraries"); 2457 2458 std::vector<StringRef> Libs; 2459 for (const auto &Entry : dynamic_table()) 2460 if (Entry.d_tag == ELF::DT_NEEDED) 2461 Libs.push_back(getDynamicString(Entry.d_un.d_val)); 2462 2463 llvm::sort(Libs); 2464 2465 for (StringRef L : Libs) 2466 W.startLine() << L << "\n"; 2467 } 2468 2469 template <class ELFT> 2470 static Error checkHashTable(const ELFDumper<ELFT> &Dumper, 2471 const typename ELFT::Hash *H, 2472 bool *IsHeaderValid = nullptr) { 2473 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile(); 2474 const uint64_t SecOffset = (const uint8_t *)H - Obj.base(); 2475 if (Dumper.getHashTableEntSize() == 8) { 2476 auto It = llvm::find_if(ElfMachineType, [&](const EnumEntry<unsigned> &E) { 2477 return E.Value == Obj.getHeader().e_machine; 2478 }); 2479 if (IsHeaderValid) 2480 *IsHeaderValid = false; 2481 return createError("the hash table at 0x" + Twine::utohexstr(SecOffset) + 2482 " is not supported: it contains non-standard 8 " 2483 "byte entries on " + 2484 It->AltName + " platform"); 2485 } 2486 2487 auto MakeError = [&](const Twine &Msg = "") { 2488 return createError("the hash table at offset 0x" + 2489 Twine::utohexstr(SecOffset) + 2490 " goes past the end of the file (0x" + 2491 Twine::utohexstr(Obj.getBufSize()) + ")" + Msg); 2492 }; 2493 2494 // Each SHT_HASH section starts from two 32-bit fields: nbucket and nchain. 2495 const unsigned HeaderSize = 2 * sizeof(typename ELFT::Word); 2496 2497 if (IsHeaderValid) 2498 *IsHeaderValid = Obj.getBufSize() - SecOffset >= HeaderSize; 2499 2500 if (Obj.getBufSize() - SecOffset < HeaderSize) 2501 return MakeError(); 2502 2503 if (Obj.getBufSize() - SecOffset - HeaderSize < 2504 ((uint64_t)H->nbucket + H->nchain) * sizeof(typename ELFT::Word)) 2505 return MakeError(", nbucket = " + Twine(H->nbucket) + 2506 ", nchain = " + Twine(H->nchain)); 2507 return Error::success(); 2508 } 2509 2510 template <class ELFT> 2511 static Error checkGNUHashTable(const ELFFile<ELFT> &Obj, 2512 const typename ELFT::GnuHash *GnuHashTable, 2513 bool *IsHeaderValid = nullptr) { 2514 const uint8_t *TableData = reinterpret_cast<const uint8_t *>(GnuHashTable); 2515 assert(TableData >= Obj.base() && TableData < Obj.base() + Obj.getBufSize() && 2516 "GnuHashTable must always point to a location inside the file"); 2517 2518 uint64_t TableOffset = TableData - Obj.base(); 2519 if (IsHeaderValid) 2520 *IsHeaderValid = TableOffset + /*Header size:*/ 16 < Obj.getBufSize(); 2521 if (TableOffset + 16 + (uint64_t)GnuHashTable->nbuckets * 4 + 2522 (uint64_t)GnuHashTable->maskwords * sizeof(typename ELFT::Off) >= 2523 Obj.getBufSize()) 2524 return createError("unable to dump the SHT_GNU_HASH " 2525 "section at 0x" + 2526 Twine::utohexstr(TableOffset) + 2527 ": it goes past the end of the file"); 2528 return Error::success(); 2529 } 2530 2531 template <typename ELFT> void ELFDumper<ELFT>::printHashTable() { 2532 DictScope D(W, "HashTable"); 2533 if (!HashTable) 2534 return; 2535 2536 bool IsHeaderValid; 2537 Error Err = checkHashTable(*this, HashTable, &IsHeaderValid); 2538 if (IsHeaderValid) { 2539 W.printNumber("Num Buckets", HashTable->nbucket); 2540 W.printNumber("Num Chains", HashTable->nchain); 2541 } 2542 2543 if (Err) { 2544 reportUniqueWarning(std::move(Err)); 2545 return; 2546 } 2547 2548 W.printList("Buckets", HashTable->buckets()); 2549 W.printList("Chains", HashTable->chains()); 2550 } 2551 2552 template <class ELFT> 2553 static Expected<ArrayRef<typename ELFT::Word>> 2554 getGnuHashTableChains(Optional<DynRegionInfo> DynSymRegion, 2555 const typename ELFT::GnuHash *GnuHashTable) { 2556 if (!DynSymRegion) 2557 return createError("no dynamic symbol table found"); 2558 2559 ArrayRef<typename ELFT::Sym> DynSymTable = 2560 DynSymRegion->template getAsArrayRef<typename ELFT::Sym>(); 2561 size_t NumSyms = DynSymTable.size(); 2562 if (!NumSyms) 2563 return createError("the dynamic symbol table is empty"); 2564 2565 if (GnuHashTable->symndx < NumSyms) 2566 return GnuHashTable->values(NumSyms); 2567 2568 // A normal empty GNU hash table section produced by linker might have 2569 // symndx set to the number of dynamic symbols + 1 (for the zero symbol) 2570 // and have dummy null values in the Bloom filter and in the buckets 2571 // vector (or no values at all). It happens because the value of symndx is not 2572 // important for dynamic loaders when the GNU hash table is empty. They just 2573 // skip the whole object during symbol lookup. In such cases, the symndx value 2574 // is irrelevant and we should not report a warning. 2575 ArrayRef<typename ELFT::Word> Buckets = GnuHashTable->buckets(); 2576 if (!llvm::all_of(Buckets, [](typename ELFT::Word V) { return V == 0; })) 2577 return createError( 2578 "the first hashed symbol index (" + Twine(GnuHashTable->symndx) + 2579 ") is greater than or equal to the number of dynamic symbols (" + 2580 Twine(NumSyms) + ")"); 2581 // There is no way to represent an array of (dynamic symbols count - symndx) 2582 // length. 2583 return ArrayRef<typename ELFT::Word>(); 2584 } 2585 2586 template <typename ELFT> 2587 void ELFDumper<ELFT>::printGnuHashTable() { 2588 DictScope D(W, "GnuHashTable"); 2589 if (!GnuHashTable) 2590 return; 2591 2592 bool IsHeaderValid; 2593 Error Err = checkGNUHashTable<ELFT>(Obj, GnuHashTable, &IsHeaderValid); 2594 if (IsHeaderValid) { 2595 W.printNumber("Num Buckets", GnuHashTable->nbuckets); 2596 W.printNumber("First Hashed Symbol Index", GnuHashTable->symndx); 2597 W.printNumber("Num Mask Words", GnuHashTable->maskwords); 2598 W.printNumber("Shift Count", GnuHashTable->shift2); 2599 } 2600 2601 if (Err) { 2602 reportUniqueWarning(std::move(Err)); 2603 return; 2604 } 2605 2606 ArrayRef<typename ELFT::Off> BloomFilter = GnuHashTable->filter(); 2607 W.printHexList("Bloom Filter", BloomFilter); 2608 2609 ArrayRef<Elf_Word> Buckets = GnuHashTable->buckets(); 2610 W.printList("Buckets", Buckets); 2611 2612 Expected<ArrayRef<Elf_Word>> Chains = 2613 getGnuHashTableChains<ELFT>(DynSymRegion, GnuHashTable); 2614 if (!Chains) { 2615 reportUniqueWarning("unable to dump 'Values' for the SHT_GNU_HASH " 2616 "section: " + 2617 toString(Chains.takeError())); 2618 return; 2619 } 2620 2621 W.printHexList("Values", *Chains); 2622 } 2623 2624 template <typename ELFT> void ELFDumper<ELFT>::printLoadName() { 2625 StringRef SOName = "<Not found>"; 2626 if (SONameOffset) 2627 SOName = getDynamicString(*SONameOffset); 2628 W.printString("LoadName", SOName); 2629 } 2630 2631 template <class ELFT> void ELFDumper<ELFT>::printArchSpecificInfo() { 2632 switch (Obj.getHeader().e_machine) { 2633 case EM_ARM: 2634 if (Obj.isLE()) 2635 printAttributes(ELF::SHT_ARM_ATTRIBUTES, 2636 std::make_unique<ARMAttributeParser>(&W), 2637 support::little); 2638 else 2639 reportUniqueWarning("attribute printing not implemented for big-endian " 2640 "ARM objects"); 2641 break; 2642 case EM_RISCV: 2643 if (Obj.isLE()) 2644 printAttributes(ELF::SHT_RISCV_ATTRIBUTES, 2645 std::make_unique<RISCVAttributeParser>(&W), 2646 support::little); 2647 else 2648 reportUniqueWarning("attribute printing not implemented for big-endian " 2649 "RISC-V objects"); 2650 break; 2651 case EM_MSP430: 2652 printAttributes(ELF::SHT_MSP430_ATTRIBUTES, 2653 std::make_unique<MSP430AttributeParser>(&W), 2654 support::little); 2655 break; 2656 case EM_MIPS: { 2657 printMipsABIFlags(); 2658 printMipsOptions(); 2659 printMipsReginfo(); 2660 MipsGOTParser<ELFT> Parser(*this); 2661 if (Error E = Parser.findGOT(dynamic_table(), dynamic_symbols())) 2662 reportUniqueWarning(std::move(E)); 2663 else if (!Parser.isGotEmpty()) 2664 printMipsGOT(Parser); 2665 2666 if (Error E = Parser.findPLT(dynamic_table())) 2667 reportUniqueWarning(std::move(E)); 2668 else if (!Parser.isPltEmpty()) 2669 printMipsPLT(Parser); 2670 break; 2671 } 2672 default: 2673 break; 2674 } 2675 } 2676 2677 template <class ELFT> 2678 void ELFDumper<ELFT>::printAttributes( 2679 unsigned AttrShType, std::unique_ptr<ELFAttributeParser> AttrParser, 2680 support::endianness Endianness) { 2681 assert((AttrShType != ELF::SHT_NULL) && AttrParser && 2682 "Incomplete ELF attribute implementation"); 2683 DictScope BA(W, "BuildAttributes"); 2684 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) { 2685 if (Sec.sh_type != AttrShType) 2686 continue; 2687 2688 ArrayRef<uint8_t> Contents; 2689 if (Expected<ArrayRef<uint8_t>> ContentOrErr = 2690 Obj.getSectionContents(Sec)) { 2691 Contents = *ContentOrErr; 2692 if (Contents.empty()) { 2693 reportUniqueWarning("the " + describe(Sec) + " is empty"); 2694 continue; 2695 } 2696 } else { 2697 reportUniqueWarning("unable to read the content of the " + describe(Sec) + 2698 ": " + toString(ContentOrErr.takeError())); 2699 continue; 2700 } 2701 2702 W.printHex("FormatVersion", Contents[0]); 2703 2704 if (Error E = AttrParser->parse(Contents, Endianness)) 2705 reportUniqueWarning("unable to dump attributes from the " + 2706 describe(Sec) + ": " + toString(std::move(E))); 2707 } 2708 } 2709 2710 namespace { 2711 2712 template <class ELFT> class MipsGOTParser { 2713 public: 2714 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT) 2715 using Entry = typename ELFT::Addr; 2716 using Entries = ArrayRef<Entry>; 2717 2718 const bool IsStatic; 2719 const ELFFile<ELFT> &Obj; 2720 const ELFDumper<ELFT> &Dumper; 2721 2722 MipsGOTParser(const ELFDumper<ELFT> &D); 2723 Error findGOT(Elf_Dyn_Range DynTable, Elf_Sym_Range DynSyms); 2724 Error findPLT(Elf_Dyn_Range DynTable); 2725 2726 bool isGotEmpty() const { return GotEntries.empty(); } 2727 bool isPltEmpty() const { return PltEntries.empty(); } 2728 2729 uint64_t getGp() const; 2730 2731 const Entry *getGotLazyResolver() const; 2732 const Entry *getGotModulePointer() const; 2733 const Entry *getPltLazyResolver() const; 2734 const Entry *getPltModulePointer() const; 2735 2736 Entries getLocalEntries() const; 2737 Entries getGlobalEntries() const; 2738 Entries getOtherEntries() const; 2739 Entries getPltEntries() const; 2740 2741 uint64_t getGotAddress(const Entry * E) const; 2742 int64_t getGotOffset(const Entry * E) const; 2743 const Elf_Sym *getGotSym(const Entry *E) const; 2744 2745 uint64_t getPltAddress(const Entry * E) const; 2746 const Elf_Sym *getPltSym(const Entry *E) const; 2747 2748 StringRef getPltStrTable() const { return PltStrTable; } 2749 const Elf_Shdr *getPltSymTable() const { return PltSymTable; } 2750 2751 private: 2752 const Elf_Shdr *GotSec; 2753 size_t LocalNum; 2754 size_t GlobalNum; 2755 2756 const Elf_Shdr *PltSec; 2757 const Elf_Shdr *PltRelSec; 2758 const Elf_Shdr *PltSymTable; 2759 StringRef FileName; 2760 2761 Elf_Sym_Range GotDynSyms; 2762 StringRef PltStrTable; 2763 2764 Entries GotEntries; 2765 Entries PltEntries; 2766 }; 2767 2768 } // end anonymous namespace 2769 2770 template <class ELFT> 2771 MipsGOTParser<ELFT>::MipsGOTParser(const ELFDumper<ELFT> &D) 2772 : IsStatic(D.dynamic_table().empty()), Obj(D.getElfObject().getELFFile()), 2773 Dumper(D), GotSec(nullptr), LocalNum(0), GlobalNum(0), PltSec(nullptr), 2774 PltRelSec(nullptr), PltSymTable(nullptr), 2775 FileName(D.getElfObject().getFileName()) {} 2776 2777 template <class ELFT> 2778 Error MipsGOTParser<ELFT>::findGOT(Elf_Dyn_Range DynTable, 2779 Elf_Sym_Range DynSyms) { 2780 // See "Global Offset Table" in Chapter 5 in the following document 2781 // for detailed GOT description. 2782 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf 2783 2784 // Find static GOT secton. 2785 if (IsStatic) { 2786 GotSec = Dumper.findSectionByName(".got"); 2787 if (!GotSec) 2788 return Error::success(); 2789 2790 ArrayRef<uint8_t> Content = 2791 unwrapOrError(FileName, Obj.getSectionContents(*GotSec)); 2792 GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()), 2793 Content.size() / sizeof(Entry)); 2794 LocalNum = GotEntries.size(); 2795 return Error::success(); 2796 } 2797 2798 // Lookup dynamic table tags which define the GOT layout. 2799 Optional<uint64_t> DtPltGot; 2800 Optional<uint64_t> DtLocalGotNum; 2801 Optional<uint64_t> DtGotSym; 2802 for (const auto &Entry : DynTable) { 2803 switch (Entry.getTag()) { 2804 case ELF::DT_PLTGOT: 2805 DtPltGot = Entry.getVal(); 2806 break; 2807 case ELF::DT_MIPS_LOCAL_GOTNO: 2808 DtLocalGotNum = Entry.getVal(); 2809 break; 2810 case ELF::DT_MIPS_GOTSYM: 2811 DtGotSym = Entry.getVal(); 2812 break; 2813 } 2814 } 2815 2816 if (!DtPltGot && !DtLocalGotNum && !DtGotSym) 2817 return Error::success(); 2818 2819 if (!DtPltGot) 2820 return createError("cannot find PLTGOT dynamic tag"); 2821 if (!DtLocalGotNum) 2822 return createError("cannot find MIPS_LOCAL_GOTNO dynamic tag"); 2823 if (!DtGotSym) 2824 return createError("cannot find MIPS_GOTSYM dynamic tag"); 2825 2826 size_t DynSymTotal = DynSyms.size(); 2827 if (*DtGotSym > DynSymTotal) 2828 return createError("DT_MIPS_GOTSYM value (" + Twine(*DtGotSym) + 2829 ") exceeds the number of dynamic symbols (" + 2830 Twine(DynSymTotal) + ")"); 2831 2832 GotSec = findNotEmptySectionByAddress(Obj, FileName, *DtPltGot); 2833 if (!GotSec) 2834 return createError("there is no non-empty GOT section at 0x" + 2835 Twine::utohexstr(*DtPltGot)); 2836 2837 LocalNum = *DtLocalGotNum; 2838 GlobalNum = DynSymTotal - *DtGotSym; 2839 2840 ArrayRef<uint8_t> Content = 2841 unwrapOrError(FileName, Obj.getSectionContents(*GotSec)); 2842 GotEntries = Entries(reinterpret_cast<const Entry *>(Content.data()), 2843 Content.size() / sizeof(Entry)); 2844 GotDynSyms = DynSyms.drop_front(*DtGotSym); 2845 2846 return Error::success(); 2847 } 2848 2849 template <class ELFT> 2850 Error MipsGOTParser<ELFT>::findPLT(Elf_Dyn_Range DynTable) { 2851 // Lookup dynamic table tags which define the PLT layout. 2852 Optional<uint64_t> DtMipsPltGot; 2853 Optional<uint64_t> DtJmpRel; 2854 for (const auto &Entry : DynTable) { 2855 switch (Entry.getTag()) { 2856 case ELF::DT_MIPS_PLTGOT: 2857 DtMipsPltGot = Entry.getVal(); 2858 break; 2859 case ELF::DT_JMPREL: 2860 DtJmpRel = Entry.getVal(); 2861 break; 2862 } 2863 } 2864 2865 if (!DtMipsPltGot && !DtJmpRel) 2866 return Error::success(); 2867 2868 // Find PLT section. 2869 if (!DtMipsPltGot) 2870 return createError("cannot find MIPS_PLTGOT dynamic tag"); 2871 if (!DtJmpRel) 2872 return createError("cannot find JMPREL dynamic tag"); 2873 2874 PltSec = findNotEmptySectionByAddress(Obj, FileName, *DtMipsPltGot); 2875 if (!PltSec) 2876 return createError("there is no non-empty PLTGOT section at 0x" + 2877 Twine::utohexstr(*DtMipsPltGot)); 2878 2879 PltRelSec = findNotEmptySectionByAddress(Obj, FileName, *DtJmpRel); 2880 if (!PltRelSec) 2881 return createError("there is no non-empty RELPLT section at 0x" + 2882 Twine::utohexstr(*DtJmpRel)); 2883 2884 if (Expected<ArrayRef<uint8_t>> PltContentOrErr = 2885 Obj.getSectionContents(*PltSec)) 2886 PltEntries = 2887 Entries(reinterpret_cast<const Entry *>(PltContentOrErr->data()), 2888 PltContentOrErr->size() / sizeof(Entry)); 2889 else 2890 return createError("unable to read PLTGOT section content: " + 2891 toString(PltContentOrErr.takeError())); 2892 2893 if (Expected<const Elf_Shdr *> PltSymTableOrErr = 2894 Obj.getSection(PltRelSec->sh_link)) 2895 PltSymTable = *PltSymTableOrErr; 2896 else 2897 return createError("unable to get a symbol table linked to the " + 2898 describe(Obj, *PltRelSec) + ": " + 2899 toString(PltSymTableOrErr.takeError())); 2900 2901 if (Expected<StringRef> StrTabOrErr = 2902 Obj.getStringTableForSymtab(*PltSymTable)) 2903 PltStrTable = *StrTabOrErr; 2904 else 2905 return createError("unable to get a string table for the " + 2906 describe(Obj, *PltSymTable) + ": " + 2907 toString(StrTabOrErr.takeError())); 2908 2909 return Error::success(); 2910 } 2911 2912 template <class ELFT> uint64_t MipsGOTParser<ELFT>::getGp() const { 2913 return GotSec->sh_addr + 0x7ff0; 2914 } 2915 2916 template <class ELFT> 2917 const typename MipsGOTParser<ELFT>::Entry * 2918 MipsGOTParser<ELFT>::getGotLazyResolver() const { 2919 return LocalNum > 0 ? &GotEntries[0] : nullptr; 2920 } 2921 2922 template <class ELFT> 2923 const typename MipsGOTParser<ELFT>::Entry * 2924 MipsGOTParser<ELFT>::getGotModulePointer() const { 2925 if (LocalNum < 2) 2926 return nullptr; 2927 const Entry &E = GotEntries[1]; 2928 if ((E >> (sizeof(Entry) * 8 - 1)) == 0) 2929 return nullptr; 2930 return &E; 2931 } 2932 2933 template <class ELFT> 2934 typename MipsGOTParser<ELFT>::Entries 2935 MipsGOTParser<ELFT>::getLocalEntries() const { 2936 size_t Skip = getGotModulePointer() ? 2 : 1; 2937 if (LocalNum - Skip <= 0) 2938 return Entries(); 2939 return GotEntries.slice(Skip, LocalNum - Skip); 2940 } 2941 2942 template <class ELFT> 2943 typename MipsGOTParser<ELFT>::Entries 2944 MipsGOTParser<ELFT>::getGlobalEntries() const { 2945 if (GlobalNum == 0) 2946 return Entries(); 2947 return GotEntries.slice(LocalNum, GlobalNum); 2948 } 2949 2950 template <class ELFT> 2951 typename MipsGOTParser<ELFT>::Entries 2952 MipsGOTParser<ELFT>::getOtherEntries() const { 2953 size_t OtherNum = GotEntries.size() - LocalNum - GlobalNum; 2954 if (OtherNum == 0) 2955 return Entries(); 2956 return GotEntries.slice(LocalNum + GlobalNum, OtherNum); 2957 } 2958 2959 template <class ELFT> 2960 uint64_t MipsGOTParser<ELFT>::getGotAddress(const Entry *E) const { 2961 int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry); 2962 return GotSec->sh_addr + Offset; 2963 } 2964 2965 template <class ELFT> 2966 int64_t MipsGOTParser<ELFT>::getGotOffset(const Entry *E) const { 2967 int64_t Offset = std::distance(GotEntries.data(), E) * sizeof(Entry); 2968 return Offset - 0x7ff0; 2969 } 2970 2971 template <class ELFT> 2972 const typename MipsGOTParser<ELFT>::Elf_Sym * 2973 MipsGOTParser<ELFT>::getGotSym(const Entry *E) const { 2974 int64_t Offset = std::distance(GotEntries.data(), E); 2975 return &GotDynSyms[Offset - LocalNum]; 2976 } 2977 2978 template <class ELFT> 2979 const typename MipsGOTParser<ELFT>::Entry * 2980 MipsGOTParser<ELFT>::getPltLazyResolver() const { 2981 return PltEntries.empty() ? nullptr : &PltEntries[0]; 2982 } 2983 2984 template <class ELFT> 2985 const typename MipsGOTParser<ELFT>::Entry * 2986 MipsGOTParser<ELFT>::getPltModulePointer() const { 2987 return PltEntries.size() < 2 ? nullptr : &PltEntries[1]; 2988 } 2989 2990 template <class ELFT> 2991 typename MipsGOTParser<ELFT>::Entries 2992 MipsGOTParser<ELFT>::getPltEntries() const { 2993 if (PltEntries.size() <= 2) 2994 return Entries(); 2995 return PltEntries.slice(2, PltEntries.size() - 2); 2996 } 2997 2998 template <class ELFT> 2999 uint64_t MipsGOTParser<ELFT>::getPltAddress(const Entry *E) const { 3000 int64_t Offset = std::distance(PltEntries.data(), E) * sizeof(Entry); 3001 return PltSec->sh_addr + Offset; 3002 } 3003 3004 template <class ELFT> 3005 const typename MipsGOTParser<ELFT>::Elf_Sym * 3006 MipsGOTParser<ELFT>::getPltSym(const Entry *E) const { 3007 int64_t Offset = std::distance(getPltEntries().data(), E); 3008 if (PltRelSec->sh_type == ELF::SHT_REL) { 3009 Elf_Rel_Range Rels = unwrapOrError(FileName, Obj.rels(*PltRelSec)); 3010 return unwrapOrError(FileName, 3011 Obj.getRelocationSymbol(Rels[Offset], PltSymTable)); 3012 } else { 3013 Elf_Rela_Range Rels = unwrapOrError(FileName, Obj.relas(*PltRelSec)); 3014 return unwrapOrError(FileName, 3015 Obj.getRelocationSymbol(Rels[Offset], PltSymTable)); 3016 } 3017 } 3018 3019 const EnumEntry<unsigned> ElfMipsISAExtType[] = { 3020 {"None", Mips::AFL_EXT_NONE}, 3021 {"Broadcom SB-1", Mips::AFL_EXT_SB1}, 3022 {"Cavium Networks Octeon", Mips::AFL_EXT_OCTEON}, 3023 {"Cavium Networks Octeon2", Mips::AFL_EXT_OCTEON2}, 3024 {"Cavium Networks OcteonP", Mips::AFL_EXT_OCTEONP}, 3025 {"Cavium Networks Octeon3", Mips::AFL_EXT_OCTEON3}, 3026 {"LSI R4010", Mips::AFL_EXT_4010}, 3027 {"Loongson 2E", Mips::AFL_EXT_LOONGSON_2E}, 3028 {"Loongson 2F", Mips::AFL_EXT_LOONGSON_2F}, 3029 {"Loongson 3A", Mips::AFL_EXT_LOONGSON_3A}, 3030 {"MIPS R4650", Mips::AFL_EXT_4650}, 3031 {"MIPS R5900", Mips::AFL_EXT_5900}, 3032 {"MIPS R10000", Mips::AFL_EXT_10000}, 3033 {"NEC VR4100", Mips::AFL_EXT_4100}, 3034 {"NEC VR4111/VR4181", Mips::AFL_EXT_4111}, 3035 {"NEC VR4120", Mips::AFL_EXT_4120}, 3036 {"NEC VR5400", Mips::AFL_EXT_5400}, 3037 {"NEC VR5500", Mips::AFL_EXT_5500}, 3038 {"RMI Xlr", Mips::AFL_EXT_XLR}, 3039 {"Toshiba R3900", Mips::AFL_EXT_3900} 3040 }; 3041 3042 const EnumEntry<unsigned> ElfMipsASEFlags[] = { 3043 {"DSP", Mips::AFL_ASE_DSP}, 3044 {"DSPR2", Mips::AFL_ASE_DSPR2}, 3045 {"Enhanced VA Scheme", Mips::AFL_ASE_EVA}, 3046 {"MCU", Mips::AFL_ASE_MCU}, 3047 {"MDMX", Mips::AFL_ASE_MDMX}, 3048 {"MIPS-3D", Mips::AFL_ASE_MIPS3D}, 3049 {"MT", Mips::AFL_ASE_MT}, 3050 {"SmartMIPS", Mips::AFL_ASE_SMARTMIPS}, 3051 {"VZ", Mips::AFL_ASE_VIRT}, 3052 {"MSA", Mips::AFL_ASE_MSA}, 3053 {"MIPS16", Mips::AFL_ASE_MIPS16}, 3054 {"microMIPS", Mips::AFL_ASE_MICROMIPS}, 3055 {"XPA", Mips::AFL_ASE_XPA}, 3056 {"CRC", Mips::AFL_ASE_CRC}, 3057 {"GINV", Mips::AFL_ASE_GINV}, 3058 }; 3059 3060 const EnumEntry<unsigned> ElfMipsFpABIType[] = { 3061 {"Hard or soft float", Mips::Val_GNU_MIPS_ABI_FP_ANY}, 3062 {"Hard float (double precision)", Mips::Val_GNU_MIPS_ABI_FP_DOUBLE}, 3063 {"Hard float (single precision)", Mips::Val_GNU_MIPS_ABI_FP_SINGLE}, 3064 {"Soft float", Mips::Val_GNU_MIPS_ABI_FP_SOFT}, 3065 {"Hard float (MIPS32r2 64-bit FPU 12 callee-saved)", 3066 Mips::Val_GNU_MIPS_ABI_FP_OLD_64}, 3067 {"Hard float (32-bit CPU, Any FPU)", Mips::Val_GNU_MIPS_ABI_FP_XX}, 3068 {"Hard float (32-bit CPU, 64-bit FPU)", Mips::Val_GNU_MIPS_ABI_FP_64}, 3069 {"Hard float compat (32-bit CPU, 64-bit FPU)", 3070 Mips::Val_GNU_MIPS_ABI_FP_64A} 3071 }; 3072 3073 static const EnumEntry<unsigned> ElfMipsFlags1[] { 3074 {"ODDSPREG", Mips::AFL_FLAGS1_ODDSPREG}, 3075 }; 3076 3077 static int getMipsRegisterSize(uint8_t Flag) { 3078 switch (Flag) { 3079 case Mips::AFL_REG_NONE: 3080 return 0; 3081 case Mips::AFL_REG_32: 3082 return 32; 3083 case Mips::AFL_REG_64: 3084 return 64; 3085 case Mips::AFL_REG_128: 3086 return 128; 3087 default: 3088 return -1; 3089 } 3090 } 3091 3092 template <class ELFT> 3093 static void printMipsReginfoData(ScopedPrinter &W, 3094 const Elf_Mips_RegInfo<ELFT> &Reginfo) { 3095 W.printHex("GP", Reginfo.ri_gp_value); 3096 W.printHex("General Mask", Reginfo.ri_gprmask); 3097 W.printHex("Co-Proc Mask0", Reginfo.ri_cprmask[0]); 3098 W.printHex("Co-Proc Mask1", Reginfo.ri_cprmask[1]); 3099 W.printHex("Co-Proc Mask2", Reginfo.ri_cprmask[2]); 3100 W.printHex("Co-Proc Mask3", Reginfo.ri_cprmask[3]); 3101 } 3102 3103 template <class ELFT> void ELFDumper<ELFT>::printMipsReginfo() { 3104 const Elf_Shdr *RegInfoSec = findSectionByName(".reginfo"); 3105 if (!RegInfoSec) { 3106 W.startLine() << "There is no .reginfo section in the file.\n"; 3107 return; 3108 } 3109 3110 Expected<ArrayRef<uint8_t>> ContentsOrErr = 3111 Obj.getSectionContents(*RegInfoSec); 3112 if (!ContentsOrErr) { 3113 this->reportUniqueWarning( 3114 "unable to read the content of the .reginfo section (" + 3115 describe(*RegInfoSec) + "): " + toString(ContentsOrErr.takeError())); 3116 return; 3117 } 3118 3119 if (ContentsOrErr->size() < sizeof(Elf_Mips_RegInfo<ELFT>)) { 3120 this->reportUniqueWarning("the .reginfo section has an invalid size (0x" + 3121 Twine::utohexstr(ContentsOrErr->size()) + ")"); 3122 return; 3123 } 3124 3125 DictScope GS(W, "MIPS RegInfo"); 3126 printMipsReginfoData(W, *reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>( 3127 ContentsOrErr->data())); 3128 } 3129 3130 template <class ELFT> 3131 static Expected<const Elf_Mips_Options<ELFT> *> 3132 readMipsOptions(const uint8_t *SecBegin, ArrayRef<uint8_t> &SecData, 3133 bool &IsSupported) { 3134 if (SecData.size() < sizeof(Elf_Mips_Options<ELFT>)) 3135 return createError("the .MIPS.options section has an invalid size (0x" + 3136 Twine::utohexstr(SecData.size()) + ")"); 3137 3138 const Elf_Mips_Options<ELFT> *O = 3139 reinterpret_cast<const Elf_Mips_Options<ELFT> *>(SecData.data()); 3140 const uint8_t Size = O->size; 3141 if (Size > SecData.size()) { 3142 const uint64_t Offset = SecData.data() - SecBegin; 3143 const uint64_t SecSize = Offset + SecData.size(); 3144 return createError("a descriptor of size 0x" + Twine::utohexstr(Size) + 3145 " at offset 0x" + Twine::utohexstr(Offset) + 3146 " goes past the end of the .MIPS.options " 3147 "section of size 0x" + 3148 Twine::utohexstr(SecSize)); 3149 } 3150 3151 IsSupported = O->kind == ODK_REGINFO; 3152 const size_t ExpectedSize = 3153 sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>); 3154 3155 if (IsSupported) 3156 if (Size < ExpectedSize) 3157 return createError( 3158 "a .MIPS.options entry of kind " + 3159 Twine(getElfMipsOptionsOdkType(O->kind)) + 3160 " has an invalid size (0x" + Twine::utohexstr(Size) + 3161 "), the expected size is 0x" + Twine::utohexstr(ExpectedSize)); 3162 3163 SecData = SecData.drop_front(Size); 3164 return O; 3165 } 3166 3167 template <class ELFT> void ELFDumper<ELFT>::printMipsOptions() { 3168 const Elf_Shdr *MipsOpts = findSectionByName(".MIPS.options"); 3169 if (!MipsOpts) { 3170 W.startLine() << "There is no .MIPS.options section in the file.\n"; 3171 return; 3172 } 3173 3174 DictScope GS(W, "MIPS Options"); 3175 3176 ArrayRef<uint8_t> Data = 3177 unwrapOrError(ObjF.getFileName(), Obj.getSectionContents(*MipsOpts)); 3178 const uint8_t *const SecBegin = Data.begin(); 3179 while (!Data.empty()) { 3180 bool IsSupported; 3181 Expected<const Elf_Mips_Options<ELFT> *> OptsOrErr = 3182 readMipsOptions<ELFT>(SecBegin, Data, IsSupported); 3183 if (!OptsOrErr) { 3184 reportUniqueWarning(OptsOrErr.takeError()); 3185 break; 3186 } 3187 3188 unsigned Kind = (*OptsOrErr)->kind; 3189 const char *Type = getElfMipsOptionsOdkType(Kind); 3190 if (!IsSupported) { 3191 W.startLine() << "Unsupported MIPS options tag: " << Type << " (" << Kind 3192 << ")\n"; 3193 continue; 3194 } 3195 3196 DictScope GS(W, Type); 3197 if (Kind == ODK_REGINFO) 3198 printMipsReginfoData(W, (*OptsOrErr)->getRegInfo()); 3199 else 3200 llvm_unreachable("unexpected .MIPS.options section descriptor kind"); 3201 } 3202 } 3203 3204 template <class ELFT> void ELFDumper<ELFT>::printStackMap() const { 3205 const Elf_Shdr *StackMapSection = findSectionByName(".llvm_stackmaps"); 3206 if (!StackMapSection) 3207 return; 3208 3209 auto Warn = [&](Error &&E) { 3210 this->reportUniqueWarning("unable to read the stack map from " + 3211 describe(*StackMapSection) + ": " + 3212 toString(std::move(E))); 3213 }; 3214 3215 Expected<ArrayRef<uint8_t>> ContentOrErr = 3216 Obj.getSectionContents(*StackMapSection); 3217 if (!ContentOrErr) { 3218 Warn(ContentOrErr.takeError()); 3219 return; 3220 } 3221 3222 if (Error E = StackMapParser<ELFT::TargetEndianness>::validateHeader( 3223 *ContentOrErr)) { 3224 Warn(std::move(E)); 3225 return; 3226 } 3227 3228 prettyPrintStackMap(W, StackMapParser<ELFT::TargetEndianness>(*ContentOrErr)); 3229 } 3230 3231 template <class ELFT> 3232 void ELFDumper<ELFT>::printReloc(const Relocation<ELFT> &R, unsigned RelIndex, 3233 const Elf_Shdr &Sec, const Elf_Shdr *SymTab) { 3234 Expected<RelSymbol<ELFT>> Target = getRelocationTarget(R, SymTab); 3235 if (!Target) 3236 reportUniqueWarning("unable to print relocation " + Twine(RelIndex) + 3237 " in " + describe(Sec) + ": " + 3238 toString(Target.takeError())); 3239 else 3240 printRelRelaReloc(R, *Target); 3241 } 3242 3243 static inline void printFields(formatted_raw_ostream &OS, StringRef Str1, 3244 StringRef Str2) { 3245 OS.PadToColumn(2u); 3246 OS << Str1; 3247 OS.PadToColumn(37u); 3248 OS << Str2 << "\n"; 3249 OS.flush(); 3250 } 3251 3252 template <class ELFT> 3253 static std::string getSectionHeadersNumString(const ELFFile<ELFT> &Obj, 3254 StringRef FileName) { 3255 const typename ELFT::Ehdr &ElfHeader = Obj.getHeader(); 3256 if (ElfHeader.e_shnum != 0) 3257 return to_string(ElfHeader.e_shnum); 3258 3259 Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections(); 3260 if (!ArrOrErr) { 3261 // In this case we can ignore an error, because we have already reported a 3262 // warning about the broken section header table earlier. 3263 consumeError(ArrOrErr.takeError()); 3264 return "<?>"; 3265 } 3266 3267 if (ArrOrErr->empty()) 3268 return "0"; 3269 return "0 (" + to_string((*ArrOrErr)[0].sh_size) + ")"; 3270 } 3271 3272 template <class ELFT> 3273 static std::string getSectionHeaderTableIndexString(const ELFFile<ELFT> &Obj, 3274 StringRef FileName) { 3275 const typename ELFT::Ehdr &ElfHeader = Obj.getHeader(); 3276 if (ElfHeader.e_shstrndx != SHN_XINDEX) 3277 return to_string(ElfHeader.e_shstrndx); 3278 3279 Expected<ArrayRef<typename ELFT::Shdr>> ArrOrErr = Obj.sections(); 3280 if (!ArrOrErr) { 3281 // In this case we can ignore an error, because we have already reported a 3282 // warning about the broken section header table earlier. 3283 consumeError(ArrOrErr.takeError()); 3284 return "<?>"; 3285 } 3286 3287 if (ArrOrErr->empty()) 3288 return "65535 (corrupt: out of range)"; 3289 return to_string(ElfHeader.e_shstrndx) + " (" + 3290 to_string((*ArrOrErr)[0].sh_link) + ")"; 3291 } 3292 3293 static const EnumEntry<unsigned> *getObjectFileEnumEntry(unsigned Type) { 3294 auto It = llvm::find_if(ElfObjectFileType, [&](const EnumEntry<unsigned> &E) { 3295 return E.Value == Type; 3296 }); 3297 if (It != makeArrayRef(ElfObjectFileType).end()) 3298 return It; 3299 return nullptr; 3300 } 3301 3302 template <class ELFT> 3303 void GNUELFDumper<ELFT>::printFileSummary(StringRef FileStr, ObjectFile &Obj, 3304 ArrayRef<std::string> InputFilenames, 3305 const Archive *A) { 3306 if (InputFilenames.size() > 1 || A) { 3307 this->W.startLine() << "\n"; 3308 this->W.printString("File", FileStr); 3309 } 3310 } 3311 3312 template <class ELFT> void GNUELFDumper<ELFT>::printFileHeaders() { 3313 const Elf_Ehdr &e = this->Obj.getHeader(); 3314 OS << "ELF Header:\n"; 3315 OS << " Magic: "; 3316 std::string Str; 3317 for (int i = 0; i < ELF::EI_NIDENT; i++) 3318 OS << format(" %02x", static_cast<int>(e.e_ident[i])); 3319 OS << "\n"; 3320 Str = enumToString(e.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass)); 3321 printFields(OS, "Class:", Str); 3322 Str = enumToString(e.e_ident[ELF::EI_DATA], makeArrayRef(ElfDataEncoding)); 3323 printFields(OS, "Data:", Str); 3324 OS.PadToColumn(2u); 3325 OS << "Version:"; 3326 OS.PadToColumn(37u); 3327 OS << utohexstr(e.e_ident[ELF::EI_VERSION]); 3328 if (e.e_version == ELF::EV_CURRENT) 3329 OS << " (current)"; 3330 OS << "\n"; 3331 Str = enumToString(e.e_ident[ELF::EI_OSABI], makeArrayRef(ElfOSABI)); 3332 printFields(OS, "OS/ABI:", Str); 3333 printFields(OS, 3334 "ABI Version:", std::to_string(e.e_ident[ELF::EI_ABIVERSION])); 3335 3336 if (const EnumEntry<unsigned> *E = getObjectFileEnumEntry(e.e_type)) { 3337 Str = E->AltName.str(); 3338 } else { 3339 if (e.e_type >= ET_LOPROC) 3340 Str = "Processor Specific: (" + utohexstr(e.e_type, /*LowerCase=*/true) + ")"; 3341 else if (e.e_type >= ET_LOOS) 3342 Str = "OS Specific: (" + utohexstr(e.e_type, /*LowerCase=*/true) + ")"; 3343 else 3344 Str = "<unknown>: " + utohexstr(e.e_type, /*LowerCase=*/true); 3345 } 3346 printFields(OS, "Type:", Str); 3347 3348 Str = enumToString(e.e_machine, makeArrayRef(ElfMachineType)); 3349 printFields(OS, "Machine:", Str); 3350 Str = "0x" + utohexstr(e.e_version); 3351 printFields(OS, "Version:", Str); 3352 Str = "0x" + utohexstr(e.e_entry); 3353 printFields(OS, "Entry point address:", Str); 3354 Str = to_string(e.e_phoff) + " (bytes into file)"; 3355 printFields(OS, "Start of program headers:", Str); 3356 Str = to_string(e.e_shoff) + " (bytes into file)"; 3357 printFields(OS, "Start of section headers:", Str); 3358 std::string ElfFlags; 3359 if (e.e_machine == EM_MIPS) 3360 ElfFlags = 3361 printFlags(e.e_flags, makeArrayRef(ElfHeaderMipsFlags), 3362 unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI), 3363 unsigned(ELF::EF_MIPS_MACH)); 3364 else if (e.e_machine == EM_RISCV) 3365 ElfFlags = printFlags(e.e_flags, makeArrayRef(ElfHeaderRISCVFlags)); 3366 else if (e.e_machine == EM_AVR) 3367 ElfFlags = printFlags(e.e_flags, makeArrayRef(ElfHeaderAVRFlags), 3368 unsigned(ELF::EF_AVR_ARCH_MASK)); 3369 else if (e.e_machine == EM_LOONGARCH) 3370 ElfFlags = printFlags(e.e_flags, makeArrayRef(ElfHeaderLoongArchFlags), 3371 unsigned(ELF::EF_LOONGARCH_BASE_ABI_MASK)); 3372 Str = "0x" + utohexstr(e.e_flags); 3373 if (!ElfFlags.empty()) 3374 Str = Str + ", " + ElfFlags; 3375 printFields(OS, "Flags:", Str); 3376 Str = to_string(e.e_ehsize) + " (bytes)"; 3377 printFields(OS, "Size of this header:", Str); 3378 Str = to_string(e.e_phentsize) + " (bytes)"; 3379 printFields(OS, "Size of program headers:", Str); 3380 Str = to_string(e.e_phnum); 3381 printFields(OS, "Number of program headers:", Str); 3382 Str = to_string(e.e_shentsize) + " (bytes)"; 3383 printFields(OS, "Size of section headers:", Str); 3384 Str = getSectionHeadersNumString(this->Obj, this->FileName); 3385 printFields(OS, "Number of section headers:", Str); 3386 Str = getSectionHeaderTableIndexString(this->Obj, this->FileName); 3387 printFields(OS, "Section header string table index:", Str); 3388 } 3389 3390 template <class ELFT> std::vector<GroupSection> ELFDumper<ELFT>::getGroups() { 3391 auto GetSignature = [&](const Elf_Sym &Sym, unsigned SymNdx, 3392 const Elf_Shdr &Symtab) -> StringRef { 3393 Expected<StringRef> StrTableOrErr = Obj.getStringTableForSymtab(Symtab); 3394 if (!StrTableOrErr) { 3395 reportUniqueWarning("unable to get the string table for " + 3396 describe(Symtab) + ": " + 3397 toString(StrTableOrErr.takeError())); 3398 return "<?>"; 3399 } 3400 3401 StringRef Strings = *StrTableOrErr; 3402 if (Sym.st_name >= Strings.size()) { 3403 reportUniqueWarning("unable to get the name of the symbol with index " + 3404 Twine(SymNdx) + ": st_name (0x" + 3405 Twine::utohexstr(Sym.st_name) + 3406 ") is past the end of the string table of size 0x" + 3407 Twine::utohexstr(Strings.size())); 3408 return "<?>"; 3409 } 3410 3411 return StrTableOrErr->data() + Sym.st_name; 3412 }; 3413 3414 std::vector<GroupSection> Ret; 3415 uint64_t I = 0; 3416 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) { 3417 ++I; 3418 if (Sec.sh_type != ELF::SHT_GROUP) 3419 continue; 3420 3421 StringRef Signature = "<?>"; 3422 if (Expected<const Elf_Shdr *> SymtabOrErr = Obj.getSection(Sec.sh_link)) { 3423 if (Expected<const Elf_Sym *> SymOrErr = 3424 Obj.template getEntry<Elf_Sym>(**SymtabOrErr, Sec.sh_info)) 3425 Signature = GetSignature(**SymOrErr, Sec.sh_info, **SymtabOrErr); 3426 else 3427 reportUniqueWarning("unable to get the signature symbol for " + 3428 describe(Sec) + ": " + 3429 toString(SymOrErr.takeError())); 3430 } else { 3431 reportUniqueWarning("unable to get the symbol table for " + 3432 describe(Sec) + ": " + 3433 toString(SymtabOrErr.takeError())); 3434 } 3435 3436 ArrayRef<Elf_Word> Data; 3437 if (Expected<ArrayRef<Elf_Word>> ContentsOrErr = 3438 Obj.template getSectionContentsAsArray<Elf_Word>(Sec)) { 3439 if (ContentsOrErr->empty()) 3440 reportUniqueWarning("unable to read the section group flag from the " + 3441 describe(Sec) + ": the section is empty"); 3442 else 3443 Data = *ContentsOrErr; 3444 } else { 3445 reportUniqueWarning("unable to get the content of the " + describe(Sec) + 3446 ": " + toString(ContentsOrErr.takeError())); 3447 } 3448 3449 Ret.push_back({getPrintableSectionName(Sec), 3450 maybeDemangle(Signature), 3451 Sec.sh_name, 3452 I - 1, 3453 Sec.sh_link, 3454 Sec.sh_info, 3455 Data.empty() ? Elf_Word(0) : Data[0], 3456 {}}); 3457 3458 if (Data.empty()) 3459 continue; 3460 3461 std::vector<GroupMember> &GM = Ret.back().Members; 3462 for (uint32_t Ndx : Data.slice(1)) { 3463 if (Expected<const Elf_Shdr *> SecOrErr = Obj.getSection(Ndx)) { 3464 GM.push_back({getPrintableSectionName(**SecOrErr), Ndx}); 3465 } else { 3466 reportUniqueWarning("unable to get the section with index " + 3467 Twine(Ndx) + " when dumping the " + describe(Sec) + 3468 ": " + toString(SecOrErr.takeError())); 3469 GM.push_back({"<?>", Ndx}); 3470 } 3471 } 3472 } 3473 return Ret; 3474 } 3475 3476 static DenseMap<uint64_t, const GroupSection *> 3477 mapSectionsToGroups(ArrayRef<GroupSection> Groups) { 3478 DenseMap<uint64_t, const GroupSection *> Ret; 3479 for (const GroupSection &G : Groups) 3480 for (const GroupMember &GM : G.Members) 3481 Ret.insert({GM.Index, &G}); 3482 return Ret; 3483 } 3484 3485 template <class ELFT> void GNUELFDumper<ELFT>::printGroupSections() { 3486 std::vector<GroupSection> V = this->getGroups(); 3487 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V); 3488 for (const GroupSection &G : V) { 3489 OS << "\n" 3490 << getGroupType(G.Type) << " group section [" 3491 << format_decimal(G.Index, 5) << "] `" << G.Name << "' [" << G.Signature 3492 << "] contains " << G.Members.size() << " sections:\n" 3493 << " [Index] Name\n"; 3494 for (const GroupMember &GM : G.Members) { 3495 const GroupSection *MainGroup = Map[GM.Index]; 3496 if (MainGroup != &G) 3497 this->reportUniqueWarning( 3498 "section with index " + Twine(GM.Index) + 3499 ", included in the group section with index " + 3500 Twine(MainGroup->Index) + 3501 ", was also found in the group section with index " + 3502 Twine(G.Index)); 3503 OS << " [" << format_decimal(GM.Index, 5) << "] " << GM.Name << "\n"; 3504 } 3505 } 3506 3507 if (V.empty()) 3508 OS << "There are no section groups in this file.\n"; 3509 } 3510 3511 template <class ELFT> 3512 void GNUELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) { 3513 OS << to_string(format_hex_no_prefix(R, ELFT::Is64Bits ? 16 : 8)) << "\n"; 3514 } 3515 3516 template <class ELFT> 3517 void GNUELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R, 3518 const RelSymbol<ELFT> &RelSym) { 3519 // First two fields are bit width dependent. The rest of them are fixed width. 3520 unsigned Bias = ELFT::Is64Bits ? 8 : 0; 3521 Field Fields[5] = {0, 10 + Bias, 19 + 2 * Bias, 42 + 2 * Bias, 53 + 2 * Bias}; 3522 unsigned Width = ELFT::Is64Bits ? 16 : 8; 3523 3524 Fields[0].Str = to_string(format_hex_no_prefix(R.Offset, Width)); 3525 Fields[1].Str = to_string(format_hex_no_prefix(R.Info, Width)); 3526 3527 SmallString<32> RelocName; 3528 this->Obj.getRelocationTypeName(R.Type, RelocName); 3529 Fields[2].Str = RelocName.c_str(); 3530 3531 if (RelSym.Sym) 3532 Fields[3].Str = 3533 to_string(format_hex_no_prefix(RelSym.Sym->getValue(), Width)); 3534 3535 Fields[4].Str = std::string(RelSym.Name); 3536 for (const Field &F : Fields) 3537 printField(F); 3538 3539 std::string Addend; 3540 if (Optional<int64_t> A = R.Addend) { 3541 int64_t RelAddend = *A; 3542 if (!RelSym.Name.empty()) { 3543 if (RelAddend < 0) { 3544 Addend = " - "; 3545 RelAddend = std::abs(RelAddend); 3546 } else { 3547 Addend = " + "; 3548 } 3549 } 3550 Addend += utohexstr(RelAddend, /*LowerCase=*/true); 3551 } 3552 OS << Addend << "\n"; 3553 } 3554 3555 template <class ELFT> 3556 static void printRelocHeaderFields(formatted_raw_ostream &OS, unsigned SType) { 3557 bool IsRela = SType == ELF::SHT_RELA || SType == ELF::SHT_ANDROID_RELA; 3558 bool IsRelr = SType == ELF::SHT_RELR || SType == ELF::SHT_ANDROID_RELR; 3559 if (ELFT::Is64Bits) 3560 OS << " "; 3561 else 3562 OS << " "; 3563 if (IsRelr && opts::RawRelr) 3564 OS << "Data "; 3565 else 3566 OS << "Offset"; 3567 if (ELFT::Is64Bits) 3568 OS << " Info Type" 3569 << " Symbol's Value Symbol's Name"; 3570 else 3571 OS << " Info Type Sym. Value Symbol's Name"; 3572 if (IsRela) 3573 OS << " + Addend"; 3574 OS << "\n"; 3575 } 3576 3577 template <class ELFT> 3578 void GNUELFDumper<ELFT>::printDynamicRelocHeader(unsigned Type, StringRef Name, 3579 const DynRegionInfo &Reg) { 3580 uint64_t Offset = Reg.Addr - this->Obj.base(); 3581 OS << "\n'" << Name.str().c_str() << "' relocation section at offset 0x" 3582 << utohexstr(Offset, /*LowerCase=*/true) << " contains " << Reg.Size << " bytes:\n"; 3583 printRelocHeaderFields<ELFT>(OS, Type); 3584 } 3585 3586 template <class ELFT> 3587 static bool isRelocationSec(const typename ELFT::Shdr &Sec) { 3588 return Sec.sh_type == ELF::SHT_REL || Sec.sh_type == ELF::SHT_RELA || 3589 Sec.sh_type == ELF::SHT_RELR || Sec.sh_type == ELF::SHT_ANDROID_REL || 3590 Sec.sh_type == ELF::SHT_ANDROID_RELA || 3591 Sec.sh_type == ELF::SHT_ANDROID_RELR; 3592 } 3593 3594 template <class ELFT> void GNUELFDumper<ELFT>::printRelocations() { 3595 auto GetEntriesNum = [&](const Elf_Shdr &Sec) -> Expected<size_t> { 3596 // Android's packed relocation section needs to be unpacked first 3597 // to get the actual number of entries. 3598 if (Sec.sh_type == ELF::SHT_ANDROID_REL || 3599 Sec.sh_type == ELF::SHT_ANDROID_RELA) { 3600 Expected<std::vector<typename ELFT::Rela>> RelasOrErr = 3601 this->Obj.android_relas(Sec); 3602 if (!RelasOrErr) 3603 return RelasOrErr.takeError(); 3604 return RelasOrErr->size(); 3605 } 3606 3607 if (!opts::RawRelr && (Sec.sh_type == ELF::SHT_RELR || 3608 Sec.sh_type == ELF::SHT_ANDROID_RELR)) { 3609 Expected<Elf_Relr_Range> RelrsOrErr = this->Obj.relrs(Sec); 3610 if (!RelrsOrErr) 3611 return RelrsOrErr.takeError(); 3612 return this->Obj.decode_relrs(*RelrsOrErr).size(); 3613 } 3614 3615 return Sec.getEntityCount(); 3616 }; 3617 3618 bool HasRelocSections = false; 3619 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) { 3620 if (!isRelocationSec<ELFT>(Sec)) 3621 continue; 3622 HasRelocSections = true; 3623 3624 std::string EntriesNum = "<?>"; 3625 if (Expected<size_t> NumOrErr = GetEntriesNum(Sec)) 3626 EntriesNum = std::to_string(*NumOrErr); 3627 else 3628 this->reportUniqueWarning("unable to get the number of relocations in " + 3629 this->describe(Sec) + ": " + 3630 toString(NumOrErr.takeError())); 3631 3632 uintX_t Offset = Sec.sh_offset; 3633 StringRef Name = this->getPrintableSectionName(Sec); 3634 OS << "\nRelocation section '" << Name << "' at offset 0x" 3635 << utohexstr(Offset, /*LowerCase=*/true) << " contains " << EntriesNum 3636 << " entries:\n"; 3637 printRelocHeaderFields<ELFT>(OS, Sec.sh_type); 3638 this->printRelocationsHelper(Sec); 3639 } 3640 if (!HasRelocSections) 3641 OS << "\nThere are no relocations in this file.\n"; 3642 } 3643 3644 // Print the offset of a particular section from anyone of the ranges: 3645 // [SHT_LOOS, SHT_HIOS], [SHT_LOPROC, SHT_HIPROC], [SHT_LOUSER, SHT_HIUSER]. 3646 // If 'Type' does not fall within any of those ranges, then a string is 3647 // returned as '<unknown>' followed by the type value. 3648 static std::string getSectionTypeOffsetString(unsigned Type) { 3649 if (Type >= SHT_LOOS && Type <= SHT_HIOS) 3650 return "LOOS+0x" + utohexstr(Type - SHT_LOOS); 3651 else if (Type >= SHT_LOPROC && Type <= SHT_HIPROC) 3652 return "LOPROC+0x" + utohexstr(Type - SHT_LOPROC); 3653 else if (Type >= SHT_LOUSER && Type <= SHT_HIUSER) 3654 return "LOUSER+0x" + utohexstr(Type - SHT_LOUSER); 3655 return "0x" + utohexstr(Type) + ": <unknown>"; 3656 } 3657 3658 static std::string getSectionTypeString(unsigned Machine, unsigned Type) { 3659 StringRef Name = getELFSectionTypeName(Machine, Type); 3660 3661 // Handle SHT_GNU_* type names. 3662 if (Name.consume_front("SHT_GNU_")) { 3663 if (Name == "HASH") 3664 return "GNU_HASH"; 3665 // E.g. SHT_GNU_verneed -> VERNEED. 3666 return Name.upper(); 3667 } 3668 3669 if (Name == "SHT_SYMTAB_SHNDX") 3670 return "SYMTAB SECTION INDICES"; 3671 3672 if (Name.consume_front("SHT_")) 3673 return Name.str(); 3674 return getSectionTypeOffsetString(Type); 3675 } 3676 3677 static void printSectionDescription(formatted_raw_ostream &OS, 3678 unsigned EMachine) { 3679 OS << "Key to Flags:\n"; 3680 OS << " W (write), A (alloc), X (execute), M (merge), S (strings), I " 3681 "(info),\n"; 3682 OS << " L (link order), O (extra OS processing required), G (group), T " 3683 "(TLS),\n"; 3684 OS << " C (compressed), x (unknown), o (OS specific), E (exclude),\n"; 3685 OS << " R (retain)"; 3686 3687 if (EMachine == EM_X86_64) 3688 OS << ", l (large)"; 3689 else if (EMachine == EM_ARM) 3690 OS << ", y (purecode)"; 3691 3692 OS << ", p (processor specific)\n"; 3693 } 3694 3695 template <class ELFT> void GNUELFDumper<ELFT>::printSectionHeaders() { 3696 unsigned Bias = ELFT::Is64Bits ? 0 : 8; 3697 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections()); 3698 OS << "There are " << to_string(Sections.size()) 3699 << " section headers, starting at offset " 3700 << "0x" << utohexstr(this->Obj.getHeader().e_shoff, /*LowerCase=*/true) << ":\n\n"; 3701 OS << "Section Headers:\n"; 3702 Field Fields[11] = { 3703 {"[Nr]", 2}, {"Name", 7}, {"Type", 25}, 3704 {"Address", 41}, {"Off", 58 - Bias}, {"Size", 65 - Bias}, 3705 {"ES", 72 - Bias}, {"Flg", 75 - Bias}, {"Lk", 79 - Bias}, 3706 {"Inf", 82 - Bias}, {"Al", 86 - Bias}}; 3707 for (const Field &F : Fields) 3708 printField(F); 3709 OS << "\n"; 3710 3711 StringRef SecStrTable; 3712 if (Expected<StringRef> SecStrTableOrErr = 3713 this->Obj.getSectionStringTable(Sections, this->WarningHandler)) 3714 SecStrTable = *SecStrTableOrErr; 3715 else 3716 this->reportUniqueWarning(SecStrTableOrErr.takeError()); 3717 3718 size_t SectionIndex = 0; 3719 for (const Elf_Shdr &Sec : Sections) { 3720 Fields[0].Str = to_string(SectionIndex); 3721 if (SecStrTable.empty()) 3722 Fields[1].Str = "<no-strings>"; 3723 else 3724 Fields[1].Str = std::string(unwrapOrError<StringRef>( 3725 this->FileName, this->Obj.getSectionName(Sec, SecStrTable))); 3726 Fields[2].Str = 3727 getSectionTypeString(this->Obj.getHeader().e_machine, Sec.sh_type); 3728 Fields[3].Str = 3729 to_string(format_hex_no_prefix(Sec.sh_addr, ELFT::Is64Bits ? 16 : 8)); 3730 Fields[4].Str = to_string(format_hex_no_prefix(Sec.sh_offset, 6)); 3731 Fields[5].Str = to_string(format_hex_no_prefix(Sec.sh_size, 6)); 3732 Fields[6].Str = to_string(format_hex_no_prefix(Sec.sh_entsize, 2)); 3733 Fields[7].Str = getGNUFlags(this->Obj.getHeader().e_ident[ELF::EI_OSABI], 3734 this->Obj.getHeader().e_machine, Sec.sh_flags); 3735 Fields[8].Str = to_string(Sec.sh_link); 3736 Fields[9].Str = to_string(Sec.sh_info); 3737 Fields[10].Str = to_string(Sec.sh_addralign); 3738 3739 OS.PadToColumn(Fields[0].Column); 3740 OS << "[" << right_justify(Fields[0].Str, 2) << "]"; 3741 for (int i = 1; i < 7; i++) 3742 printField(Fields[i]); 3743 OS.PadToColumn(Fields[7].Column); 3744 OS << right_justify(Fields[7].Str, 3); 3745 OS.PadToColumn(Fields[8].Column); 3746 OS << right_justify(Fields[8].Str, 2); 3747 OS.PadToColumn(Fields[9].Column); 3748 OS << right_justify(Fields[9].Str, 3); 3749 OS.PadToColumn(Fields[10].Column); 3750 OS << right_justify(Fields[10].Str, 2); 3751 OS << "\n"; 3752 ++SectionIndex; 3753 } 3754 printSectionDescription(OS, this->Obj.getHeader().e_machine); 3755 } 3756 3757 template <class ELFT> 3758 void GNUELFDumper<ELFT>::printSymtabMessage(const Elf_Shdr *Symtab, 3759 size_t Entries, 3760 bool NonVisibilityBitsUsed) const { 3761 StringRef Name; 3762 if (Symtab) 3763 Name = this->getPrintableSectionName(*Symtab); 3764 if (!Name.empty()) 3765 OS << "\nSymbol table '" << Name << "'"; 3766 else 3767 OS << "\nSymbol table for image"; 3768 OS << " contains " << Entries << " entries:\n"; 3769 3770 if (ELFT::Is64Bits) 3771 OS << " Num: Value Size Type Bind Vis"; 3772 else 3773 OS << " Num: Value Size Type Bind Vis"; 3774 3775 if (NonVisibilityBitsUsed) 3776 OS << " "; 3777 OS << " Ndx Name\n"; 3778 } 3779 3780 template <class ELFT> 3781 std::string 3782 GNUELFDumper<ELFT>::getSymbolSectionNdx(const Elf_Sym &Symbol, 3783 unsigned SymIndex, 3784 DataRegion<Elf_Word> ShndxTable) const { 3785 unsigned SectionIndex = Symbol.st_shndx; 3786 switch (SectionIndex) { 3787 case ELF::SHN_UNDEF: 3788 return "UND"; 3789 case ELF::SHN_ABS: 3790 return "ABS"; 3791 case ELF::SHN_COMMON: 3792 return "COM"; 3793 case ELF::SHN_XINDEX: { 3794 Expected<uint32_t> IndexOrErr = 3795 object::getExtendedSymbolTableIndex<ELFT>(Symbol, SymIndex, ShndxTable); 3796 if (!IndexOrErr) { 3797 assert(Symbol.st_shndx == SHN_XINDEX && 3798 "getExtendedSymbolTableIndex should only fail due to an invalid " 3799 "SHT_SYMTAB_SHNDX table/reference"); 3800 this->reportUniqueWarning(IndexOrErr.takeError()); 3801 return "RSV[0xffff]"; 3802 } 3803 return to_string(format_decimal(*IndexOrErr, 3)); 3804 } 3805 default: 3806 // Find if: 3807 // Processor specific 3808 if (SectionIndex >= ELF::SHN_LOPROC && SectionIndex <= ELF::SHN_HIPROC) 3809 return std::string("PRC[0x") + 3810 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]"; 3811 // OS specific 3812 if (SectionIndex >= ELF::SHN_LOOS && SectionIndex <= ELF::SHN_HIOS) 3813 return std::string("OS[0x") + 3814 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]"; 3815 // Architecture reserved: 3816 if (SectionIndex >= ELF::SHN_LORESERVE && 3817 SectionIndex <= ELF::SHN_HIRESERVE) 3818 return std::string("RSV[0x") + 3819 to_string(format_hex_no_prefix(SectionIndex, 4)) + "]"; 3820 // A normal section with an index 3821 return to_string(format_decimal(SectionIndex, 3)); 3822 } 3823 } 3824 3825 template <class ELFT> 3826 void GNUELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex, 3827 DataRegion<Elf_Word> ShndxTable, 3828 Optional<StringRef> StrTable, 3829 bool IsDynamic, 3830 bool NonVisibilityBitsUsed) const { 3831 unsigned Bias = ELFT::Is64Bits ? 8 : 0; 3832 Field Fields[8] = {0, 8, 17 + Bias, 23 + Bias, 3833 31 + Bias, 38 + Bias, 48 + Bias, 51 + Bias}; 3834 Fields[0].Str = to_string(format_decimal(SymIndex, 6)) + ":"; 3835 Fields[1].Str = 3836 to_string(format_hex_no_prefix(Symbol.st_value, ELFT::Is64Bits ? 16 : 8)); 3837 Fields[2].Str = to_string(format_decimal(Symbol.st_size, 5)); 3838 3839 unsigned char SymbolType = Symbol.getType(); 3840 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU && 3841 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS) 3842 Fields[3].Str = enumToString(SymbolType, makeArrayRef(AMDGPUSymbolTypes)); 3843 else 3844 Fields[3].Str = enumToString(SymbolType, makeArrayRef(ElfSymbolTypes)); 3845 3846 Fields[4].Str = 3847 enumToString(Symbol.getBinding(), makeArrayRef(ElfSymbolBindings)); 3848 Fields[5].Str = 3849 enumToString(Symbol.getVisibility(), makeArrayRef(ElfSymbolVisibilities)); 3850 3851 if (Symbol.st_other & ~0x3) { 3852 if (this->Obj.getHeader().e_machine == ELF::EM_AARCH64) { 3853 uint8_t Other = Symbol.st_other & ~0x3; 3854 if (Other & STO_AARCH64_VARIANT_PCS) { 3855 Other &= ~STO_AARCH64_VARIANT_PCS; 3856 Fields[5].Str += " [VARIANT_PCS"; 3857 if (Other != 0) 3858 Fields[5].Str.append(" | " + utohexstr(Other, /*LowerCase=*/true)); 3859 Fields[5].Str.append("]"); 3860 } 3861 } else if (this->Obj.getHeader().e_machine == ELF::EM_RISCV) { 3862 uint8_t Other = Symbol.st_other & ~0x3; 3863 if (Other & STO_RISCV_VARIANT_CC) { 3864 Other &= ~STO_RISCV_VARIANT_CC; 3865 Fields[5].Str += " [VARIANT_CC"; 3866 if (Other != 0) 3867 Fields[5].Str.append(" | " + utohexstr(Other, /*LowerCase=*/true)); 3868 Fields[5].Str.append("]"); 3869 } 3870 } else { 3871 Fields[5].Str += 3872 " [<other: " + to_string(format_hex(Symbol.st_other, 2)) + ">]"; 3873 } 3874 } 3875 3876 Fields[6].Column += NonVisibilityBitsUsed ? 13 : 0; 3877 Fields[6].Str = getSymbolSectionNdx(Symbol, SymIndex, ShndxTable); 3878 3879 Fields[7].Str = this->getFullSymbolName(Symbol, SymIndex, ShndxTable, 3880 StrTable, IsDynamic); 3881 for (const Field &Entry : Fields) 3882 printField(Entry); 3883 OS << "\n"; 3884 } 3885 3886 template <class ELFT> 3887 void GNUELFDumper<ELFT>::printHashedSymbol(const Elf_Sym *Symbol, 3888 unsigned SymIndex, 3889 DataRegion<Elf_Word> ShndxTable, 3890 StringRef StrTable, 3891 uint32_t Bucket) { 3892 unsigned Bias = ELFT::Is64Bits ? 8 : 0; 3893 Field Fields[9] = {0, 6, 11, 20 + Bias, 25 + Bias, 3894 34 + Bias, 41 + Bias, 49 + Bias, 53 + Bias}; 3895 Fields[0].Str = to_string(format_decimal(SymIndex, 5)); 3896 Fields[1].Str = to_string(format_decimal(Bucket, 3)) + ":"; 3897 3898 Fields[2].Str = to_string( 3899 format_hex_no_prefix(Symbol->st_value, ELFT::Is64Bits ? 16 : 8)); 3900 Fields[3].Str = to_string(format_decimal(Symbol->st_size, 5)); 3901 3902 unsigned char SymbolType = Symbol->getType(); 3903 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU && 3904 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS) 3905 Fields[4].Str = enumToString(SymbolType, makeArrayRef(AMDGPUSymbolTypes)); 3906 else 3907 Fields[4].Str = enumToString(SymbolType, makeArrayRef(ElfSymbolTypes)); 3908 3909 Fields[5].Str = 3910 enumToString(Symbol->getBinding(), makeArrayRef(ElfSymbolBindings)); 3911 Fields[6].Str = enumToString(Symbol->getVisibility(), 3912 makeArrayRef(ElfSymbolVisibilities)); 3913 Fields[7].Str = getSymbolSectionNdx(*Symbol, SymIndex, ShndxTable); 3914 Fields[8].Str = 3915 this->getFullSymbolName(*Symbol, SymIndex, ShndxTable, StrTable, true); 3916 3917 for (const Field &Entry : Fields) 3918 printField(Entry); 3919 OS << "\n"; 3920 } 3921 3922 template <class ELFT> 3923 void GNUELFDumper<ELFT>::printSymbols(bool PrintSymbols, 3924 bool PrintDynamicSymbols) { 3925 if (!PrintSymbols && !PrintDynamicSymbols) 3926 return; 3927 // GNU readelf prints both the .dynsym and .symtab with --symbols. 3928 this->printSymbolsHelper(true); 3929 if (PrintSymbols) 3930 this->printSymbolsHelper(false); 3931 } 3932 3933 template <class ELFT> 3934 void GNUELFDumper<ELFT>::printHashTableSymbols(const Elf_Hash &SysVHash) { 3935 if (this->DynamicStringTable.empty()) 3936 return; 3937 3938 if (ELFT::Is64Bits) 3939 OS << " Num Buc: Value Size Type Bind Vis Ndx Name"; 3940 else 3941 OS << " Num Buc: Value Size Type Bind Vis Ndx Name"; 3942 OS << "\n"; 3943 3944 Elf_Sym_Range DynSyms = this->dynamic_symbols(); 3945 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0]; 3946 if (!FirstSym) { 3947 this->reportUniqueWarning( 3948 Twine("unable to print symbols for the .hash table: the " 3949 "dynamic symbol table ") + 3950 (this->DynSymRegion ? "is empty" : "was not found")); 3951 return; 3952 } 3953 3954 DataRegion<Elf_Word> ShndxTable( 3955 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end()); 3956 auto Buckets = SysVHash.buckets(); 3957 auto Chains = SysVHash.chains(); 3958 for (uint32_t Buc = 0; Buc < SysVHash.nbucket; Buc++) { 3959 if (Buckets[Buc] == ELF::STN_UNDEF) 3960 continue; 3961 BitVector Visited(SysVHash.nchain); 3962 for (uint32_t Ch = Buckets[Buc]; Ch < SysVHash.nchain; Ch = Chains[Ch]) { 3963 if (Ch == ELF::STN_UNDEF) 3964 break; 3965 3966 if (Visited[Ch]) { 3967 this->reportUniqueWarning(".hash section is invalid: bucket " + 3968 Twine(Ch) + 3969 ": a cycle was detected in the linked chain"); 3970 break; 3971 } 3972 3973 printHashedSymbol(FirstSym + Ch, Ch, ShndxTable, this->DynamicStringTable, 3974 Buc); 3975 Visited[Ch] = true; 3976 } 3977 } 3978 } 3979 3980 template <class ELFT> 3981 void GNUELFDumper<ELFT>::printGnuHashTableSymbols(const Elf_GnuHash &GnuHash) { 3982 if (this->DynamicStringTable.empty()) 3983 return; 3984 3985 Elf_Sym_Range DynSyms = this->dynamic_symbols(); 3986 const Elf_Sym *FirstSym = DynSyms.empty() ? nullptr : &DynSyms[0]; 3987 if (!FirstSym) { 3988 this->reportUniqueWarning( 3989 Twine("unable to print symbols for the .gnu.hash table: the " 3990 "dynamic symbol table ") + 3991 (this->DynSymRegion ? "is empty" : "was not found")); 3992 return; 3993 } 3994 3995 auto GetSymbol = [&](uint64_t SymIndex, 3996 uint64_t SymsTotal) -> const Elf_Sym * { 3997 if (SymIndex >= SymsTotal) { 3998 this->reportUniqueWarning( 3999 "unable to print hashed symbol with index " + Twine(SymIndex) + 4000 ", which is greater than or equal to the number of dynamic symbols " 4001 "(" + 4002 Twine::utohexstr(SymsTotal) + ")"); 4003 return nullptr; 4004 } 4005 return FirstSym + SymIndex; 4006 }; 4007 4008 Expected<ArrayRef<Elf_Word>> ValuesOrErr = 4009 getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHash); 4010 ArrayRef<Elf_Word> Values; 4011 if (!ValuesOrErr) 4012 this->reportUniqueWarning("unable to get hash values for the SHT_GNU_HASH " 4013 "section: " + 4014 toString(ValuesOrErr.takeError())); 4015 else 4016 Values = *ValuesOrErr; 4017 4018 DataRegion<Elf_Word> ShndxTable( 4019 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end()); 4020 ArrayRef<Elf_Word> Buckets = GnuHash.buckets(); 4021 for (uint32_t Buc = 0; Buc < GnuHash.nbuckets; Buc++) { 4022 if (Buckets[Buc] == ELF::STN_UNDEF) 4023 continue; 4024 uint32_t Index = Buckets[Buc]; 4025 // Print whole chain. 4026 while (true) { 4027 uint32_t SymIndex = Index++; 4028 if (const Elf_Sym *Sym = GetSymbol(SymIndex, DynSyms.size())) 4029 printHashedSymbol(Sym, SymIndex, ShndxTable, this->DynamicStringTable, 4030 Buc); 4031 else 4032 break; 4033 4034 if (SymIndex < GnuHash.symndx) { 4035 this->reportUniqueWarning( 4036 "unable to read the hash value for symbol with index " + 4037 Twine(SymIndex) + 4038 ", which is less than the index of the first hashed symbol (" + 4039 Twine(GnuHash.symndx) + ")"); 4040 break; 4041 } 4042 4043 // Chain ends at symbol with stopper bit. 4044 if ((Values[SymIndex - GnuHash.symndx] & 1) == 1) 4045 break; 4046 } 4047 } 4048 } 4049 4050 template <class ELFT> void GNUELFDumper<ELFT>::printHashSymbols() { 4051 if (this->HashTable) { 4052 OS << "\n Symbol table of .hash for image:\n"; 4053 if (Error E = checkHashTable<ELFT>(*this, this->HashTable)) 4054 this->reportUniqueWarning(std::move(E)); 4055 else 4056 printHashTableSymbols(*this->HashTable); 4057 } 4058 4059 // Try printing the .gnu.hash table. 4060 if (this->GnuHashTable) { 4061 OS << "\n Symbol table of .gnu.hash for image:\n"; 4062 if (ELFT::Is64Bits) 4063 OS << " Num Buc: Value Size Type Bind Vis Ndx Name"; 4064 else 4065 OS << " Num Buc: Value Size Type Bind Vis Ndx Name"; 4066 OS << "\n"; 4067 4068 if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable)) 4069 this->reportUniqueWarning(std::move(E)); 4070 else 4071 printGnuHashTableSymbols(*this->GnuHashTable); 4072 } 4073 } 4074 4075 template <class ELFT> void GNUELFDumper<ELFT>::printSectionDetails() { 4076 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections()); 4077 OS << "There are " << to_string(Sections.size()) 4078 << " section headers, starting at offset " 4079 << "0x" << utohexstr(this->Obj.getHeader().e_shoff, /*LowerCase=*/true) << ":\n\n"; 4080 4081 OS << "Section Headers:\n"; 4082 4083 auto PrintFields = [&](ArrayRef<Field> V) { 4084 for (const Field &F : V) 4085 printField(F); 4086 OS << "\n"; 4087 }; 4088 4089 PrintFields({{"[Nr]", 2}, {"Name", 7}}); 4090 4091 constexpr bool Is64 = ELFT::Is64Bits; 4092 PrintFields({{"Type", 7}, 4093 {Is64 ? "Address" : "Addr", 23}, 4094 {"Off", Is64 ? 40 : 32}, 4095 {"Size", Is64 ? 47 : 39}, 4096 {"ES", Is64 ? 54 : 46}, 4097 {"Lk", Is64 ? 59 : 51}, 4098 {"Inf", Is64 ? 62 : 54}, 4099 {"Al", Is64 ? 66 : 57}}); 4100 PrintFields({{"Flags", 7}}); 4101 4102 StringRef SecStrTable; 4103 if (Expected<StringRef> SecStrTableOrErr = 4104 this->Obj.getSectionStringTable(Sections, this->WarningHandler)) 4105 SecStrTable = *SecStrTableOrErr; 4106 else 4107 this->reportUniqueWarning(SecStrTableOrErr.takeError()); 4108 4109 size_t SectionIndex = 0; 4110 const unsigned AddrSize = Is64 ? 16 : 8; 4111 for (const Elf_Shdr &S : Sections) { 4112 StringRef Name = "<?>"; 4113 if (Expected<StringRef> NameOrErr = 4114 this->Obj.getSectionName(S, SecStrTable)) 4115 Name = *NameOrErr; 4116 else 4117 this->reportUniqueWarning(NameOrErr.takeError()); 4118 4119 OS.PadToColumn(2); 4120 OS << "[" << right_justify(to_string(SectionIndex), 2) << "]"; 4121 PrintFields({{Name, 7}}); 4122 PrintFields( 4123 {{getSectionTypeString(this->Obj.getHeader().e_machine, S.sh_type), 7}, 4124 {to_string(format_hex_no_prefix(S.sh_addr, AddrSize)), 23}, 4125 {to_string(format_hex_no_prefix(S.sh_offset, 6)), Is64 ? 39 : 32}, 4126 {to_string(format_hex_no_prefix(S.sh_size, 6)), Is64 ? 47 : 39}, 4127 {to_string(format_hex_no_prefix(S.sh_entsize, 2)), Is64 ? 54 : 46}, 4128 {to_string(S.sh_link), Is64 ? 59 : 51}, 4129 {to_string(S.sh_info), Is64 ? 63 : 55}, 4130 {to_string(S.sh_addralign), Is64 ? 66 : 58}}); 4131 4132 OS.PadToColumn(7); 4133 OS << "[" << to_string(format_hex_no_prefix(S.sh_flags, AddrSize)) << "]: "; 4134 4135 DenseMap<unsigned, StringRef> FlagToName = { 4136 {SHF_WRITE, "WRITE"}, {SHF_ALLOC, "ALLOC"}, 4137 {SHF_EXECINSTR, "EXEC"}, {SHF_MERGE, "MERGE"}, 4138 {SHF_STRINGS, "STRINGS"}, {SHF_INFO_LINK, "INFO LINK"}, 4139 {SHF_LINK_ORDER, "LINK ORDER"}, {SHF_OS_NONCONFORMING, "OS NONCONF"}, 4140 {SHF_GROUP, "GROUP"}, {SHF_TLS, "TLS"}, 4141 {SHF_COMPRESSED, "COMPRESSED"}, {SHF_EXCLUDE, "EXCLUDE"}}; 4142 4143 uint64_t Flags = S.sh_flags; 4144 uint64_t UnknownFlags = 0; 4145 ListSeparator LS; 4146 while (Flags) { 4147 // Take the least significant bit as a flag. 4148 uint64_t Flag = Flags & -Flags; 4149 Flags -= Flag; 4150 4151 auto It = FlagToName.find(Flag); 4152 if (It != FlagToName.end()) 4153 OS << LS << It->second; 4154 else 4155 UnknownFlags |= Flag; 4156 } 4157 4158 auto PrintUnknownFlags = [&](uint64_t Mask, StringRef Name) { 4159 uint64_t FlagsToPrint = UnknownFlags & Mask; 4160 if (!FlagsToPrint) 4161 return; 4162 4163 OS << LS << Name << " (" 4164 << to_string(format_hex_no_prefix(FlagsToPrint, AddrSize)) << ")"; 4165 UnknownFlags &= ~Mask; 4166 }; 4167 4168 PrintUnknownFlags(SHF_MASKOS, "OS"); 4169 PrintUnknownFlags(SHF_MASKPROC, "PROC"); 4170 PrintUnknownFlags(uint64_t(-1), "UNKNOWN"); 4171 4172 OS << "\n"; 4173 ++SectionIndex; 4174 } 4175 } 4176 4177 static inline std::string printPhdrFlags(unsigned Flag) { 4178 std::string Str; 4179 Str = (Flag & PF_R) ? "R" : " "; 4180 Str += (Flag & PF_W) ? "W" : " "; 4181 Str += (Flag & PF_X) ? "E" : " "; 4182 return Str; 4183 } 4184 4185 template <class ELFT> 4186 static bool checkTLSSections(const typename ELFT::Phdr &Phdr, 4187 const typename ELFT::Shdr &Sec) { 4188 if (Sec.sh_flags & ELF::SHF_TLS) { 4189 // .tbss must only be shown in the PT_TLS segment. 4190 if (Sec.sh_type == ELF::SHT_NOBITS) 4191 return Phdr.p_type == ELF::PT_TLS; 4192 4193 // SHF_TLS sections are only shown in PT_TLS, PT_LOAD or PT_GNU_RELRO 4194 // segments. 4195 return (Phdr.p_type == ELF::PT_TLS) || (Phdr.p_type == ELF::PT_LOAD) || 4196 (Phdr.p_type == ELF::PT_GNU_RELRO); 4197 } 4198 4199 // PT_TLS must only have SHF_TLS sections. 4200 return Phdr.p_type != ELF::PT_TLS; 4201 } 4202 4203 template <class ELFT> 4204 static bool checkOffsets(const typename ELFT::Phdr &Phdr, 4205 const typename ELFT::Shdr &Sec) { 4206 // SHT_NOBITS sections don't need to have an offset inside the segment. 4207 if (Sec.sh_type == ELF::SHT_NOBITS) 4208 return true; 4209 4210 if (Sec.sh_offset < Phdr.p_offset) 4211 return false; 4212 4213 // Only non-empty sections can be at the end of a segment. 4214 if (Sec.sh_size == 0) 4215 return (Sec.sh_offset + 1 <= Phdr.p_offset + Phdr.p_filesz); 4216 return Sec.sh_offset + Sec.sh_size <= Phdr.p_offset + Phdr.p_filesz; 4217 } 4218 4219 // Check that an allocatable section belongs to a virtual address 4220 // space of a segment. 4221 template <class ELFT> 4222 static bool checkVMA(const typename ELFT::Phdr &Phdr, 4223 const typename ELFT::Shdr &Sec) { 4224 if (!(Sec.sh_flags & ELF::SHF_ALLOC)) 4225 return true; 4226 4227 if (Sec.sh_addr < Phdr.p_vaddr) 4228 return false; 4229 4230 bool IsTbss = 4231 (Sec.sh_type == ELF::SHT_NOBITS) && ((Sec.sh_flags & ELF::SHF_TLS) != 0); 4232 // .tbss is special, it only has memory in PT_TLS and has NOBITS properties. 4233 bool IsTbssInNonTLS = IsTbss && Phdr.p_type != ELF::PT_TLS; 4234 // Only non-empty sections can be at the end of a segment. 4235 if (Sec.sh_size == 0 || IsTbssInNonTLS) 4236 return Sec.sh_addr + 1 <= Phdr.p_vaddr + Phdr.p_memsz; 4237 return Sec.sh_addr + Sec.sh_size <= Phdr.p_vaddr + Phdr.p_memsz; 4238 } 4239 4240 template <class ELFT> 4241 static bool checkPTDynamic(const typename ELFT::Phdr &Phdr, 4242 const typename ELFT::Shdr &Sec) { 4243 if (Phdr.p_type != ELF::PT_DYNAMIC || Phdr.p_memsz == 0 || Sec.sh_size != 0) 4244 return true; 4245 4246 // We get here when we have an empty section. Only non-empty sections can be 4247 // at the start or at the end of PT_DYNAMIC. 4248 // Is section within the phdr both based on offset and VMA? 4249 bool CheckOffset = (Sec.sh_type == ELF::SHT_NOBITS) || 4250 (Sec.sh_offset > Phdr.p_offset && 4251 Sec.sh_offset < Phdr.p_offset + Phdr.p_filesz); 4252 bool CheckVA = !(Sec.sh_flags & ELF::SHF_ALLOC) || 4253 (Sec.sh_addr > Phdr.p_vaddr && Sec.sh_addr < Phdr.p_memsz); 4254 return CheckOffset && CheckVA; 4255 } 4256 4257 template <class ELFT> 4258 void GNUELFDumper<ELFT>::printProgramHeaders( 4259 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) { 4260 if (PrintProgramHeaders) 4261 printProgramHeaders(); 4262 4263 // Display the section mapping along with the program headers, unless 4264 // -section-mapping is explicitly set to false. 4265 if (PrintSectionMapping != cl::BOU_FALSE) 4266 printSectionMapping(); 4267 } 4268 4269 template <class ELFT> void GNUELFDumper<ELFT>::printProgramHeaders() { 4270 unsigned Bias = ELFT::Is64Bits ? 8 : 0; 4271 const Elf_Ehdr &Header = this->Obj.getHeader(); 4272 Field Fields[8] = {2, 17, 26, 37 + Bias, 4273 48 + Bias, 56 + Bias, 64 + Bias, 68 + Bias}; 4274 OS << "\nElf file type is " 4275 << enumToString(Header.e_type, makeArrayRef(ElfObjectFileType)) << "\n" 4276 << "Entry point " << format_hex(Header.e_entry, 3) << "\n" 4277 << "There are " << Header.e_phnum << " program headers," 4278 << " starting at offset " << Header.e_phoff << "\n\n" 4279 << "Program Headers:\n"; 4280 if (ELFT::Is64Bits) 4281 OS << " Type Offset VirtAddr PhysAddr " 4282 << " FileSiz MemSiz Flg Align\n"; 4283 else 4284 OS << " Type Offset VirtAddr PhysAddr FileSiz " 4285 << "MemSiz Flg Align\n"; 4286 4287 unsigned Width = ELFT::Is64Bits ? 18 : 10; 4288 unsigned SizeWidth = ELFT::Is64Bits ? 8 : 7; 4289 4290 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers(); 4291 if (!PhdrsOrErr) { 4292 this->reportUniqueWarning("unable to dump program headers: " + 4293 toString(PhdrsOrErr.takeError())); 4294 return; 4295 } 4296 4297 for (const Elf_Phdr &Phdr : *PhdrsOrErr) { 4298 Fields[0].Str = getGNUPtType(Header.e_machine, Phdr.p_type); 4299 Fields[1].Str = to_string(format_hex(Phdr.p_offset, 8)); 4300 Fields[2].Str = to_string(format_hex(Phdr.p_vaddr, Width)); 4301 Fields[3].Str = to_string(format_hex(Phdr.p_paddr, Width)); 4302 Fields[4].Str = to_string(format_hex(Phdr.p_filesz, SizeWidth)); 4303 Fields[5].Str = to_string(format_hex(Phdr.p_memsz, SizeWidth)); 4304 Fields[6].Str = printPhdrFlags(Phdr.p_flags); 4305 Fields[7].Str = to_string(format_hex(Phdr.p_align, 1)); 4306 for (const Field &F : Fields) 4307 printField(F); 4308 if (Phdr.p_type == ELF::PT_INTERP) { 4309 OS << "\n"; 4310 auto ReportBadInterp = [&](const Twine &Msg) { 4311 this->reportUniqueWarning( 4312 "unable to read program interpreter name at offset 0x" + 4313 Twine::utohexstr(Phdr.p_offset) + ": " + Msg); 4314 }; 4315 4316 if (Phdr.p_offset >= this->Obj.getBufSize()) { 4317 ReportBadInterp("it goes past the end of the file (0x" + 4318 Twine::utohexstr(this->Obj.getBufSize()) + ")"); 4319 continue; 4320 } 4321 4322 const char *Data = 4323 reinterpret_cast<const char *>(this->Obj.base()) + Phdr.p_offset; 4324 size_t MaxSize = this->Obj.getBufSize() - Phdr.p_offset; 4325 size_t Len = strnlen(Data, MaxSize); 4326 if (Len == MaxSize) { 4327 ReportBadInterp("it is not null-terminated"); 4328 continue; 4329 } 4330 4331 OS << " [Requesting program interpreter: "; 4332 OS << StringRef(Data, Len) << "]"; 4333 } 4334 OS << "\n"; 4335 } 4336 } 4337 4338 template <class ELFT> void GNUELFDumper<ELFT>::printSectionMapping() { 4339 OS << "\n Section to Segment mapping:\n Segment Sections...\n"; 4340 DenseSet<const Elf_Shdr *> BelongsToSegment; 4341 int Phnum = 0; 4342 4343 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers(); 4344 if (!PhdrsOrErr) { 4345 this->reportUniqueWarning( 4346 "can't read program headers to build section to segment mapping: " + 4347 toString(PhdrsOrErr.takeError())); 4348 return; 4349 } 4350 4351 for (const Elf_Phdr &Phdr : *PhdrsOrErr) { 4352 std::string Sections; 4353 OS << format(" %2.2d ", Phnum++); 4354 // Check if each section is in a segment and then print mapping. 4355 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) { 4356 if (Sec.sh_type == ELF::SHT_NULL) 4357 continue; 4358 4359 // readelf additionally makes sure it does not print zero sized sections 4360 // at end of segments and for PT_DYNAMIC both start and end of section 4361 // .tbss must only be shown in PT_TLS section. 4362 if (checkTLSSections<ELFT>(Phdr, Sec) && checkOffsets<ELFT>(Phdr, Sec) && 4363 checkVMA<ELFT>(Phdr, Sec) && checkPTDynamic<ELFT>(Phdr, Sec)) { 4364 Sections += 4365 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() + 4366 " "; 4367 BelongsToSegment.insert(&Sec); 4368 } 4369 } 4370 OS << Sections << "\n"; 4371 OS.flush(); 4372 } 4373 4374 // Display sections that do not belong to a segment. 4375 std::string Sections; 4376 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) { 4377 if (BelongsToSegment.find(&Sec) == BelongsToSegment.end()) 4378 Sections += 4379 unwrapOrError(this->FileName, this->Obj.getSectionName(Sec)).str() + 4380 ' '; 4381 } 4382 if (!Sections.empty()) { 4383 OS << " None " << Sections << '\n'; 4384 OS.flush(); 4385 } 4386 } 4387 4388 namespace { 4389 4390 template <class ELFT> 4391 RelSymbol<ELFT> getSymbolForReloc(const ELFDumper<ELFT> &Dumper, 4392 const Relocation<ELFT> &Reloc) { 4393 using Elf_Sym = typename ELFT::Sym; 4394 auto WarnAndReturn = [&](const Elf_Sym *Sym, 4395 const Twine &Reason) -> RelSymbol<ELFT> { 4396 Dumper.reportUniqueWarning( 4397 "unable to get name of the dynamic symbol with index " + 4398 Twine(Reloc.Symbol) + ": " + Reason); 4399 return {Sym, "<corrupt>"}; 4400 }; 4401 4402 ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols(); 4403 const Elf_Sym *FirstSym = Symbols.begin(); 4404 if (!FirstSym) 4405 return WarnAndReturn(nullptr, "no dynamic symbol table found"); 4406 4407 // We might have an object without a section header. In this case the size of 4408 // Symbols is zero, because there is no way to know the size of the dynamic 4409 // table. We should allow this case and not print a warning. 4410 if (!Symbols.empty() && Reloc.Symbol >= Symbols.size()) 4411 return WarnAndReturn( 4412 nullptr, 4413 "index is greater than or equal to the number of dynamic symbols (" + 4414 Twine(Symbols.size()) + ")"); 4415 4416 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile(); 4417 const uint64_t FileSize = Obj.getBufSize(); 4418 const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) + 4419 (uint64_t)Reloc.Symbol * sizeof(Elf_Sym); 4420 if (SymOffset + sizeof(Elf_Sym) > FileSize) 4421 return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(SymOffset) + 4422 " goes past the end of the file (0x" + 4423 Twine::utohexstr(FileSize) + ")"); 4424 4425 const Elf_Sym *Sym = FirstSym + Reloc.Symbol; 4426 Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable()); 4427 if (!ErrOrName) 4428 return WarnAndReturn(Sym, toString(ErrOrName.takeError())); 4429 4430 return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(*ErrOrName)}; 4431 } 4432 } // namespace 4433 4434 template <class ELFT> 4435 static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj, 4436 typename ELFT::DynRange Tags) { 4437 size_t Max = 0; 4438 for (const typename ELFT::Dyn &Dyn : Tags) 4439 Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size()); 4440 return Max; 4441 } 4442 4443 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicTable() { 4444 Elf_Dyn_Range Table = this->dynamic_table(); 4445 if (Table.empty()) 4446 return; 4447 4448 OS << "Dynamic section at offset " 4449 << format_hex(reinterpret_cast<const uint8_t *>(this->DynamicTable.Addr) - 4450 this->Obj.base(), 4451 1) 4452 << " contains " << Table.size() << " entries:\n"; 4453 4454 // The type name is surrounded with round brackets, hence add 2. 4455 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2; 4456 // The "Name/Value" column should be indented from the "Type" column by N 4457 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing 4458 // space (1) = 3. 4459 OS << " Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type" 4460 << std::string(MaxTagSize - 3, ' ') << "Name/Value\n"; 4461 4462 std::string ValueFmt = " %-" + std::to_string(MaxTagSize) + "s "; 4463 for (auto Entry : Table) { 4464 uintX_t Tag = Entry.getTag(); 4465 std::string Type = 4466 std::string("(") + this->Obj.getDynamicTagAsString(Tag) + ")"; 4467 std::string Value = this->getDynamicEntry(Tag, Entry.getVal()); 4468 OS << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10) 4469 << format(ValueFmt.c_str(), Type.c_str()) << Value << "\n"; 4470 } 4471 } 4472 4473 template <class ELFT> void GNUELFDumper<ELFT>::printDynamicRelocations() { 4474 this->printDynamicRelocationsHelper(); 4475 } 4476 4477 template <class ELFT> 4478 void ELFDumper<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) { 4479 printRelRelaReloc(R, getSymbolForReloc(*this, R)); 4480 } 4481 4482 template <class ELFT> 4483 void ELFDumper<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) { 4484 this->forEachRelocationDo( 4485 Sec, opts::RawRelr, 4486 [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec, 4487 const Elf_Shdr *SymTab) { printReloc(R, Ndx, Sec, SymTab); }, 4488 [&](const Elf_Relr &R) { printRelrReloc(R); }); 4489 } 4490 4491 template <class ELFT> void ELFDumper<ELFT>::printDynamicRelocationsHelper() { 4492 const bool IsMips64EL = this->Obj.isMips64EL(); 4493 if (this->DynRelaRegion.Size > 0) { 4494 printDynamicRelocHeader(ELF::SHT_RELA, "RELA", this->DynRelaRegion); 4495 for (const Elf_Rela &Rela : 4496 this->DynRelaRegion.template getAsArrayRef<Elf_Rela>()) 4497 printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL)); 4498 } 4499 4500 if (this->DynRelRegion.Size > 0) { 4501 printDynamicRelocHeader(ELF::SHT_REL, "REL", this->DynRelRegion); 4502 for (const Elf_Rel &Rel : 4503 this->DynRelRegion.template getAsArrayRef<Elf_Rel>()) 4504 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL)); 4505 } 4506 4507 if (this->DynRelrRegion.Size > 0) { 4508 printDynamicRelocHeader(ELF::SHT_REL, "RELR", this->DynRelrRegion); 4509 Elf_Relr_Range Relrs = 4510 this->DynRelrRegion.template getAsArrayRef<Elf_Relr>(); 4511 for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs)) 4512 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL)); 4513 } 4514 4515 if (this->DynPLTRelRegion.Size) { 4516 if (this->DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) { 4517 printDynamicRelocHeader(ELF::SHT_RELA, "PLT", this->DynPLTRelRegion); 4518 for (const Elf_Rela &Rela : 4519 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rela>()) 4520 printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL)); 4521 } else { 4522 printDynamicRelocHeader(ELF::SHT_REL, "PLT", this->DynPLTRelRegion); 4523 for (const Elf_Rel &Rel : 4524 this->DynPLTRelRegion.template getAsArrayRef<Elf_Rel>()) 4525 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL)); 4526 } 4527 } 4528 } 4529 4530 template <class ELFT> 4531 void GNUELFDumper<ELFT>::printGNUVersionSectionProlog( 4532 const typename ELFT::Shdr &Sec, const Twine &Label, unsigned EntriesNum) { 4533 // Don't inline the SecName, because it might report a warning to stderr and 4534 // corrupt the output. 4535 StringRef SecName = this->getPrintableSectionName(Sec); 4536 OS << Label << " section '" << SecName << "' " 4537 << "contains " << EntriesNum << " entries:\n"; 4538 4539 StringRef LinkedSecName = "<corrupt>"; 4540 if (Expected<const typename ELFT::Shdr *> LinkedSecOrErr = 4541 this->Obj.getSection(Sec.sh_link)) 4542 LinkedSecName = this->getPrintableSectionName(**LinkedSecOrErr); 4543 else 4544 this->reportUniqueWarning("invalid section linked to " + 4545 this->describe(Sec) + ": " + 4546 toString(LinkedSecOrErr.takeError())); 4547 4548 OS << " Addr: " << format_hex_no_prefix(Sec.sh_addr, 16) 4549 << " Offset: " << format_hex(Sec.sh_offset, 8) 4550 << " Link: " << Sec.sh_link << " (" << LinkedSecName << ")\n"; 4551 } 4552 4553 template <class ELFT> 4554 void GNUELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) { 4555 if (!Sec) 4556 return; 4557 4558 printGNUVersionSectionProlog(*Sec, "Version symbols", 4559 Sec->sh_size / sizeof(Elf_Versym)); 4560 Expected<ArrayRef<Elf_Versym>> VerTableOrErr = 4561 this->getVersionTable(*Sec, /*SymTab=*/nullptr, 4562 /*StrTab=*/nullptr, /*SymTabSec=*/nullptr); 4563 if (!VerTableOrErr) { 4564 this->reportUniqueWarning(VerTableOrErr.takeError()); 4565 return; 4566 } 4567 4568 SmallVector<Optional<VersionEntry>, 0> *VersionMap = nullptr; 4569 if (Expected<SmallVector<Optional<VersionEntry>, 0> *> MapOrErr = 4570 this->getVersionMap()) 4571 VersionMap = *MapOrErr; 4572 else 4573 this->reportUniqueWarning(MapOrErr.takeError()); 4574 4575 ArrayRef<Elf_Versym> VerTable = *VerTableOrErr; 4576 std::vector<StringRef> Versions; 4577 for (size_t I = 0, E = VerTable.size(); I < E; ++I) { 4578 unsigned Ndx = VerTable[I].vs_index; 4579 if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) { 4580 Versions.emplace_back(Ndx == VER_NDX_LOCAL ? "*local*" : "*global*"); 4581 continue; 4582 } 4583 4584 if (!VersionMap) { 4585 Versions.emplace_back("<corrupt>"); 4586 continue; 4587 } 4588 4589 bool IsDefault; 4590 Expected<StringRef> NameOrErr = this->Obj.getSymbolVersionByIndex( 4591 Ndx, IsDefault, *VersionMap, /*IsSymHidden=*/None); 4592 if (!NameOrErr) { 4593 this->reportUniqueWarning("unable to get a version for entry " + 4594 Twine(I) + " of " + this->describe(*Sec) + 4595 ": " + toString(NameOrErr.takeError())); 4596 Versions.emplace_back("<corrupt>"); 4597 continue; 4598 } 4599 Versions.emplace_back(*NameOrErr); 4600 } 4601 4602 // readelf prints 4 entries per line. 4603 uint64_t Entries = VerTable.size(); 4604 for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) { 4605 OS << " " << format_hex_no_prefix(VersymRow, 3) << ":"; 4606 for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) { 4607 unsigned Ndx = VerTable[VersymRow + I].vs_index; 4608 OS << format("%4x%c", Ndx & VERSYM_VERSION, 4609 Ndx & VERSYM_HIDDEN ? 'h' : ' '); 4610 OS << left_justify("(" + std::string(Versions[VersymRow + I]) + ")", 13); 4611 } 4612 OS << '\n'; 4613 } 4614 OS << '\n'; 4615 } 4616 4617 static std::string versionFlagToString(unsigned Flags) { 4618 if (Flags == 0) 4619 return "none"; 4620 4621 std::string Ret; 4622 auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) { 4623 if (!(Flags & Flag)) 4624 return; 4625 if (!Ret.empty()) 4626 Ret += " | "; 4627 Ret += Name; 4628 Flags &= ~Flag; 4629 }; 4630 4631 AddFlag(VER_FLG_BASE, "BASE"); 4632 AddFlag(VER_FLG_WEAK, "WEAK"); 4633 AddFlag(VER_FLG_INFO, "INFO"); 4634 AddFlag(~0, "<unknown>"); 4635 return Ret; 4636 } 4637 4638 template <class ELFT> 4639 void GNUELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) { 4640 if (!Sec) 4641 return; 4642 4643 printGNUVersionSectionProlog(*Sec, "Version definition", Sec->sh_info); 4644 4645 Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec); 4646 if (!V) { 4647 this->reportUniqueWarning(V.takeError()); 4648 return; 4649 } 4650 4651 for (const VerDef &Def : *V) { 4652 OS << format(" 0x%04x: Rev: %u Flags: %s Index: %u Cnt: %u Name: %s\n", 4653 Def.Offset, Def.Version, 4654 versionFlagToString(Def.Flags).c_str(), Def.Ndx, Def.Cnt, 4655 Def.Name.data()); 4656 unsigned I = 0; 4657 for (const VerdAux &Aux : Def.AuxV) 4658 OS << format(" 0x%04x: Parent %u: %s\n", Aux.Offset, ++I, 4659 Aux.Name.data()); 4660 } 4661 4662 OS << '\n'; 4663 } 4664 4665 template <class ELFT> 4666 void GNUELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) { 4667 if (!Sec) 4668 return; 4669 4670 unsigned VerneedNum = Sec->sh_info; 4671 printGNUVersionSectionProlog(*Sec, "Version needs", VerneedNum); 4672 4673 Expected<std::vector<VerNeed>> V = 4674 this->Obj.getVersionDependencies(*Sec, this->WarningHandler); 4675 if (!V) { 4676 this->reportUniqueWarning(V.takeError()); 4677 return; 4678 } 4679 4680 for (const VerNeed &VN : *V) { 4681 OS << format(" 0x%04x: Version: %u File: %s Cnt: %u\n", VN.Offset, 4682 VN.Version, VN.File.data(), VN.Cnt); 4683 for (const VernAux &Aux : VN.AuxV) 4684 OS << format(" 0x%04x: Name: %s Flags: %s Version: %u\n", Aux.Offset, 4685 Aux.Name.data(), versionFlagToString(Aux.Flags).c_str(), 4686 Aux.Other); 4687 } 4688 OS << '\n'; 4689 } 4690 4691 template <class ELFT> 4692 void GNUELFDumper<ELFT>::printHashHistogram(const Elf_Hash &HashTable) { 4693 size_t NBucket = HashTable.nbucket; 4694 size_t NChain = HashTable.nchain; 4695 ArrayRef<Elf_Word> Buckets = HashTable.buckets(); 4696 ArrayRef<Elf_Word> Chains = HashTable.chains(); 4697 size_t TotalSyms = 0; 4698 // If hash table is correct, we have at least chains with 0 length 4699 size_t MaxChain = 1; 4700 size_t CumulativeNonZero = 0; 4701 4702 if (NChain == 0 || NBucket == 0) 4703 return; 4704 4705 std::vector<size_t> ChainLen(NBucket, 0); 4706 // Go over all buckets and and note chain lengths of each bucket (total 4707 // unique chain lengths). 4708 for (size_t B = 0; B < NBucket; B++) { 4709 BitVector Visited(NChain); 4710 for (size_t C = Buckets[B]; C < NChain; C = Chains[C]) { 4711 if (C == ELF::STN_UNDEF) 4712 break; 4713 if (Visited[C]) { 4714 this->reportUniqueWarning(".hash section is invalid: bucket " + 4715 Twine(C) + 4716 ": a cycle was detected in the linked chain"); 4717 break; 4718 } 4719 Visited[C] = true; 4720 if (MaxChain <= ++ChainLen[B]) 4721 MaxChain++; 4722 } 4723 TotalSyms += ChainLen[B]; 4724 } 4725 4726 if (!TotalSyms) 4727 return; 4728 4729 std::vector<size_t> Count(MaxChain, 0); 4730 // Count how long is the chain for each bucket 4731 for (size_t B = 0; B < NBucket; B++) 4732 ++Count[ChainLen[B]]; 4733 // Print Number of buckets with each chain lengths and their cumulative 4734 // coverage of the symbols 4735 OS << "Histogram for bucket list length (total of " << NBucket 4736 << " buckets)\n" 4737 << " Length Number % of total Coverage\n"; 4738 for (size_t I = 0; I < MaxChain; I++) { 4739 CumulativeNonZero += Count[I] * I; 4740 OS << format("%7lu %-10lu (%5.1f%%) %5.1f%%\n", I, Count[I], 4741 (Count[I] * 100.0) / NBucket, 4742 (CumulativeNonZero * 100.0) / TotalSyms); 4743 } 4744 } 4745 4746 template <class ELFT> 4747 void GNUELFDumper<ELFT>::printGnuHashHistogram( 4748 const Elf_GnuHash &GnuHashTable) { 4749 Expected<ArrayRef<Elf_Word>> ChainsOrErr = 4750 getGnuHashTableChains<ELFT>(this->DynSymRegion, &GnuHashTable); 4751 if (!ChainsOrErr) { 4752 this->reportUniqueWarning("unable to print the GNU hash table histogram: " + 4753 toString(ChainsOrErr.takeError())); 4754 return; 4755 } 4756 4757 ArrayRef<Elf_Word> Chains = *ChainsOrErr; 4758 size_t Symndx = GnuHashTable.symndx; 4759 size_t TotalSyms = 0; 4760 size_t MaxChain = 1; 4761 size_t CumulativeNonZero = 0; 4762 4763 size_t NBucket = GnuHashTable.nbuckets; 4764 if (Chains.empty() || NBucket == 0) 4765 return; 4766 4767 ArrayRef<Elf_Word> Buckets = GnuHashTable.buckets(); 4768 std::vector<size_t> ChainLen(NBucket, 0); 4769 for (size_t B = 0; B < NBucket; B++) { 4770 if (!Buckets[B]) 4771 continue; 4772 size_t Len = 1; 4773 for (size_t C = Buckets[B] - Symndx; 4774 C < Chains.size() && (Chains[C] & 1) == 0; C++) 4775 if (MaxChain < ++Len) 4776 MaxChain++; 4777 ChainLen[B] = Len; 4778 TotalSyms += Len; 4779 } 4780 MaxChain++; 4781 4782 if (!TotalSyms) 4783 return; 4784 4785 std::vector<size_t> Count(MaxChain, 0); 4786 for (size_t B = 0; B < NBucket; B++) 4787 ++Count[ChainLen[B]]; 4788 // Print Number of buckets with each chain lengths and their cumulative 4789 // coverage of the symbols 4790 OS << "Histogram for `.gnu.hash' bucket list length (total of " << NBucket 4791 << " buckets)\n" 4792 << " Length Number % of total Coverage\n"; 4793 for (size_t I = 0; I < MaxChain; I++) { 4794 CumulativeNonZero += Count[I] * I; 4795 OS << format("%7lu %-10lu (%5.1f%%) %5.1f%%\n", I, Count[I], 4796 (Count[I] * 100.0) / NBucket, 4797 (CumulativeNonZero * 100.0) / TotalSyms); 4798 } 4799 } 4800 4801 // Hash histogram shows statistics of how efficient the hash was for the 4802 // dynamic symbol table. The table shows the number of hash buckets for 4803 // different lengths of chains as an absolute number and percentage of the total 4804 // buckets, and the cumulative coverage of symbols for each set of buckets. 4805 template <class ELFT> void GNUELFDumper<ELFT>::printHashHistograms() { 4806 // Print histogram for the .hash section. 4807 if (this->HashTable) { 4808 if (Error E = checkHashTable<ELFT>(*this, this->HashTable)) 4809 this->reportUniqueWarning(std::move(E)); 4810 else 4811 printHashHistogram(*this->HashTable); 4812 } 4813 4814 // Print histogram for the .gnu.hash section. 4815 if (this->GnuHashTable) { 4816 if (Error E = checkGNUHashTable<ELFT>(this->Obj, this->GnuHashTable)) 4817 this->reportUniqueWarning(std::move(E)); 4818 else 4819 printGnuHashHistogram(*this->GnuHashTable); 4820 } 4821 } 4822 4823 template <class ELFT> void GNUELFDumper<ELFT>::printCGProfile() { 4824 OS << "GNUStyle::printCGProfile not implemented\n"; 4825 } 4826 4827 template <class ELFT> void GNUELFDumper<ELFT>::printBBAddrMaps() { 4828 OS << "GNUStyle::printBBAddrMaps not implemented\n"; 4829 } 4830 4831 static Expected<std::vector<uint64_t>> toULEB128Array(ArrayRef<uint8_t> Data) { 4832 std::vector<uint64_t> Ret; 4833 const uint8_t *Cur = Data.begin(); 4834 const uint8_t *End = Data.end(); 4835 while (Cur != End) { 4836 unsigned Size; 4837 const char *Err; 4838 Ret.push_back(decodeULEB128(Cur, &Size, End, &Err)); 4839 if (Err) 4840 return createError(Err); 4841 Cur += Size; 4842 } 4843 return Ret; 4844 } 4845 4846 template <class ELFT> 4847 static Expected<std::vector<uint64_t>> 4848 decodeAddrsigSection(const ELFFile<ELFT> &Obj, const typename ELFT::Shdr &Sec) { 4849 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Sec); 4850 if (!ContentsOrErr) 4851 return ContentsOrErr.takeError(); 4852 4853 if (Expected<std::vector<uint64_t>> SymsOrErr = 4854 toULEB128Array(*ContentsOrErr)) 4855 return *SymsOrErr; 4856 else 4857 return createError("unable to decode " + describe(Obj, Sec) + ": " + 4858 toString(SymsOrErr.takeError())); 4859 } 4860 4861 template <class ELFT> void GNUELFDumper<ELFT>::printAddrsig() { 4862 if (!this->DotAddrsigSec) 4863 return; 4864 4865 Expected<std::vector<uint64_t>> SymsOrErr = 4866 decodeAddrsigSection(this->Obj, *this->DotAddrsigSec); 4867 if (!SymsOrErr) { 4868 this->reportUniqueWarning(SymsOrErr.takeError()); 4869 return; 4870 } 4871 4872 StringRef Name = this->getPrintableSectionName(*this->DotAddrsigSec); 4873 OS << "\nAddress-significant symbols section '" << Name << "'" 4874 << " contains " << SymsOrErr->size() << " entries:\n"; 4875 OS << " Num: Name\n"; 4876 4877 Field Fields[2] = {0, 8}; 4878 size_t SymIndex = 0; 4879 for (uint64_t Sym : *SymsOrErr) { 4880 Fields[0].Str = to_string(format_decimal(++SymIndex, 6)) + ":"; 4881 Fields[1].Str = this->getStaticSymbolName(Sym); 4882 for (const Field &Entry : Fields) 4883 printField(Entry); 4884 OS << "\n"; 4885 } 4886 } 4887 4888 template <typename ELFT> 4889 static std::string getGNUProperty(uint32_t Type, uint32_t DataSize, 4890 ArrayRef<uint8_t> Data) { 4891 std::string str; 4892 raw_string_ostream OS(str); 4893 uint32_t PrData; 4894 auto DumpBit = [&](uint32_t Flag, StringRef Name) { 4895 if (PrData & Flag) { 4896 PrData &= ~Flag; 4897 OS << Name; 4898 if (PrData) 4899 OS << ", "; 4900 } 4901 }; 4902 4903 switch (Type) { 4904 default: 4905 OS << format("<application-specific type 0x%x>", Type); 4906 return OS.str(); 4907 case GNU_PROPERTY_STACK_SIZE: { 4908 OS << "stack size: "; 4909 if (DataSize == sizeof(typename ELFT::uint)) 4910 OS << formatv("{0:x}", 4911 (uint64_t)(*(const typename ELFT::Addr *)Data.data())); 4912 else 4913 OS << format("<corrupt length: 0x%x>", DataSize); 4914 return OS.str(); 4915 } 4916 case GNU_PROPERTY_NO_COPY_ON_PROTECTED: 4917 OS << "no copy on protected"; 4918 if (DataSize) 4919 OS << format(" <corrupt length: 0x%x>", DataSize); 4920 return OS.str(); 4921 case GNU_PROPERTY_AARCH64_FEATURE_1_AND: 4922 case GNU_PROPERTY_X86_FEATURE_1_AND: 4923 OS << ((Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) ? "aarch64 feature: " 4924 : "x86 feature: "); 4925 if (DataSize != 4) { 4926 OS << format("<corrupt length: 0x%x>", DataSize); 4927 return OS.str(); 4928 } 4929 PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data()); 4930 if (PrData == 0) { 4931 OS << "<None>"; 4932 return OS.str(); 4933 } 4934 if (Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) { 4935 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI, "BTI"); 4936 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC, "PAC"); 4937 } else { 4938 DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT, "IBT"); 4939 DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK, "SHSTK"); 4940 } 4941 if (PrData) 4942 OS << format("<unknown flags: 0x%x>", PrData); 4943 return OS.str(); 4944 case GNU_PROPERTY_X86_FEATURE_2_NEEDED: 4945 case GNU_PROPERTY_X86_FEATURE_2_USED: 4946 OS << "x86 feature " 4947 << (Type == GNU_PROPERTY_X86_FEATURE_2_NEEDED ? "needed: " : "used: "); 4948 if (DataSize != 4) { 4949 OS << format("<corrupt length: 0x%x>", DataSize); 4950 return OS.str(); 4951 } 4952 PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data()); 4953 if (PrData == 0) { 4954 OS << "<None>"; 4955 return OS.str(); 4956 } 4957 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86, "x86"); 4958 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87, "x87"); 4959 DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX, "MMX"); 4960 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM, "XMM"); 4961 DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM, "YMM"); 4962 DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM, "ZMM"); 4963 DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR, "FXSR"); 4964 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE, "XSAVE"); 4965 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT, "XSAVEOPT"); 4966 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC, "XSAVEC"); 4967 if (PrData) 4968 OS << format("<unknown flags: 0x%x>", PrData); 4969 return OS.str(); 4970 case GNU_PROPERTY_X86_ISA_1_NEEDED: 4971 case GNU_PROPERTY_X86_ISA_1_USED: 4972 OS << "x86 ISA " 4973 << (Type == GNU_PROPERTY_X86_ISA_1_NEEDED ? "needed: " : "used: "); 4974 if (DataSize != 4) { 4975 OS << format("<corrupt length: 0x%x>", DataSize); 4976 return OS.str(); 4977 } 4978 PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data()); 4979 if (PrData == 0) { 4980 OS << "<None>"; 4981 return OS.str(); 4982 } 4983 DumpBit(GNU_PROPERTY_X86_ISA_1_BASELINE, "x86-64-baseline"); 4984 DumpBit(GNU_PROPERTY_X86_ISA_1_V2, "x86-64-v2"); 4985 DumpBit(GNU_PROPERTY_X86_ISA_1_V3, "x86-64-v3"); 4986 DumpBit(GNU_PROPERTY_X86_ISA_1_V4, "x86-64-v4"); 4987 if (PrData) 4988 OS << format("<unknown flags: 0x%x>", PrData); 4989 return OS.str(); 4990 } 4991 } 4992 4993 template <typename ELFT> 4994 static SmallVector<std::string, 4> getGNUPropertyList(ArrayRef<uint8_t> Arr) { 4995 using Elf_Word = typename ELFT::Word; 4996 4997 SmallVector<std::string, 4> Properties; 4998 while (Arr.size() >= 8) { 4999 uint32_t Type = *reinterpret_cast<const Elf_Word *>(Arr.data()); 5000 uint32_t DataSize = *reinterpret_cast<const Elf_Word *>(Arr.data() + 4); 5001 Arr = Arr.drop_front(8); 5002 5003 // Take padding size into account if present. 5004 uint64_t PaddedSize = alignTo(DataSize, sizeof(typename ELFT::uint)); 5005 std::string str; 5006 raw_string_ostream OS(str); 5007 if (Arr.size() < PaddedSize) { 5008 OS << format("<corrupt type (0x%x) datasz: 0x%x>", Type, DataSize); 5009 Properties.push_back(OS.str()); 5010 break; 5011 } 5012 Properties.push_back( 5013 getGNUProperty<ELFT>(Type, DataSize, Arr.take_front(PaddedSize))); 5014 Arr = Arr.drop_front(PaddedSize); 5015 } 5016 5017 if (!Arr.empty()) 5018 Properties.push_back("<corrupted GNU_PROPERTY_TYPE_0>"); 5019 5020 return Properties; 5021 } 5022 5023 struct GNUAbiTag { 5024 std::string OSName; 5025 std::string ABI; 5026 bool IsValid; 5027 }; 5028 5029 template <typename ELFT> static GNUAbiTag getGNUAbiTag(ArrayRef<uint8_t> Desc) { 5030 typedef typename ELFT::Word Elf_Word; 5031 5032 ArrayRef<Elf_Word> Words(reinterpret_cast<const Elf_Word *>(Desc.begin()), 5033 reinterpret_cast<const Elf_Word *>(Desc.end())); 5034 5035 if (Words.size() < 4) 5036 return {"", "", /*IsValid=*/false}; 5037 5038 static const char *OSNames[] = { 5039 "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable", "NaCl", 5040 }; 5041 StringRef OSName = "Unknown"; 5042 if (Words[0] < array_lengthof(OSNames)) 5043 OSName = OSNames[Words[0]]; 5044 uint32_t Major = Words[1], Minor = Words[2], Patch = Words[3]; 5045 std::string str; 5046 raw_string_ostream ABI(str); 5047 ABI << Major << "." << Minor << "." << Patch; 5048 return {std::string(OSName), ABI.str(), /*IsValid=*/true}; 5049 } 5050 5051 static std::string getGNUBuildId(ArrayRef<uint8_t> Desc) { 5052 std::string str; 5053 raw_string_ostream OS(str); 5054 for (uint8_t B : Desc) 5055 OS << format_hex_no_prefix(B, 2); 5056 return OS.str(); 5057 } 5058 5059 static StringRef getDescAsStringRef(ArrayRef<uint8_t> Desc) { 5060 return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size()); 5061 } 5062 5063 template <typename ELFT> 5064 static bool printGNUNote(raw_ostream &OS, uint32_t NoteType, 5065 ArrayRef<uint8_t> Desc) { 5066 // Return true if we were able to pretty-print the note, false otherwise. 5067 switch (NoteType) { 5068 default: 5069 return false; 5070 case ELF::NT_GNU_ABI_TAG: { 5071 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc); 5072 if (!AbiTag.IsValid) 5073 OS << " <corrupt GNU_ABI_TAG>"; 5074 else 5075 OS << " OS: " << AbiTag.OSName << ", ABI: " << AbiTag.ABI; 5076 break; 5077 } 5078 case ELF::NT_GNU_BUILD_ID: { 5079 OS << " Build ID: " << getGNUBuildId(Desc); 5080 break; 5081 } 5082 case ELF::NT_GNU_GOLD_VERSION: 5083 OS << " Version: " << getDescAsStringRef(Desc); 5084 break; 5085 case ELF::NT_GNU_PROPERTY_TYPE_0: 5086 OS << " Properties:"; 5087 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc)) 5088 OS << " " << Property << "\n"; 5089 break; 5090 } 5091 OS << '\n'; 5092 return true; 5093 } 5094 5095 using AndroidNoteProperties = std::vector<std::pair<StringRef, std::string>>; 5096 static AndroidNoteProperties getAndroidNoteProperties(uint32_t NoteType, 5097 ArrayRef<uint8_t> Desc) { 5098 AndroidNoteProperties Props; 5099 switch (NoteType) { 5100 case ELF::NT_ANDROID_TYPE_MEMTAG: 5101 if (Desc.empty()) { 5102 Props.emplace_back("Invalid .note.android.memtag", ""); 5103 return Props; 5104 } 5105 5106 switch (Desc[0] & NT_MEMTAG_LEVEL_MASK) { 5107 case NT_MEMTAG_LEVEL_NONE: 5108 Props.emplace_back("Tagging Mode", "NONE"); 5109 break; 5110 case NT_MEMTAG_LEVEL_ASYNC: 5111 Props.emplace_back("Tagging Mode", "ASYNC"); 5112 break; 5113 case NT_MEMTAG_LEVEL_SYNC: 5114 Props.emplace_back("Tagging Mode", "SYNC"); 5115 break; 5116 default: 5117 Props.emplace_back( 5118 "Tagging Mode", 5119 ("Unknown (" + Twine::utohexstr(Desc[0] & NT_MEMTAG_LEVEL_MASK) + ")") 5120 .str()); 5121 break; 5122 } 5123 Props.emplace_back("Heap", 5124 (Desc[0] & NT_MEMTAG_HEAP) ? "Enabled" : "Disabled"); 5125 Props.emplace_back("Stack", 5126 (Desc[0] & NT_MEMTAG_STACK) ? "Enabled" : "Disabled"); 5127 break; 5128 default: 5129 return Props; 5130 } 5131 return Props; 5132 } 5133 5134 static bool printAndroidNote(raw_ostream &OS, uint32_t NoteType, 5135 ArrayRef<uint8_t> Desc) { 5136 // Return true if we were able to pretty-print the note, false otherwise. 5137 AndroidNoteProperties Props = getAndroidNoteProperties(NoteType, Desc); 5138 if (Props.empty()) 5139 return false; 5140 for (const auto &KV : Props) 5141 OS << " " << KV.first << ": " << KV.second << '\n'; 5142 OS << '\n'; 5143 return true; 5144 } 5145 5146 template <typename ELFT> 5147 static bool printLLVMOMPOFFLOADNote(raw_ostream &OS, uint32_t NoteType, 5148 ArrayRef<uint8_t> Desc) { 5149 switch (NoteType) { 5150 default: 5151 return false; 5152 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION: 5153 OS << " Version: " << getDescAsStringRef(Desc); 5154 break; 5155 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER: 5156 OS << " Producer: " << getDescAsStringRef(Desc); 5157 break; 5158 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION: 5159 OS << " Producer version: " << getDescAsStringRef(Desc); 5160 break; 5161 } 5162 OS << '\n'; 5163 return true; 5164 } 5165 5166 const EnumEntry<unsigned> FreeBSDFeatureCtlFlags[] = { 5167 {"ASLR_DISABLE", NT_FREEBSD_FCTL_ASLR_DISABLE}, 5168 {"PROTMAX_DISABLE", NT_FREEBSD_FCTL_PROTMAX_DISABLE}, 5169 {"STKGAP_DISABLE", NT_FREEBSD_FCTL_STKGAP_DISABLE}, 5170 {"WXNEEDED", NT_FREEBSD_FCTL_WXNEEDED}, 5171 {"LA48", NT_FREEBSD_FCTL_LA48}, 5172 {"ASG_DISABLE", NT_FREEBSD_FCTL_ASG_DISABLE}, 5173 }; 5174 5175 struct FreeBSDNote { 5176 std::string Type; 5177 std::string Value; 5178 }; 5179 5180 template <typename ELFT> 5181 static Optional<FreeBSDNote> 5182 getFreeBSDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc, bool IsCore) { 5183 if (IsCore) 5184 return None; // No pretty-printing yet. 5185 switch (NoteType) { 5186 case ELF::NT_FREEBSD_ABI_TAG: 5187 if (Desc.size() != 4) 5188 return None; 5189 return FreeBSDNote{ 5190 "ABI tag", 5191 utostr(support::endian::read32<ELFT::TargetEndianness>(Desc.data()))}; 5192 case ELF::NT_FREEBSD_ARCH_TAG: 5193 return FreeBSDNote{"Arch tag", toStringRef(Desc).str()}; 5194 case ELF::NT_FREEBSD_FEATURE_CTL: { 5195 if (Desc.size() != 4) 5196 return None; 5197 unsigned Value = 5198 support::endian::read32<ELFT::TargetEndianness>(Desc.data()); 5199 std::string FlagsStr; 5200 raw_string_ostream OS(FlagsStr); 5201 printFlags(Value, makeArrayRef(FreeBSDFeatureCtlFlags), OS); 5202 if (OS.str().empty()) 5203 OS << "0x" << utohexstr(Value); 5204 else 5205 OS << "(0x" << utohexstr(Value) << ")"; 5206 return FreeBSDNote{"Feature flags", OS.str()}; 5207 } 5208 default: 5209 return None; 5210 } 5211 } 5212 5213 struct AMDNote { 5214 std::string Type; 5215 std::string Value; 5216 }; 5217 5218 template <typename ELFT> 5219 static AMDNote getAMDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) { 5220 switch (NoteType) { 5221 default: 5222 return {"", ""}; 5223 case ELF::NT_AMD_HSA_CODE_OBJECT_VERSION: { 5224 struct CodeObjectVersion { 5225 uint32_t MajorVersion; 5226 uint32_t MinorVersion; 5227 }; 5228 if (Desc.size() != sizeof(CodeObjectVersion)) 5229 return {"AMD HSA Code Object Version", 5230 "Invalid AMD HSA Code Object Version"}; 5231 std::string VersionString; 5232 raw_string_ostream StrOS(VersionString); 5233 auto Version = reinterpret_cast<const CodeObjectVersion *>(Desc.data()); 5234 StrOS << "[Major: " << Version->MajorVersion 5235 << ", Minor: " << Version->MinorVersion << "]"; 5236 return {"AMD HSA Code Object Version", VersionString}; 5237 } 5238 case ELF::NT_AMD_HSA_HSAIL: { 5239 struct HSAILProperties { 5240 uint32_t HSAILMajorVersion; 5241 uint32_t HSAILMinorVersion; 5242 uint8_t Profile; 5243 uint8_t MachineModel; 5244 uint8_t DefaultFloatRound; 5245 }; 5246 if (Desc.size() != sizeof(HSAILProperties)) 5247 return {"AMD HSA HSAIL Properties", "Invalid AMD HSA HSAIL Properties"}; 5248 auto Properties = reinterpret_cast<const HSAILProperties *>(Desc.data()); 5249 std::string HSAILPropetiesString; 5250 raw_string_ostream StrOS(HSAILPropetiesString); 5251 StrOS << "[HSAIL Major: " << Properties->HSAILMajorVersion 5252 << ", HSAIL Minor: " << Properties->HSAILMinorVersion 5253 << ", Profile: " << uint32_t(Properties->Profile) 5254 << ", Machine Model: " << uint32_t(Properties->MachineModel) 5255 << ", Default Float Round: " 5256 << uint32_t(Properties->DefaultFloatRound) << "]"; 5257 return {"AMD HSA HSAIL Properties", HSAILPropetiesString}; 5258 } 5259 case ELF::NT_AMD_HSA_ISA_VERSION: { 5260 struct IsaVersion { 5261 uint16_t VendorNameSize; 5262 uint16_t ArchitectureNameSize; 5263 uint32_t Major; 5264 uint32_t Minor; 5265 uint32_t Stepping; 5266 }; 5267 if (Desc.size() < sizeof(IsaVersion)) 5268 return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"}; 5269 auto Isa = reinterpret_cast<const IsaVersion *>(Desc.data()); 5270 if (Desc.size() < sizeof(IsaVersion) + 5271 Isa->VendorNameSize + Isa->ArchitectureNameSize || 5272 Isa->VendorNameSize == 0 || Isa->ArchitectureNameSize == 0) 5273 return {"AMD HSA ISA Version", "Invalid AMD HSA ISA Version"}; 5274 std::string IsaString; 5275 raw_string_ostream StrOS(IsaString); 5276 StrOS << "[Vendor: " 5277 << StringRef((const char*)Desc.data() + sizeof(IsaVersion), Isa->VendorNameSize - 1) 5278 << ", Architecture: " 5279 << StringRef((const char*)Desc.data() + sizeof(IsaVersion) + Isa->VendorNameSize, 5280 Isa->ArchitectureNameSize - 1) 5281 << ", Major: " << Isa->Major << ", Minor: " << Isa->Minor 5282 << ", Stepping: " << Isa->Stepping << "]"; 5283 return {"AMD HSA ISA Version", IsaString}; 5284 } 5285 case ELF::NT_AMD_HSA_METADATA: { 5286 if (Desc.size() == 0) 5287 return {"AMD HSA Metadata", ""}; 5288 return { 5289 "AMD HSA Metadata", 5290 std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size() - 1)}; 5291 } 5292 case ELF::NT_AMD_HSA_ISA_NAME: { 5293 if (Desc.size() == 0) 5294 return {"AMD HSA ISA Name", ""}; 5295 return { 5296 "AMD HSA ISA Name", 5297 std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())}; 5298 } 5299 case ELF::NT_AMD_PAL_METADATA: { 5300 struct PALMetadata { 5301 uint32_t Key; 5302 uint32_t Value; 5303 }; 5304 if (Desc.size() % sizeof(PALMetadata) != 0) 5305 return {"AMD PAL Metadata", "Invalid AMD PAL Metadata"}; 5306 auto Isa = reinterpret_cast<const PALMetadata *>(Desc.data()); 5307 std::string MetadataString; 5308 raw_string_ostream StrOS(MetadataString); 5309 for (size_t I = 0, E = Desc.size() / sizeof(PALMetadata); I < E; ++I) { 5310 StrOS << "[" << Isa[I].Key << ": " << Isa[I].Value << "]"; 5311 } 5312 return {"AMD PAL Metadata", MetadataString}; 5313 } 5314 } 5315 } 5316 5317 struct AMDGPUNote { 5318 std::string Type; 5319 std::string Value; 5320 }; 5321 5322 template <typename ELFT> 5323 static AMDGPUNote getAMDGPUNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) { 5324 switch (NoteType) { 5325 default: 5326 return {"", ""}; 5327 case ELF::NT_AMDGPU_METADATA: { 5328 StringRef MsgPackString = 5329 StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size()); 5330 msgpack::Document MsgPackDoc; 5331 if (!MsgPackDoc.readFromBlob(MsgPackString, /*Multi=*/false)) 5332 return {"", ""}; 5333 5334 AMDGPU::HSAMD::V3::MetadataVerifier Verifier(true); 5335 std::string MetadataString; 5336 if (!Verifier.verify(MsgPackDoc.getRoot())) 5337 MetadataString = "Invalid AMDGPU Metadata\n"; 5338 5339 raw_string_ostream StrOS(MetadataString); 5340 if (MsgPackDoc.getRoot().isScalar()) { 5341 // TODO: passing a scalar root to toYAML() asserts: 5342 // (PolymorphicTraits<T>::getKind(Val) != NodeKind::Scalar && 5343 // "plain scalar documents are not supported") 5344 // To avoid this crash we print the raw data instead. 5345 return {"", ""}; 5346 } 5347 MsgPackDoc.toYAML(StrOS); 5348 return {"AMDGPU Metadata", StrOS.str()}; 5349 } 5350 } 5351 } 5352 5353 struct CoreFileMapping { 5354 uint64_t Start, End, Offset; 5355 StringRef Filename; 5356 }; 5357 5358 struct CoreNote { 5359 uint64_t PageSize; 5360 std::vector<CoreFileMapping> Mappings; 5361 }; 5362 5363 static Expected<CoreNote> readCoreNote(DataExtractor Desc) { 5364 // Expected format of the NT_FILE note description: 5365 // 1. # of file mappings (call it N) 5366 // 2. Page size 5367 // 3. N (start, end, offset) triples 5368 // 4. N packed filenames (null delimited) 5369 // Each field is an Elf_Addr, except for filenames which are char* strings. 5370 5371 CoreNote Ret; 5372 const int Bytes = Desc.getAddressSize(); 5373 5374 if (!Desc.isValidOffsetForAddress(2)) 5375 return createError("the note of size 0x" + Twine::utohexstr(Desc.size()) + 5376 " is too short, expected at least 0x" + 5377 Twine::utohexstr(Bytes * 2)); 5378 if (Desc.getData().back() != 0) 5379 return createError("the note is not NUL terminated"); 5380 5381 uint64_t DescOffset = 0; 5382 uint64_t FileCount = Desc.getAddress(&DescOffset); 5383 Ret.PageSize = Desc.getAddress(&DescOffset); 5384 5385 if (!Desc.isValidOffsetForAddress(3 * FileCount * Bytes)) 5386 return createError("unable to read file mappings (found " + 5387 Twine(FileCount) + "): the note of size 0x" + 5388 Twine::utohexstr(Desc.size()) + " is too short"); 5389 5390 uint64_t FilenamesOffset = 0; 5391 DataExtractor Filenames( 5392 Desc.getData().drop_front(DescOffset + 3 * FileCount * Bytes), 5393 Desc.isLittleEndian(), Desc.getAddressSize()); 5394 5395 Ret.Mappings.resize(FileCount); 5396 size_t I = 0; 5397 for (CoreFileMapping &Mapping : Ret.Mappings) { 5398 ++I; 5399 if (!Filenames.isValidOffsetForDataOfSize(FilenamesOffset, 1)) 5400 return createError( 5401 "unable to read the file name for the mapping with index " + 5402 Twine(I) + ": the note of size 0x" + Twine::utohexstr(Desc.size()) + 5403 " is truncated"); 5404 Mapping.Start = Desc.getAddress(&DescOffset); 5405 Mapping.End = Desc.getAddress(&DescOffset); 5406 Mapping.Offset = Desc.getAddress(&DescOffset); 5407 Mapping.Filename = Filenames.getCStrRef(&FilenamesOffset); 5408 } 5409 5410 return Ret; 5411 } 5412 5413 template <typename ELFT> 5414 static void printCoreNote(raw_ostream &OS, const CoreNote &Note) { 5415 // Length of "0x<address>" string. 5416 const int FieldWidth = ELFT::Is64Bits ? 18 : 10; 5417 5418 OS << " Page size: " << format_decimal(Note.PageSize, 0) << '\n'; 5419 OS << " " << right_justify("Start", FieldWidth) << " " 5420 << right_justify("End", FieldWidth) << " " 5421 << right_justify("Page Offset", FieldWidth) << '\n'; 5422 for (const CoreFileMapping &Mapping : Note.Mappings) { 5423 OS << " " << format_hex(Mapping.Start, FieldWidth) << " " 5424 << format_hex(Mapping.End, FieldWidth) << " " 5425 << format_hex(Mapping.Offset, FieldWidth) << "\n " 5426 << Mapping.Filename << '\n'; 5427 } 5428 } 5429 5430 const NoteType GenericNoteTypes[] = { 5431 {ELF::NT_VERSION, "NT_VERSION (version)"}, 5432 {ELF::NT_ARCH, "NT_ARCH (architecture)"}, 5433 {ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN, "OPEN"}, 5434 {ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC, "func"}, 5435 }; 5436 5437 const NoteType GNUNoteTypes[] = { 5438 {ELF::NT_GNU_ABI_TAG, "NT_GNU_ABI_TAG (ABI version tag)"}, 5439 {ELF::NT_GNU_HWCAP, "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"}, 5440 {ELF::NT_GNU_BUILD_ID, "NT_GNU_BUILD_ID (unique build ID bitstring)"}, 5441 {ELF::NT_GNU_GOLD_VERSION, "NT_GNU_GOLD_VERSION (gold version)"}, 5442 {ELF::NT_GNU_PROPERTY_TYPE_0, "NT_GNU_PROPERTY_TYPE_0 (property note)"}, 5443 }; 5444 5445 const NoteType FreeBSDCoreNoteTypes[] = { 5446 {ELF::NT_FREEBSD_THRMISC, "NT_THRMISC (thrmisc structure)"}, 5447 {ELF::NT_FREEBSD_PROCSTAT_PROC, "NT_PROCSTAT_PROC (proc data)"}, 5448 {ELF::NT_FREEBSD_PROCSTAT_FILES, "NT_PROCSTAT_FILES (files data)"}, 5449 {ELF::NT_FREEBSD_PROCSTAT_VMMAP, "NT_PROCSTAT_VMMAP (vmmap data)"}, 5450 {ELF::NT_FREEBSD_PROCSTAT_GROUPS, "NT_PROCSTAT_GROUPS (groups data)"}, 5451 {ELF::NT_FREEBSD_PROCSTAT_UMASK, "NT_PROCSTAT_UMASK (umask data)"}, 5452 {ELF::NT_FREEBSD_PROCSTAT_RLIMIT, "NT_PROCSTAT_RLIMIT (rlimit data)"}, 5453 {ELF::NT_FREEBSD_PROCSTAT_OSREL, "NT_PROCSTAT_OSREL (osreldate data)"}, 5454 {ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS, 5455 "NT_PROCSTAT_PSSTRINGS (ps_strings data)"}, 5456 {ELF::NT_FREEBSD_PROCSTAT_AUXV, "NT_PROCSTAT_AUXV (auxv data)"}, 5457 }; 5458 5459 const NoteType FreeBSDNoteTypes[] = { 5460 {ELF::NT_FREEBSD_ABI_TAG, "NT_FREEBSD_ABI_TAG (ABI version tag)"}, 5461 {ELF::NT_FREEBSD_NOINIT_TAG, "NT_FREEBSD_NOINIT_TAG (no .init tag)"}, 5462 {ELF::NT_FREEBSD_ARCH_TAG, "NT_FREEBSD_ARCH_TAG (architecture tag)"}, 5463 {ELF::NT_FREEBSD_FEATURE_CTL, 5464 "NT_FREEBSD_FEATURE_CTL (FreeBSD feature control)"}, 5465 }; 5466 5467 const NoteType NetBSDCoreNoteTypes[] = { 5468 {ELF::NT_NETBSDCORE_PROCINFO, 5469 "NT_NETBSDCORE_PROCINFO (procinfo structure)"}, 5470 {ELF::NT_NETBSDCORE_AUXV, "NT_NETBSDCORE_AUXV (ELF auxiliary vector data)"}, 5471 {ELF::NT_NETBSDCORE_LWPSTATUS, "PT_LWPSTATUS (ptrace_lwpstatus structure)"}, 5472 }; 5473 5474 const NoteType OpenBSDCoreNoteTypes[] = { 5475 {ELF::NT_OPENBSD_PROCINFO, "NT_OPENBSD_PROCINFO (procinfo structure)"}, 5476 {ELF::NT_OPENBSD_AUXV, "NT_OPENBSD_AUXV (ELF auxiliary vector data)"}, 5477 {ELF::NT_OPENBSD_REGS, "NT_OPENBSD_REGS (regular registers)"}, 5478 {ELF::NT_OPENBSD_FPREGS, "NT_OPENBSD_FPREGS (floating point registers)"}, 5479 {ELF::NT_OPENBSD_WCOOKIE, "NT_OPENBSD_WCOOKIE (window cookie)"}, 5480 }; 5481 5482 const NoteType AMDNoteTypes[] = { 5483 {ELF::NT_AMD_HSA_CODE_OBJECT_VERSION, 5484 "NT_AMD_HSA_CODE_OBJECT_VERSION (AMD HSA Code Object Version)"}, 5485 {ELF::NT_AMD_HSA_HSAIL, "NT_AMD_HSA_HSAIL (AMD HSA HSAIL Properties)"}, 5486 {ELF::NT_AMD_HSA_ISA_VERSION, "NT_AMD_HSA_ISA_VERSION (AMD HSA ISA Version)"}, 5487 {ELF::NT_AMD_HSA_METADATA, "NT_AMD_HSA_METADATA (AMD HSA Metadata)"}, 5488 {ELF::NT_AMD_HSA_ISA_NAME, "NT_AMD_HSA_ISA_NAME (AMD HSA ISA Name)"}, 5489 {ELF::NT_AMD_PAL_METADATA, "NT_AMD_PAL_METADATA (AMD PAL Metadata)"}, 5490 }; 5491 5492 const NoteType AMDGPUNoteTypes[] = { 5493 {ELF::NT_AMDGPU_METADATA, "NT_AMDGPU_METADATA (AMDGPU Metadata)"}, 5494 }; 5495 5496 const NoteType LLVMOMPOFFLOADNoteTypes[] = { 5497 {ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION, 5498 "NT_LLVM_OPENMP_OFFLOAD_VERSION (image format version)"}, 5499 {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER, 5500 "NT_LLVM_OPENMP_OFFLOAD_PRODUCER (producing toolchain)"}, 5501 {ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION, 5502 "NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION (producing toolchain version)"}, 5503 }; 5504 5505 const NoteType AndroidNoteTypes[] = { 5506 {ELF::NT_ANDROID_TYPE_IDENT, "NT_ANDROID_TYPE_IDENT"}, 5507 {ELF::NT_ANDROID_TYPE_KUSER, "NT_ANDROID_TYPE_KUSER"}, 5508 {ELF::NT_ANDROID_TYPE_MEMTAG, 5509 "NT_ANDROID_TYPE_MEMTAG (Android memory tagging information)"}, 5510 }; 5511 5512 const NoteType CoreNoteTypes[] = { 5513 {ELF::NT_PRSTATUS, "NT_PRSTATUS (prstatus structure)"}, 5514 {ELF::NT_FPREGSET, "NT_FPREGSET (floating point registers)"}, 5515 {ELF::NT_PRPSINFO, "NT_PRPSINFO (prpsinfo structure)"}, 5516 {ELF::NT_TASKSTRUCT, "NT_TASKSTRUCT (task structure)"}, 5517 {ELF::NT_AUXV, "NT_AUXV (auxiliary vector)"}, 5518 {ELF::NT_PSTATUS, "NT_PSTATUS (pstatus structure)"}, 5519 {ELF::NT_FPREGS, "NT_FPREGS (floating point registers)"}, 5520 {ELF::NT_PSINFO, "NT_PSINFO (psinfo structure)"}, 5521 {ELF::NT_LWPSTATUS, "NT_LWPSTATUS (lwpstatus_t structure)"}, 5522 {ELF::NT_LWPSINFO, "NT_LWPSINFO (lwpsinfo_t structure)"}, 5523 {ELF::NT_WIN32PSTATUS, "NT_WIN32PSTATUS (win32_pstatus structure)"}, 5524 5525 {ELF::NT_PPC_VMX, "NT_PPC_VMX (ppc Altivec registers)"}, 5526 {ELF::NT_PPC_VSX, "NT_PPC_VSX (ppc VSX registers)"}, 5527 {ELF::NT_PPC_TAR, "NT_PPC_TAR (ppc TAR register)"}, 5528 {ELF::NT_PPC_PPR, "NT_PPC_PPR (ppc PPR register)"}, 5529 {ELF::NT_PPC_DSCR, "NT_PPC_DSCR (ppc DSCR register)"}, 5530 {ELF::NT_PPC_EBB, "NT_PPC_EBB (ppc EBB registers)"}, 5531 {ELF::NT_PPC_PMU, "NT_PPC_PMU (ppc PMU registers)"}, 5532 {ELF::NT_PPC_TM_CGPR, "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"}, 5533 {ELF::NT_PPC_TM_CFPR, 5534 "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"}, 5535 {ELF::NT_PPC_TM_CVMX, 5536 "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"}, 5537 {ELF::NT_PPC_TM_CVSX, "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"}, 5538 {ELF::NT_PPC_TM_SPR, "NT_PPC_TM_SPR (ppc TM special purpose registers)"}, 5539 {ELF::NT_PPC_TM_CTAR, "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"}, 5540 {ELF::NT_PPC_TM_CPPR, "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"}, 5541 {ELF::NT_PPC_TM_CDSCR, "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"}, 5542 5543 {ELF::NT_386_TLS, "NT_386_TLS (x86 TLS information)"}, 5544 {ELF::NT_386_IOPERM, "NT_386_IOPERM (x86 I/O permissions)"}, 5545 {ELF::NT_X86_XSTATE, "NT_X86_XSTATE (x86 XSAVE extended state)"}, 5546 5547 {ELF::NT_S390_HIGH_GPRS, "NT_S390_HIGH_GPRS (s390 upper register halves)"}, 5548 {ELF::NT_S390_TIMER, "NT_S390_TIMER (s390 timer register)"}, 5549 {ELF::NT_S390_TODCMP, "NT_S390_TODCMP (s390 TOD comparator register)"}, 5550 {ELF::NT_S390_TODPREG, "NT_S390_TODPREG (s390 TOD programmable register)"}, 5551 {ELF::NT_S390_CTRS, "NT_S390_CTRS (s390 control registers)"}, 5552 {ELF::NT_S390_PREFIX, "NT_S390_PREFIX (s390 prefix register)"}, 5553 {ELF::NT_S390_LAST_BREAK, 5554 "NT_S390_LAST_BREAK (s390 last breaking event address)"}, 5555 {ELF::NT_S390_SYSTEM_CALL, 5556 "NT_S390_SYSTEM_CALL (s390 system call restart data)"}, 5557 {ELF::NT_S390_TDB, "NT_S390_TDB (s390 transaction diagnostic block)"}, 5558 {ELF::NT_S390_VXRS_LOW, 5559 "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"}, 5560 {ELF::NT_S390_VXRS_HIGH, "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"}, 5561 {ELF::NT_S390_GS_CB, "NT_S390_GS_CB (s390 guarded-storage registers)"}, 5562 {ELF::NT_S390_GS_BC, 5563 "NT_S390_GS_BC (s390 guarded-storage broadcast control)"}, 5564 5565 {ELF::NT_ARM_VFP, "NT_ARM_VFP (arm VFP registers)"}, 5566 {ELF::NT_ARM_TLS, "NT_ARM_TLS (AArch TLS registers)"}, 5567 {ELF::NT_ARM_HW_BREAK, 5568 "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"}, 5569 {ELF::NT_ARM_HW_WATCH, 5570 "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"}, 5571 5572 {ELF::NT_FILE, "NT_FILE (mapped files)"}, 5573 {ELF::NT_PRXFPREG, "NT_PRXFPREG (user_xfpregs structure)"}, 5574 {ELF::NT_SIGINFO, "NT_SIGINFO (siginfo_t data)"}, 5575 }; 5576 5577 template <class ELFT> 5578 StringRef getNoteTypeName(const typename ELFT::Note &Note, unsigned ELFType) { 5579 uint32_t Type = Note.getType(); 5580 auto FindNote = [&](ArrayRef<NoteType> V) -> StringRef { 5581 for (const NoteType &N : V) 5582 if (N.ID == Type) 5583 return N.Name; 5584 return ""; 5585 }; 5586 5587 StringRef Name = Note.getName(); 5588 if (Name == "GNU") 5589 return FindNote(GNUNoteTypes); 5590 if (Name == "FreeBSD") { 5591 if (ELFType == ELF::ET_CORE) { 5592 // FreeBSD also places the generic core notes in the FreeBSD namespace. 5593 StringRef Result = FindNote(FreeBSDCoreNoteTypes); 5594 if (!Result.empty()) 5595 return Result; 5596 return FindNote(CoreNoteTypes); 5597 } else { 5598 return FindNote(FreeBSDNoteTypes); 5599 } 5600 } 5601 if (ELFType == ELF::ET_CORE && Name.startswith("NetBSD-CORE")) { 5602 StringRef Result = FindNote(NetBSDCoreNoteTypes); 5603 if (!Result.empty()) 5604 return Result; 5605 return FindNote(CoreNoteTypes); 5606 } 5607 if (ELFType == ELF::ET_CORE && Name.startswith("OpenBSD")) { 5608 // OpenBSD also places the generic core notes in the OpenBSD namespace. 5609 StringRef Result = FindNote(OpenBSDCoreNoteTypes); 5610 if (!Result.empty()) 5611 return Result; 5612 return FindNote(CoreNoteTypes); 5613 } 5614 if (Name == "AMD") 5615 return FindNote(AMDNoteTypes); 5616 if (Name == "AMDGPU") 5617 return FindNote(AMDGPUNoteTypes); 5618 if (Name == "LLVMOMPOFFLOAD") 5619 return FindNote(LLVMOMPOFFLOADNoteTypes); 5620 if (Name == "Android") 5621 return FindNote(AndroidNoteTypes); 5622 5623 if (ELFType == ELF::ET_CORE) 5624 return FindNote(CoreNoteTypes); 5625 return FindNote(GenericNoteTypes); 5626 } 5627 5628 template <class ELFT> 5629 static void printNotesHelper( 5630 const ELFDumper<ELFT> &Dumper, 5631 llvm::function_ref<void(Optional<StringRef>, typename ELFT::Off, 5632 typename ELFT::Addr)> 5633 StartNotesFn, 5634 llvm::function_ref<Error(const typename ELFT::Note &, bool)> ProcessNoteFn, 5635 llvm::function_ref<void()> FinishNotesFn) { 5636 const ELFFile<ELFT> &Obj = Dumper.getElfObject().getELFFile(); 5637 bool IsCoreFile = Obj.getHeader().e_type == ELF::ET_CORE; 5638 5639 ArrayRef<typename ELFT::Shdr> Sections = cantFail(Obj.sections()); 5640 if (!IsCoreFile && !Sections.empty()) { 5641 for (const typename ELFT::Shdr &S : Sections) { 5642 if (S.sh_type != SHT_NOTE) 5643 continue; 5644 StartNotesFn(expectedToOptional(Obj.getSectionName(S)), S.sh_offset, 5645 S.sh_size); 5646 Error Err = Error::success(); 5647 size_t I = 0; 5648 for (const typename ELFT::Note Note : Obj.notes(S, Err)) { 5649 if (Error E = ProcessNoteFn(Note, IsCoreFile)) 5650 Dumper.reportUniqueWarning( 5651 "unable to read note with index " + Twine(I) + " from the " + 5652 describe(Obj, S) + ": " + toString(std::move(E))); 5653 ++I; 5654 } 5655 if (Err) 5656 Dumper.reportUniqueWarning("unable to read notes from the " + 5657 describe(Obj, S) + ": " + 5658 toString(std::move(Err))); 5659 FinishNotesFn(); 5660 } 5661 return; 5662 } 5663 5664 Expected<ArrayRef<typename ELFT::Phdr>> PhdrsOrErr = Obj.program_headers(); 5665 if (!PhdrsOrErr) { 5666 Dumper.reportUniqueWarning( 5667 "unable to read program headers to locate the PT_NOTE segment: " + 5668 toString(PhdrsOrErr.takeError())); 5669 return; 5670 } 5671 5672 for (size_t I = 0, E = (*PhdrsOrErr).size(); I != E; ++I) { 5673 const typename ELFT::Phdr &P = (*PhdrsOrErr)[I]; 5674 if (P.p_type != PT_NOTE) 5675 continue; 5676 StartNotesFn(/*SecName=*/None, P.p_offset, P.p_filesz); 5677 Error Err = Error::success(); 5678 size_t Index = 0; 5679 for (const typename ELFT::Note Note : Obj.notes(P, Err)) { 5680 if (Error E = ProcessNoteFn(Note, IsCoreFile)) 5681 Dumper.reportUniqueWarning("unable to read note with index " + 5682 Twine(Index) + 5683 " from the PT_NOTE segment with index " + 5684 Twine(I) + ": " + toString(std::move(E))); 5685 ++Index; 5686 } 5687 if (Err) 5688 Dumper.reportUniqueWarning( 5689 "unable to read notes from the PT_NOTE segment with index " + 5690 Twine(I) + ": " + toString(std::move(Err))); 5691 FinishNotesFn(); 5692 } 5693 } 5694 5695 template <class ELFT> void GNUELFDumper<ELFT>::printNotes() { 5696 bool IsFirstHeader = true; 5697 auto PrintHeader = [&](Optional<StringRef> SecName, 5698 const typename ELFT::Off Offset, 5699 const typename ELFT::Addr Size) { 5700 // Print a newline between notes sections to match GNU readelf. 5701 if (!IsFirstHeader) { 5702 OS << '\n'; 5703 } else { 5704 IsFirstHeader = false; 5705 } 5706 5707 OS << "Displaying notes found "; 5708 5709 if (SecName) 5710 OS << "in: " << *SecName << "\n"; 5711 else 5712 OS << "at file offset " << format_hex(Offset, 10) << " with length " 5713 << format_hex(Size, 10) << ":\n"; 5714 5715 OS << " Owner Data size \tDescription\n"; 5716 }; 5717 5718 auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error { 5719 StringRef Name = Note.getName(); 5720 ArrayRef<uint8_t> Descriptor = Note.getDesc(); 5721 Elf_Word Type = Note.getType(); 5722 5723 // Print the note owner/type. 5724 OS << " " << left_justify(Name, 20) << ' ' 5725 << format_hex(Descriptor.size(), 10) << '\t'; 5726 5727 StringRef NoteType = 5728 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type); 5729 if (!NoteType.empty()) 5730 OS << NoteType << '\n'; 5731 else 5732 OS << "Unknown note type: (" << format_hex(Type, 10) << ")\n"; 5733 5734 // Print the description, or fallback to printing raw bytes for unknown 5735 // owners/if we fail to pretty-print the contents. 5736 if (Name == "GNU") { 5737 if (printGNUNote<ELFT>(OS, Type, Descriptor)) 5738 return Error::success(); 5739 } else if (Name == "FreeBSD") { 5740 if (Optional<FreeBSDNote> N = 5741 getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) { 5742 OS << " " << N->Type << ": " << N->Value << '\n'; 5743 return Error::success(); 5744 } 5745 } else if (Name == "AMD") { 5746 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor); 5747 if (!N.Type.empty()) { 5748 OS << " " << N.Type << ":\n " << N.Value << '\n'; 5749 return Error::success(); 5750 } 5751 } else if (Name == "AMDGPU") { 5752 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor); 5753 if (!N.Type.empty()) { 5754 OS << " " << N.Type << ":\n " << N.Value << '\n'; 5755 return Error::success(); 5756 } 5757 } else if (Name == "LLVMOMPOFFLOAD") { 5758 if (printLLVMOMPOFFLOADNote<ELFT>(OS, Type, Descriptor)) 5759 return Error::success(); 5760 } else if (Name == "CORE") { 5761 if (Type == ELF::NT_FILE) { 5762 DataExtractor DescExtractor(Descriptor, 5763 ELFT::TargetEndianness == support::little, 5764 sizeof(Elf_Addr)); 5765 if (Expected<CoreNote> NoteOrErr = readCoreNote(DescExtractor)) { 5766 printCoreNote<ELFT>(OS, *NoteOrErr); 5767 return Error::success(); 5768 } else { 5769 return NoteOrErr.takeError(); 5770 } 5771 } 5772 } else if (Name == "Android") { 5773 if (printAndroidNote(OS, Type, Descriptor)) 5774 return Error::success(); 5775 } 5776 if (!Descriptor.empty()) { 5777 OS << " description data:"; 5778 for (uint8_t B : Descriptor) 5779 OS << " " << format("%02x", B); 5780 OS << '\n'; 5781 } 5782 return Error::success(); 5783 }; 5784 5785 printNotesHelper(*this, PrintHeader, ProcessNote, []() {}); 5786 } 5787 5788 template <class ELFT> void GNUELFDumper<ELFT>::printELFLinkerOptions() { 5789 OS << "printELFLinkerOptions not implemented!\n"; 5790 } 5791 5792 template <class ELFT> 5793 void ELFDumper<ELFT>::printDependentLibsHelper( 5794 function_ref<void(const Elf_Shdr &)> OnSectionStart, 5795 function_ref<void(StringRef, uint64_t)> OnLibEntry) { 5796 auto Warn = [this](unsigned SecNdx, StringRef Msg) { 5797 this->reportUniqueWarning("SHT_LLVM_DEPENDENT_LIBRARIES section at index " + 5798 Twine(SecNdx) + " is broken: " + Msg); 5799 }; 5800 5801 unsigned I = -1; 5802 for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) { 5803 ++I; 5804 if (Shdr.sh_type != ELF::SHT_LLVM_DEPENDENT_LIBRARIES) 5805 continue; 5806 5807 OnSectionStart(Shdr); 5808 5809 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Shdr); 5810 if (!ContentsOrErr) { 5811 Warn(I, toString(ContentsOrErr.takeError())); 5812 continue; 5813 } 5814 5815 ArrayRef<uint8_t> Contents = *ContentsOrErr; 5816 if (!Contents.empty() && Contents.back() != 0) { 5817 Warn(I, "the content is not null-terminated"); 5818 continue; 5819 } 5820 5821 for (const uint8_t *I = Contents.begin(), *E = Contents.end(); I < E;) { 5822 StringRef Lib((const char *)I); 5823 OnLibEntry(Lib, I - Contents.begin()); 5824 I += Lib.size() + 1; 5825 } 5826 } 5827 } 5828 5829 template <class ELFT> 5830 void ELFDumper<ELFT>::forEachRelocationDo( 5831 const Elf_Shdr &Sec, bool RawRelr, 5832 llvm::function_ref<void(const Relocation<ELFT> &, unsigned, 5833 const Elf_Shdr &, const Elf_Shdr *)> 5834 RelRelaFn, 5835 llvm::function_ref<void(const Elf_Relr &)> RelrFn) { 5836 auto Warn = [&](Error &&E, 5837 const Twine &Prefix = "unable to read relocations from") { 5838 this->reportUniqueWarning(Prefix + " " + describe(Sec) + ": " + 5839 toString(std::move(E))); 5840 }; 5841 5842 // SHT_RELR/SHT_ANDROID_RELR sections do not have an associated symbol table. 5843 // For them we should not treat the value of the sh_link field as an index of 5844 // a symbol table. 5845 const Elf_Shdr *SymTab; 5846 if (Sec.sh_type != ELF::SHT_RELR && Sec.sh_type != ELF::SHT_ANDROID_RELR) { 5847 Expected<const Elf_Shdr *> SymTabOrErr = Obj.getSection(Sec.sh_link); 5848 if (!SymTabOrErr) { 5849 Warn(SymTabOrErr.takeError(), "unable to locate a symbol table for"); 5850 return; 5851 } 5852 SymTab = *SymTabOrErr; 5853 } 5854 5855 unsigned RelNdx = 0; 5856 const bool IsMips64EL = this->Obj.isMips64EL(); 5857 switch (Sec.sh_type) { 5858 case ELF::SHT_REL: 5859 if (Expected<Elf_Rel_Range> RangeOrErr = Obj.rels(Sec)) { 5860 for (const Elf_Rel &R : *RangeOrErr) 5861 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab); 5862 } else { 5863 Warn(RangeOrErr.takeError()); 5864 } 5865 break; 5866 case ELF::SHT_RELA: 5867 if (Expected<Elf_Rela_Range> RangeOrErr = Obj.relas(Sec)) { 5868 for (const Elf_Rela &R : *RangeOrErr) 5869 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab); 5870 } else { 5871 Warn(RangeOrErr.takeError()); 5872 } 5873 break; 5874 case ELF::SHT_RELR: 5875 case ELF::SHT_ANDROID_RELR: { 5876 Expected<Elf_Relr_Range> RangeOrErr = Obj.relrs(Sec); 5877 if (!RangeOrErr) { 5878 Warn(RangeOrErr.takeError()); 5879 break; 5880 } 5881 if (RawRelr) { 5882 for (const Elf_Relr &R : *RangeOrErr) 5883 RelrFn(R); 5884 break; 5885 } 5886 5887 for (const Elf_Rel &R : Obj.decode_relrs(*RangeOrErr)) 5888 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, 5889 /*SymTab=*/nullptr); 5890 break; 5891 } 5892 case ELF::SHT_ANDROID_REL: 5893 case ELF::SHT_ANDROID_RELA: 5894 if (Expected<std::vector<Elf_Rela>> RelasOrErr = Obj.android_relas(Sec)) { 5895 for (const Elf_Rela &R : *RelasOrErr) 5896 RelRelaFn(Relocation<ELFT>(R, IsMips64EL), RelNdx++, Sec, SymTab); 5897 } else { 5898 Warn(RelasOrErr.takeError()); 5899 } 5900 break; 5901 } 5902 } 5903 5904 template <class ELFT> 5905 StringRef ELFDumper<ELFT>::getPrintableSectionName(const Elf_Shdr &Sec) const { 5906 StringRef Name = "<?>"; 5907 if (Expected<StringRef> SecNameOrErr = 5908 Obj.getSectionName(Sec, this->WarningHandler)) 5909 Name = *SecNameOrErr; 5910 else 5911 this->reportUniqueWarning("unable to get the name of " + describe(Sec) + 5912 ": " + toString(SecNameOrErr.takeError())); 5913 return Name; 5914 } 5915 5916 template <class ELFT> void GNUELFDumper<ELFT>::printDependentLibs() { 5917 bool SectionStarted = false; 5918 struct NameOffset { 5919 StringRef Name; 5920 uint64_t Offset; 5921 }; 5922 std::vector<NameOffset> SecEntries; 5923 NameOffset Current; 5924 auto PrintSection = [&]() { 5925 OS << "Dependent libraries section " << Current.Name << " at offset " 5926 << format_hex(Current.Offset, 1) << " contains " << SecEntries.size() 5927 << " entries:\n"; 5928 for (NameOffset Entry : SecEntries) 5929 OS << " [" << format("%6" PRIx64, Entry.Offset) << "] " << Entry.Name 5930 << "\n"; 5931 OS << "\n"; 5932 SecEntries.clear(); 5933 }; 5934 5935 auto OnSectionStart = [&](const Elf_Shdr &Shdr) { 5936 if (SectionStarted) 5937 PrintSection(); 5938 SectionStarted = true; 5939 Current.Offset = Shdr.sh_offset; 5940 Current.Name = this->getPrintableSectionName(Shdr); 5941 }; 5942 auto OnLibEntry = [&](StringRef Lib, uint64_t Offset) { 5943 SecEntries.push_back(NameOffset{Lib, Offset}); 5944 }; 5945 5946 this->printDependentLibsHelper(OnSectionStart, OnLibEntry); 5947 if (SectionStarted) 5948 PrintSection(); 5949 } 5950 5951 template <class ELFT> 5952 SmallVector<uint32_t> ELFDumper<ELFT>::getSymbolIndexesForFunctionAddress( 5953 uint64_t SymValue, Optional<const Elf_Shdr *> FunctionSec) { 5954 SmallVector<uint32_t> SymbolIndexes; 5955 if (!this->AddressToIndexMap) { 5956 // Populate the address to index map upon the first invocation of this 5957 // function. 5958 this->AddressToIndexMap.emplace(); 5959 if (this->DotSymtabSec) { 5960 if (Expected<Elf_Sym_Range> SymsOrError = 5961 Obj.symbols(this->DotSymtabSec)) { 5962 uint32_t Index = (uint32_t)-1; 5963 for (const Elf_Sym &Sym : *SymsOrError) { 5964 ++Index; 5965 5966 if (Sym.st_shndx == ELF::SHN_UNDEF || Sym.getType() != ELF::STT_FUNC) 5967 continue; 5968 5969 Expected<uint64_t> SymAddrOrErr = 5970 ObjF.toSymbolRef(this->DotSymtabSec, Index).getAddress(); 5971 if (!SymAddrOrErr) { 5972 std::string Name = this->getStaticSymbolName(Index); 5973 reportUniqueWarning("unable to get address of symbol '" + Name + 5974 "': " + toString(SymAddrOrErr.takeError())); 5975 return SymbolIndexes; 5976 } 5977 5978 (*this->AddressToIndexMap)[*SymAddrOrErr].push_back(Index); 5979 } 5980 } else { 5981 reportUniqueWarning("unable to read the symbol table: " + 5982 toString(SymsOrError.takeError())); 5983 } 5984 } 5985 } 5986 5987 auto Symbols = this->AddressToIndexMap->find(SymValue); 5988 if (Symbols == this->AddressToIndexMap->end()) 5989 return SymbolIndexes; 5990 5991 for (uint32_t Index : Symbols->second) { 5992 // Check if the symbol is in the right section. FunctionSec == None 5993 // means "any section". 5994 if (FunctionSec) { 5995 const Elf_Sym &Sym = *cantFail(Obj.getSymbol(this->DotSymtabSec, Index)); 5996 if (Expected<const Elf_Shdr *> SecOrErr = 5997 Obj.getSection(Sym, this->DotSymtabSec, 5998 this->getShndxTable(this->DotSymtabSec))) { 5999 if (*FunctionSec != *SecOrErr) 6000 continue; 6001 } else { 6002 std::string Name = this->getStaticSymbolName(Index); 6003 // Note: it is impossible to trigger this error currently, it is 6004 // untested. 6005 reportUniqueWarning("unable to get section of symbol '" + Name + 6006 "': " + toString(SecOrErr.takeError())); 6007 return SymbolIndexes; 6008 } 6009 } 6010 6011 SymbolIndexes.push_back(Index); 6012 } 6013 6014 return SymbolIndexes; 6015 } 6016 6017 template <class ELFT> 6018 bool ELFDumper<ELFT>::printFunctionStackSize( 6019 uint64_t SymValue, Optional<const Elf_Shdr *> FunctionSec, 6020 const Elf_Shdr &StackSizeSec, DataExtractor Data, uint64_t *Offset) { 6021 SmallVector<uint32_t> FuncSymIndexes = 6022 this->getSymbolIndexesForFunctionAddress(SymValue, FunctionSec); 6023 if (FuncSymIndexes.empty()) 6024 reportUniqueWarning( 6025 "could not identify function symbol for stack size entry in " + 6026 describe(StackSizeSec)); 6027 6028 // Extract the size. The expectation is that Offset is pointing to the right 6029 // place, i.e. past the function address. 6030 Error Err = Error::success(); 6031 uint64_t StackSize = Data.getULEB128(Offset, &Err); 6032 if (Err) { 6033 reportUniqueWarning("could not extract a valid stack size from " + 6034 describe(StackSizeSec) + ": " + 6035 toString(std::move(Err))); 6036 return false; 6037 } 6038 6039 if (FuncSymIndexes.empty()) { 6040 printStackSizeEntry(StackSize, {"?"}); 6041 } else { 6042 SmallVector<std::string> FuncSymNames; 6043 for (uint32_t Index : FuncSymIndexes) 6044 FuncSymNames.push_back(this->getStaticSymbolName(Index)); 6045 printStackSizeEntry(StackSize, FuncSymNames); 6046 } 6047 6048 return true; 6049 } 6050 6051 template <class ELFT> 6052 void GNUELFDumper<ELFT>::printStackSizeEntry(uint64_t Size, 6053 ArrayRef<std::string> FuncNames) { 6054 OS.PadToColumn(2); 6055 OS << format_decimal(Size, 11); 6056 OS.PadToColumn(18); 6057 6058 OS << join(FuncNames.begin(), FuncNames.end(), ", ") << "\n"; 6059 } 6060 6061 template <class ELFT> 6062 void ELFDumper<ELFT>::printStackSize(const Relocation<ELFT> &R, 6063 const Elf_Shdr &RelocSec, unsigned Ndx, 6064 const Elf_Shdr *SymTab, 6065 const Elf_Shdr *FunctionSec, 6066 const Elf_Shdr &StackSizeSec, 6067 const RelocationResolver &Resolver, 6068 DataExtractor Data) { 6069 // This function ignores potentially erroneous input, unless it is directly 6070 // related to stack size reporting. 6071 const Elf_Sym *Sym = nullptr; 6072 Expected<RelSymbol<ELFT>> TargetOrErr = this->getRelocationTarget(R, SymTab); 6073 if (!TargetOrErr) 6074 reportUniqueWarning("unable to get the target of relocation with index " + 6075 Twine(Ndx) + " in " + describe(RelocSec) + ": " + 6076 toString(TargetOrErr.takeError())); 6077 else 6078 Sym = TargetOrErr->Sym; 6079 6080 uint64_t RelocSymValue = 0; 6081 if (Sym) { 6082 Expected<const Elf_Shdr *> SectionOrErr = 6083 this->Obj.getSection(*Sym, SymTab, this->getShndxTable(SymTab)); 6084 if (!SectionOrErr) { 6085 reportUniqueWarning( 6086 "cannot identify the section for relocation symbol '" + 6087 (*TargetOrErr).Name + "': " + toString(SectionOrErr.takeError())); 6088 } else if (*SectionOrErr != FunctionSec) { 6089 reportUniqueWarning("relocation symbol '" + (*TargetOrErr).Name + 6090 "' is not in the expected section"); 6091 // Pretend that the symbol is in the correct section and report its 6092 // stack size anyway. 6093 FunctionSec = *SectionOrErr; 6094 } 6095 6096 RelocSymValue = Sym->st_value; 6097 } 6098 6099 uint64_t Offset = R.Offset; 6100 if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) { 6101 reportUniqueWarning("found invalid relocation offset (0x" + 6102 Twine::utohexstr(Offset) + ") into " + 6103 describe(StackSizeSec) + 6104 " while trying to extract a stack size entry"); 6105 return; 6106 } 6107 6108 uint64_t SymValue = Resolver(R.Type, Offset, RelocSymValue, 6109 Data.getAddress(&Offset), R.Addend.value_or(0)); 6110 this->printFunctionStackSize(SymValue, FunctionSec, StackSizeSec, Data, 6111 &Offset); 6112 } 6113 6114 template <class ELFT> 6115 void ELFDumper<ELFT>::printNonRelocatableStackSizes( 6116 std::function<void()> PrintHeader) { 6117 // This function ignores potentially erroneous input, unless it is directly 6118 // related to stack size reporting. 6119 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) { 6120 if (this->getPrintableSectionName(Sec) != ".stack_sizes") 6121 continue; 6122 PrintHeader(); 6123 ArrayRef<uint8_t> Contents = 6124 unwrapOrError(this->FileName, Obj.getSectionContents(Sec)); 6125 DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr)); 6126 uint64_t Offset = 0; 6127 while (Offset < Contents.size()) { 6128 // The function address is followed by a ULEB representing the stack 6129 // size. Check for an extra byte before we try to process the entry. 6130 if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) { 6131 reportUniqueWarning( 6132 describe(Sec) + 6133 " ended while trying to extract a stack size entry"); 6134 break; 6135 } 6136 uint64_t SymValue = Data.getAddress(&Offset); 6137 if (!printFunctionStackSize(SymValue, /*FunctionSec=*/None, Sec, Data, 6138 &Offset)) 6139 break; 6140 } 6141 } 6142 } 6143 6144 template <class ELFT> 6145 void ELFDumper<ELFT>::getSectionAndRelocations( 6146 std::function<bool(const Elf_Shdr &)> IsMatch, 6147 llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> &SecToRelocMap) { 6148 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) { 6149 if (IsMatch(Sec)) 6150 if (SecToRelocMap.insert(std::make_pair(&Sec, (const Elf_Shdr *)nullptr)) 6151 .second) 6152 continue; 6153 6154 if (Sec.sh_type != ELF::SHT_RELA && Sec.sh_type != ELF::SHT_REL) 6155 continue; 6156 6157 Expected<const Elf_Shdr *> RelSecOrErr = Obj.getSection(Sec.sh_info); 6158 if (!RelSecOrErr) { 6159 reportUniqueWarning(describe(Sec) + 6160 ": failed to get a relocated section: " + 6161 toString(RelSecOrErr.takeError())); 6162 continue; 6163 } 6164 const Elf_Shdr *ContentsSec = *RelSecOrErr; 6165 if (IsMatch(*ContentsSec)) 6166 SecToRelocMap[ContentsSec] = &Sec; 6167 } 6168 } 6169 6170 template <class ELFT> 6171 void ELFDumper<ELFT>::printRelocatableStackSizes( 6172 std::function<void()> PrintHeader) { 6173 // Build a map between stack size sections and their corresponding relocation 6174 // sections. 6175 llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> StackSizeRelocMap; 6176 auto IsMatch = [&](const Elf_Shdr &Sec) -> bool { 6177 StringRef SectionName; 6178 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec)) 6179 SectionName = *NameOrErr; 6180 else 6181 consumeError(NameOrErr.takeError()); 6182 6183 return SectionName == ".stack_sizes"; 6184 }; 6185 getSectionAndRelocations(IsMatch, StackSizeRelocMap); 6186 6187 for (const auto &StackSizeMapEntry : StackSizeRelocMap) { 6188 PrintHeader(); 6189 const Elf_Shdr *StackSizesELFSec = StackSizeMapEntry.first; 6190 const Elf_Shdr *RelocSec = StackSizeMapEntry.second; 6191 6192 // Warn about stack size sections without a relocation section. 6193 if (!RelocSec) { 6194 reportWarning(createError(".stack_sizes (" + describe(*StackSizesELFSec) + 6195 ") does not have a corresponding " 6196 "relocation section"), 6197 FileName); 6198 continue; 6199 } 6200 6201 // A .stack_sizes section header's sh_link field is supposed to point 6202 // to the section that contains the functions whose stack sizes are 6203 // described in it. 6204 const Elf_Shdr *FunctionSec = unwrapOrError( 6205 this->FileName, Obj.getSection(StackSizesELFSec->sh_link)); 6206 6207 SupportsRelocation IsSupportedFn; 6208 RelocationResolver Resolver; 6209 std::tie(IsSupportedFn, Resolver) = getRelocationResolver(this->ObjF); 6210 ArrayRef<uint8_t> Contents = 6211 unwrapOrError(this->FileName, Obj.getSectionContents(*StackSizesELFSec)); 6212 DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr)); 6213 6214 forEachRelocationDo( 6215 *RelocSec, /*RawRelr=*/false, 6216 [&](const Relocation<ELFT> &R, unsigned Ndx, const Elf_Shdr &Sec, 6217 const Elf_Shdr *SymTab) { 6218 if (!IsSupportedFn || !IsSupportedFn(R.Type)) { 6219 reportUniqueWarning( 6220 describe(*RelocSec) + 6221 " contains an unsupported relocation with index " + Twine(Ndx) + 6222 ": " + Obj.getRelocationTypeName(R.Type)); 6223 return; 6224 } 6225 6226 this->printStackSize(R, *RelocSec, Ndx, SymTab, FunctionSec, 6227 *StackSizesELFSec, Resolver, Data); 6228 }, 6229 [](const Elf_Relr &) { 6230 llvm_unreachable("can't get here, because we only support " 6231 "SHT_REL/SHT_RELA sections"); 6232 }); 6233 } 6234 } 6235 6236 template <class ELFT> 6237 void GNUELFDumper<ELFT>::printStackSizes() { 6238 bool HeaderHasBeenPrinted = false; 6239 auto PrintHeader = [&]() { 6240 if (HeaderHasBeenPrinted) 6241 return; 6242 OS << "\nStack Sizes:\n"; 6243 OS.PadToColumn(9); 6244 OS << "Size"; 6245 OS.PadToColumn(18); 6246 OS << "Functions\n"; 6247 HeaderHasBeenPrinted = true; 6248 }; 6249 6250 // For non-relocatable objects, look directly for sections whose name starts 6251 // with .stack_sizes and process the contents. 6252 if (this->Obj.getHeader().e_type == ELF::ET_REL) 6253 this->printRelocatableStackSizes(PrintHeader); 6254 else 6255 this->printNonRelocatableStackSizes(PrintHeader); 6256 } 6257 6258 template <class ELFT> 6259 void GNUELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) { 6260 size_t Bias = ELFT::Is64Bits ? 8 : 0; 6261 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) { 6262 OS.PadToColumn(2); 6263 OS << format_hex_no_prefix(Parser.getGotAddress(E), 8 + Bias); 6264 OS.PadToColumn(11 + Bias); 6265 OS << format_decimal(Parser.getGotOffset(E), 6) << "(gp)"; 6266 OS.PadToColumn(22 + Bias); 6267 OS << format_hex_no_prefix(*E, 8 + Bias); 6268 OS.PadToColumn(31 + 2 * Bias); 6269 OS << Purpose << "\n"; 6270 }; 6271 6272 OS << (Parser.IsStatic ? "Static GOT:\n" : "Primary GOT:\n"); 6273 OS << " Canonical gp value: " 6274 << format_hex_no_prefix(Parser.getGp(), 8 + Bias) << "\n\n"; 6275 6276 OS << " Reserved entries:\n"; 6277 if (ELFT::Is64Bits) 6278 OS << " Address Access Initial Purpose\n"; 6279 else 6280 OS << " Address Access Initial Purpose\n"; 6281 PrintEntry(Parser.getGotLazyResolver(), "Lazy resolver"); 6282 if (Parser.getGotModulePointer()) 6283 PrintEntry(Parser.getGotModulePointer(), "Module pointer (GNU extension)"); 6284 6285 if (!Parser.getLocalEntries().empty()) { 6286 OS << "\n"; 6287 OS << " Local entries:\n"; 6288 if (ELFT::Is64Bits) 6289 OS << " Address Access Initial\n"; 6290 else 6291 OS << " Address Access Initial\n"; 6292 for (auto &E : Parser.getLocalEntries()) 6293 PrintEntry(&E, ""); 6294 } 6295 6296 if (Parser.IsStatic) 6297 return; 6298 6299 if (!Parser.getGlobalEntries().empty()) { 6300 OS << "\n"; 6301 OS << " Global entries:\n"; 6302 if (ELFT::Is64Bits) 6303 OS << " Address Access Initial Sym.Val." 6304 << " Type Ndx Name\n"; 6305 else 6306 OS << " Address Access Initial Sym.Val. Type Ndx Name\n"; 6307 6308 DataRegion<Elf_Word> ShndxTable( 6309 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end()); 6310 for (auto &E : Parser.getGlobalEntries()) { 6311 const Elf_Sym &Sym = *Parser.getGotSym(&E); 6312 const Elf_Sym &FirstSym = this->dynamic_symbols()[0]; 6313 std::string SymName = this->getFullSymbolName( 6314 Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false); 6315 6316 OS.PadToColumn(2); 6317 OS << to_string(format_hex_no_prefix(Parser.getGotAddress(&E), 8 + Bias)); 6318 OS.PadToColumn(11 + Bias); 6319 OS << to_string(format_decimal(Parser.getGotOffset(&E), 6)) + "(gp)"; 6320 OS.PadToColumn(22 + Bias); 6321 OS << to_string(format_hex_no_prefix(E, 8 + Bias)); 6322 OS.PadToColumn(31 + 2 * Bias); 6323 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias)); 6324 OS.PadToColumn(40 + 3 * Bias); 6325 OS << enumToString(Sym.getType(), makeArrayRef(ElfSymbolTypes)); 6326 OS.PadToColumn(48 + 3 * Bias); 6327 OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(), 6328 ShndxTable); 6329 OS.PadToColumn(52 + 3 * Bias); 6330 OS << SymName << "\n"; 6331 } 6332 } 6333 6334 if (!Parser.getOtherEntries().empty()) 6335 OS << "\n Number of TLS and multi-GOT entries " 6336 << Parser.getOtherEntries().size() << "\n"; 6337 } 6338 6339 template <class ELFT> 6340 void GNUELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) { 6341 size_t Bias = ELFT::Is64Bits ? 8 : 0; 6342 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) { 6343 OS.PadToColumn(2); 6344 OS << format_hex_no_prefix(Parser.getPltAddress(E), 8 + Bias); 6345 OS.PadToColumn(11 + Bias); 6346 OS << format_hex_no_prefix(*E, 8 + Bias); 6347 OS.PadToColumn(20 + 2 * Bias); 6348 OS << Purpose << "\n"; 6349 }; 6350 6351 OS << "PLT GOT:\n\n"; 6352 6353 OS << " Reserved entries:\n"; 6354 OS << " Address Initial Purpose\n"; 6355 PrintEntry(Parser.getPltLazyResolver(), "PLT lazy resolver"); 6356 if (Parser.getPltModulePointer()) 6357 PrintEntry(Parser.getPltModulePointer(), "Module pointer"); 6358 6359 if (!Parser.getPltEntries().empty()) { 6360 OS << "\n"; 6361 OS << " Entries:\n"; 6362 OS << " Address Initial Sym.Val. Type Ndx Name\n"; 6363 DataRegion<Elf_Word> ShndxTable( 6364 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end()); 6365 for (auto &E : Parser.getPltEntries()) { 6366 const Elf_Sym &Sym = *Parser.getPltSym(&E); 6367 const Elf_Sym &FirstSym = *cantFail( 6368 this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0)); 6369 std::string SymName = this->getFullSymbolName( 6370 Sym, &Sym - &FirstSym, ShndxTable, this->DynamicStringTable, false); 6371 6372 OS.PadToColumn(2); 6373 OS << to_string(format_hex_no_prefix(Parser.getPltAddress(&E), 8 + Bias)); 6374 OS.PadToColumn(11 + Bias); 6375 OS << to_string(format_hex_no_prefix(E, 8 + Bias)); 6376 OS.PadToColumn(20 + 2 * Bias); 6377 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias)); 6378 OS.PadToColumn(29 + 3 * Bias); 6379 OS << enumToString(Sym.getType(), makeArrayRef(ElfSymbolTypes)); 6380 OS.PadToColumn(37 + 3 * Bias); 6381 OS << getSymbolSectionNdx(Sym, &Sym - this->dynamic_symbols().begin(), 6382 ShndxTable); 6383 OS.PadToColumn(41 + 3 * Bias); 6384 OS << SymName << "\n"; 6385 } 6386 } 6387 } 6388 6389 template <class ELFT> 6390 Expected<const Elf_Mips_ABIFlags<ELFT> *> 6391 getMipsAbiFlagsSection(const ELFDumper<ELFT> &Dumper) { 6392 const typename ELFT::Shdr *Sec = Dumper.findSectionByName(".MIPS.abiflags"); 6393 if (Sec == nullptr) 6394 return nullptr; 6395 6396 constexpr StringRef ErrPrefix = "unable to read the .MIPS.abiflags section: "; 6397 Expected<ArrayRef<uint8_t>> DataOrErr = 6398 Dumper.getElfObject().getELFFile().getSectionContents(*Sec); 6399 if (!DataOrErr) 6400 return createError(ErrPrefix + toString(DataOrErr.takeError())); 6401 6402 if (DataOrErr->size() != sizeof(Elf_Mips_ABIFlags<ELFT>)) 6403 return createError(ErrPrefix + "it has a wrong size (" + 6404 Twine(DataOrErr->size()) + ")"); 6405 return reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(DataOrErr->data()); 6406 } 6407 6408 template <class ELFT> void GNUELFDumper<ELFT>::printMipsABIFlags() { 6409 const Elf_Mips_ABIFlags<ELFT> *Flags = nullptr; 6410 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr = 6411 getMipsAbiFlagsSection(*this)) 6412 Flags = *SecOrErr; 6413 else 6414 this->reportUniqueWarning(SecOrErr.takeError()); 6415 if (!Flags) 6416 return; 6417 6418 OS << "MIPS ABI Flags Version: " << Flags->version << "\n\n"; 6419 OS << "ISA: MIPS" << int(Flags->isa_level); 6420 if (Flags->isa_rev > 1) 6421 OS << "r" << int(Flags->isa_rev); 6422 OS << "\n"; 6423 OS << "GPR size: " << getMipsRegisterSize(Flags->gpr_size) << "\n"; 6424 OS << "CPR1 size: " << getMipsRegisterSize(Flags->cpr1_size) << "\n"; 6425 OS << "CPR2 size: " << getMipsRegisterSize(Flags->cpr2_size) << "\n"; 6426 OS << "FP ABI: " 6427 << enumToString(Flags->fp_abi, makeArrayRef(ElfMipsFpABIType)) << "\n"; 6428 OS << "ISA Extension: " 6429 << enumToString(Flags->isa_ext, makeArrayRef(ElfMipsISAExtType)) << "\n"; 6430 if (Flags->ases == 0) 6431 OS << "ASEs: None\n"; 6432 else 6433 // FIXME: Print each flag on a separate line. 6434 OS << "ASEs: " << printFlags(Flags->ases, makeArrayRef(ElfMipsASEFlags)) 6435 << "\n"; 6436 OS << "FLAGS 1: " << format_hex_no_prefix(Flags->flags1, 8, false) << "\n"; 6437 OS << "FLAGS 2: " << format_hex_no_prefix(Flags->flags2, 8, false) << "\n"; 6438 OS << "\n"; 6439 } 6440 6441 template <class ELFT> void LLVMELFDumper<ELFT>::printFileHeaders() { 6442 const Elf_Ehdr &E = this->Obj.getHeader(); 6443 { 6444 DictScope D(W, "ElfHeader"); 6445 { 6446 DictScope D(W, "Ident"); 6447 W.printBinary("Magic", makeArrayRef(E.e_ident).slice(ELF::EI_MAG0, 4)); 6448 W.printEnum("Class", E.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass)); 6449 W.printEnum("DataEncoding", E.e_ident[ELF::EI_DATA], 6450 makeArrayRef(ElfDataEncoding)); 6451 W.printNumber("FileVersion", E.e_ident[ELF::EI_VERSION]); 6452 6453 auto OSABI = makeArrayRef(ElfOSABI); 6454 if (E.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH && 6455 E.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) { 6456 switch (E.e_machine) { 6457 case ELF::EM_AMDGPU: 6458 OSABI = makeArrayRef(AMDGPUElfOSABI); 6459 break; 6460 case ELF::EM_ARM: 6461 OSABI = makeArrayRef(ARMElfOSABI); 6462 break; 6463 case ELF::EM_TI_C6000: 6464 OSABI = makeArrayRef(C6000ElfOSABI); 6465 break; 6466 } 6467 } 6468 W.printEnum("OS/ABI", E.e_ident[ELF::EI_OSABI], OSABI); 6469 W.printNumber("ABIVersion", E.e_ident[ELF::EI_ABIVERSION]); 6470 W.printBinary("Unused", makeArrayRef(E.e_ident).slice(ELF::EI_PAD)); 6471 } 6472 6473 std::string TypeStr; 6474 if (const EnumEntry<unsigned> *Ent = getObjectFileEnumEntry(E.e_type)) { 6475 TypeStr = Ent->Name.str(); 6476 } else { 6477 if (E.e_type >= ET_LOPROC) 6478 TypeStr = "Processor Specific"; 6479 else if (E.e_type >= ET_LOOS) 6480 TypeStr = "OS Specific"; 6481 else 6482 TypeStr = "Unknown"; 6483 } 6484 W.printString("Type", TypeStr + " (0x" + utohexstr(E.e_type) + ")"); 6485 6486 W.printEnum("Machine", E.e_machine, makeArrayRef(ElfMachineType)); 6487 W.printNumber("Version", E.e_version); 6488 W.printHex("Entry", E.e_entry); 6489 W.printHex("ProgramHeaderOffset", E.e_phoff); 6490 W.printHex("SectionHeaderOffset", E.e_shoff); 6491 if (E.e_machine == EM_MIPS) 6492 W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderMipsFlags), 6493 unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI), 6494 unsigned(ELF::EF_MIPS_MACH)); 6495 else if (E.e_machine == EM_AMDGPU) { 6496 switch (E.e_ident[ELF::EI_ABIVERSION]) { 6497 default: 6498 W.printHex("Flags", E.e_flags); 6499 break; 6500 case 0: 6501 // ELFOSABI_AMDGPU_PAL, ELFOSABI_AMDGPU_MESA3D support *_V3 flags. 6502 LLVM_FALLTHROUGH; 6503 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 6504 W.printFlags("Flags", E.e_flags, 6505 makeArrayRef(ElfHeaderAMDGPUFlagsABIVersion3), 6506 unsigned(ELF::EF_AMDGPU_MACH)); 6507 break; 6508 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 6509 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 6510 W.printFlags("Flags", E.e_flags, 6511 makeArrayRef(ElfHeaderAMDGPUFlagsABIVersion4), 6512 unsigned(ELF::EF_AMDGPU_MACH), 6513 unsigned(ELF::EF_AMDGPU_FEATURE_XNACK_V4), 6514 unsigned(ELF::EF_AMDGPU_FEATURE_SRAMECC_V4)); 6515 break; 6516 } 6517 } else if (E.e_machine == EM_RISCV) 6518 W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderRISCVFlags)); 6519 else if (E.e_machine == EM_AVR) 6520 W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderAVRFlags), 6521 unsigned(ELF::EF_AVR_ARCH_MASK)); 6522 else if (E.e_machine == EM_LOONGARCH) 6523 W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderLoongArchFlags), 6524 unsigned(ELF::EF_LOONGARCH_BASE_ABI_MASK)); 6525 else 6526 W.printFlags("Flags", E.e_flags); 6527 W.printNumber("HeaderSize", E.e_ehsize); 6528 W.printNumber("ProgramHeaderEntrySize", E.e_phentsize); 6529 W.printNumber("ProgramHeaderCount", E.e_phnum); 6530 W.printNumber("SectionHeaderEntrySize", E.e_shentsize); 6531 W.printString("SectionHeaderCount", 6532 getSectionHeadersNumString(this->Obj, this->FileName)); 6533 W.printString("StringTableSectionIndex", 6534 getSectionHeaderTableIndexString(this->Obj, this->FileName)); 6535 } 6536 } 6537 6538 template <class ELFT> void LLVMELFDumper<ELFT>::printGroupSections() { 6539 DictScope Lists(W, "Groups"); 6540 std::vector<GroupSection> V = this->getGroups(); 6541 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V); 6542 for (const GroupSection &G : V) { 6543 DictScope D(W, "Group"); 6544 W.printNumber("Name", G.Name, G.ShName); 6545 W.printNumber("Index", G.Index); 6546 W.printNumber("Link", G.Link); 6547 W.printNumber("Info", G.Info); 6548 W.printHex("Type", getGroupType(G.Type), G.Type); 6549 W.startLine() << "Signature: " << G.Signature << "\n"; 6550 6551 ListScope L(W, "Section(s) in group"); 6552 for (const GroupMember &GM : G.Members) { 6553 const GroupSection *MainGroup = Map[GM.Index]; 6554 if (MainGroup != &G) 6555 this->reportUniqueWarning( 6556 "section with index " + Twine(GM.Index) + 6557 ", included in the group section with index " + 6558 Twine(MainGroup->Index) + 6559 ", was also found in the group section with index " + 6560 Twine(G.Index)); 6561 W.startLine() << GM.Name << " (" << GM.Index << ")\n"; 6562 } 6563 } 6564 6565 if (V.empty()) 6566 W.startLine() << "There are no group sections in the file.\n"; 6567 } 6568 6569 template <class ELFT> void LLVMELFDumper<ELFT>::printRelocations() { 6570 ListScope D(W, "Relocations"); 6571 6572 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) { 6573 if (!isRelocationSec<ELFT>(Sec)) 6574 continue; 6575 6576 StringRef Name = this->getPrintableSectionName(Sec); 6577 unsigned SecNdx = &Sec - &cantFail(this->Obj.sections()).front(); 6578 W.startLine() << "Section (" << SecNdx << ") " << Name << " {\n"; 6579 W.indent(); 6580 this->printRelocationsHelper(Sec); 6581 W.unindent(); 6582 W.startLine() << "}\n"; 6583 } 6584 } 6585 6586 template <class ELFT> 6587 void LLVMELFDumper<ELFT>::printRelrReloc(const Elf_Relr &R) { 6588 W.startLine() << W.hex(R) << "\n"; 6589 } 6590 6591 template <class ELFT> 6592 void LLVMELFDumper<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R, 6593 const RelSymbol<ELFT> &RelSym) { 6594 StringRef SymbolName = RelSym.Name; 6595 SmallString<32> RelocName; 6596 this->Obj.getRelocationTypeName(R.Type, RelocName); 6597 6598 if (opts::ExpandRelocs) { 6599 DictScope Group(W, "Relocation"); 6600 W.printHex("Offset", R.Offset); 6601 W.printNumber("Type", RelocName, R.Type); 6602 W.printNumber("Symbol", !SymbolName.empty() ? SymbolName : "-", R.Symbol); 6603 if (R.Addend) 6604 W.printHex("Addend", (uintX_t)*R.Addend); 6605 } else { 6606 raw_ostream &OS = W.startLine(); 6607 OS << W.hex(R.Offset) << " " << RelocName << " " 6608 << (!SymbolName.empty() ? SymbolName : "-"); 6609 if (R.Addend) 6610 OS << " " << W.hex((uintX_t)*R.Addend); 6611 OS << "\n"; 6612 } 6613 } 6614 6615 template <class ELFT> void LLVMELFDumper<ELFT>::printSectionHeaders() { 6616 ListScope SectionsD(W, "Sections"); 6617 6618 int SectionIndex = -1; 6619 std::vector<EnumEntry<unsigned>> FlagsList = 6620 getSectionFlagsForTarget(this->Obj.getHeader().e_ident[ELF::EI_OSABI], 6621 this->Obj.getHeader().e_machine); 6622 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) { 6623 DictScope SectionD(W, "Section"); 6624 W.printNumber("Index", ++SectionIndex); 6625 W.printNumber("Name", this->getPrintableSectionName(Sec), Sec.sh_name); 6626 W.printHex("Type", 6627 object::getELFSectionTypeName(this->Obj.getHeader().e_machine, 6628 Sec.sh_type), 6629 Sec.sh_type); 6630 W.printFlags("Flags", Sec.sh_flags, makeArrayRef(FlagsList)); 6631 W.printHex("Address", Sec.sh_addr); 6632 W.printHex("Offset", Sec.sh_offset); 6633 W.printNumber("Size", Sec.sh_size); 6634 W.printNumber("Link", Sec.sh_link); 6635 W.printNumber("Info", Sec.sh_info); 6636 W.printNumber("AddressAlignment", Sec.sh_addralign); 6637 W.printNumber("EntrySize", Sec.sh_entsize); 6638 6639 if (opts::SectionRelocations) { 6640 ListScope D(W, "Relocations"); 6641 this->printRelocationsHelper(Sec); 6642 } 6643 6644 if (opts::SectionSymbols) { 6645 ListScope D(W, "Symbols"); 6646 if (this->DotSymtabSec) { 6647 StringRef StrTable = unwrapOrError( 6648 this->FileName, 6649 this->Obj.getStringTableForSymtab(*this->DotSymtabSec)); 6650 ArrayRef<Elf_Word> ShndxTable = this->getShndxTable(this->DotSymtabSec); 6651 6652 typename ELFT::SymRange Symbols = unwrapOrError( 6653 this->FileName, this->Obj.symbols(this->DotSymtabSec)); 6654 for (const Elf_Sym &Sym : Symbols) { 6655 const Elf_Shdr *SymSec = unwrapOrError( 6656 this->FileName, 6657 this->Obj.getSection(Sym, this->DotSymtabSec, ShndxTable)); 6658 if (SymSec == &Sec) 6659 printSymbol(Sym, &Sym - &Symbols[0], ShndxTable, StrTable, false, 6660 false); 6661 } 6662 } 6663 } 6664 6665 if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) { 6666 ArrayRef<uint8_t> Data = 6667 unwrapOrError(this->FileName, this->Obj.getSectionContents(Sec)); 6668 W.printBinaryBlock( 6669 "SectionData", 6670 StringRef(reinterpret_cast<const char *>(Data.data()), Data.size())); 6671 } 6672 } 6673 } 6674 6675 template <class ELFT> 6676 void LLVMELFDumper<ELFT>::printSymbolSection( 6677 const Elf_Sym &Symbol, unsigned SymIndex, 6678 DataRegion<Elf_Word> ShndxTable) const { 6679 auto GetSectionSpecialType = [&]() -> Optional<StringRef> { 6680 if (Symbol.isUndefined()) 6681 return StringRef("Undefined"); 6682 if (Symbol.isProcessorSpecific()) 6683 return StringRef("Processor Specific"); 6684 if (Symbol.isOSSpecific()) 6685 return StringRef("Operating System Specific"); 6686 if (Symbol.isAbsolute()) 6687 return StringRef("Absolute"); 6688 if (Symbol.isCommon()) 6689 return StringRef("Common"); 6690 if (Symbol.isReserved() && Symbol.st_shndx != SHN_XINDEX) 6691 return StringRef("Reserved"); 6692 return None; 6693 }; 6694 6695 if (Optional<StringRef> Type = GetSectionSpecialType()) { 6696 W.printHex("Section", *Type, Symbol.st_shndx); 6697 return; 6698 } 6699 6700 Expected<unsigned> SectionIndex = 6701 this->getSymbolSectionIndex(Symbol, SymIndex, ShndxTable); 6702 if (!SectionIndex) { 6703 assert(Symbol.st_shndx == SHN_XINDEX && 6704 "getSymbolSectionIndex should only fail due to an invalid " 6705 "SHT_SYMTAB_SHNDX table/reference"); 6706 this->reportUniqueWarning(SectionIndex.takeError()); 6707 W.printHex("Section", "Reserved", SHN_XINDEX); 6708 return; 6709 } 6710 6711 Expected<StringRef> SectionName = 6712 this->getSymbolSectionName(Symbol, *SectionIndex); 6713 if (!SectionName) { 6714 // Don't report an invalid section name if the section headers are missing. 6715 // In such situations, all sections will be "invalid". 6716 if (!this->ObjF.sections().empty()) 6717 this->reportUniqueWarning(SectionName.takeError()); 6718 else 6719 consumeError(SectionName.takeError()); 6720 W.printHex("Section", "<?>", *SectionIndex); 6721 } else { 6722 W.printHex("Section", *SectionName, *SectionIndex); 6723 } 6724 } 6725 6726 template <class ELFT> 6727 void LLVMELFDumper<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex, 6728 DataRegion<Elf_Word> ShndxTable, 6729 Optional<StringRef> StrTable, 6730 bool IsDynamic, 6731 bool /*NonVisibilityBitsUsed*/) const { 6732 std::string FullSymbolName = this->getFullSymbolName( 6733 Symbol, SymIndex, ShndxTable, StrTable, IsDynamic); 6734 unsigned char SymbolType = Symbol.getType(); 6735 6736 DictScope D(W, "Symbol"); 6737 W.printNumber("Name", FullSymbolName, Symbol.st_name); 6738 W.printHex("Value", Symbol.st_value); 6739 W.printNumber("Size", Symbol.st_size); 6740 W.printEnum("Binding", Symbol.getBinding(), makeArrayRef(ElfSymbolBindings)); 6741 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU && 6742 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS) 6743 W.printEnum("Type", SymbolType, makeArrayRef(AMDGPUSymbolTypes)); 6744 else 6745 W.printEnum("Type", SymbolType, makeArrayRef(ElfSymbolTypes)); 6746 if (Symbol.st_other == 0) 6747 // Usually st_other flag is zero. Do not pollute the output 6748 // by flags enumeration in that case. 6749 W.printNumber("Other", 0); 6750 else { 6751 std::vector<EnumEntry<unsigned>> SymOtherFlags(std::begin(ElfSymOtherFlags), 6752 std::end(ElfSymOtherFlags)); 6753 if (this->Obj.getHeader().e_machine == EM_MIPS) { 6754 // Someones in their infinite wisdom decided to make STO_MIPS_MIPS16 6755 // flag overlapped with other ST_MIPS_xxx flags. So consider both 6756 // cases separately. 6757 if ((Symbol.st_other & STO_MIPS_MIPS16) == STO_MIPS_MIPS16) 6758 SymOtherFlags.insert(SymOtherFlags.end(), 6759 std::begin(ElfMips16SymOtherFlags), 6760 std::end(ElfMips16SymOtherFlags)); 6761 else 6762 SymOtherFlags.insert(SymOtherFlags.end(), 6763 std::begin(ElfMipsSymOtherFlags), 6764 std::end(ElfMipsSymOtherFlags)); 6765 } else if (this->Obj.getHeader().e_machine == EM_AARCH64) { 6766 SymOtherFlags.insert(SymOtherFlags.end(), 6767 std::begin(ElfAArch64SymOtherFlags), 6768 std::end(ElfAArch64SymOtherFlags)); 6769 } else if (this->Obj.getHeader().e_machine == EM_RISCV) { 6770 SymOtherFlags.insert(SymOtherFlags.end(), 6771 std::begin(ElfRISCVSymOtherFlags), 6772 std::end(ElfRISCVSymOtherFlags)); 6773 } 6774 W.printFlags("Other", Symbol.st_other, makeArrayRef(SymOtherFlags), 0x3u); 6775 } 6776 printSymbolSection(Symbol, SymIndex, ShndxTable); 6777 } 6778 6779 template <class ELFT> 6780 void LLVMELFDumper<ELFT>::printSymbols(bool PrintSymbols, 6781 bool PrintDynamicSymbols) { 6782 if (PrintSymbols) { 6783 ListScope Group(W, "Symbols"); 6784 this->printSymbolsHelper(false); 6785 } 6786 if (PrintDynamicSymbols) { 6787 ListScope Group(W, "DynamicSymbols"); 6788 this->printSymbolsHelper(true); 6789 } 6790 } 6791 6792 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicTable() { 6793 Elf_Dyn_Range Table = this->dynamic_table(); 6794 if (Table.empty()) 6795 return; 6796 6797 W.startLine() << "DynamicSection [ (" << Table.size() << " entries)\n"; 6798 6799 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table); 6800 // The "Name/Value" column should be indented from the "Type" column by N 6801 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing 6802 // space (1) = -3. 6803 W.startLine() << " Tag" << std::string(ELFT::Is64Bits ? 16 : 8, ' ') 6804 << "Type" << std::string(MaxTagSize - 3, ' ') << "Name/Value\n"; 6805 6806 std::string ValueFmt = "%-" + std::to_string(MaxTagSize) + "s "; 6807 for (auto Entry : Table) { 6808 uintX_t Tag = Entry.getTag(); 6809 std::string Value = this->getDynamicEntry(Tag, Entry.getVal()); 6810 W.startLine() << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10, true) 6811 << " " 6812 << format(ValueFmt.c_str(), 6813 this->Obj.getDynamicTagAsString(Tag).c_str()) 6814 << Value << "\n"; 6815 } 6816 W.startLine() << "]\n"; 6817 } 6818 6819 template <class ELFT> void LLVMELFDumper<ELFT>::printDynamicRelocations() { 6820 W.startLine() << "Dynamic Relocations {\n"; 6821 W.indent(); 6822 this->printDynamicRelocationsHelper(); 6823 W.unindent(); 6824 W.startLine() << "}\n"; 6825 } 6826 6827 template <class ELFT> 6828 void LLVMELFDumper<ELFT>::printProgramHeaders( 6829 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) { 6830 if (PrintProgramHeaders) 6831 printProgramHeaders(); 6832 if (PrintSectionMapping == cl::BOU_TRUE) 6833 printSectionMapping(); 6834 } 6835 6836 template <class ELFT> void LLVMELFDumper<ELFT>::printProgramHeaders() { 6837 ListScope L(W, "ProgramHeaders"); 6838 6839 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers(); 6840 if (!PhdrsOrErr) { 6841 this->reportUniqueWarning("unable to dump program headers: " + 6842 toString(PhdrsOrErr.takeError())); 6843 return; 6844 } 6845 6846 for (const Elf_Phdr &Phdr : *PhdrsOrErr) { 6847 DictScope P(W, "ProgramHeader"); 6848 StringRef Type = 6849 segmentTypeToString(this->Obj.getHeader().e_machine, Phdr.p_type); 6850 6851 W.printHex("Type", Type.empty() ? "Unknown" : Type, Phdr.p_type); 6852 W.printHex("Offset", Phdr.p_offset); 6853 W.printHex("VirtualAddress", Phdr.p_vaddr); 6854 W.printHex("PhysicalAddress", Phdr.p_paddr); 6855 W.printNumber("FileSize", Phdr.p_filesz); 6856 W.printNumber("MemSize", Phdr.p_memsz); 6857 W.printFlags("Flags", Phdr.p_flags, makeArrayRef(ElfSegmentFlags)); 6858 W.printNumber("Alignment", Phdr.p_align); 6859 } 6860 } 6861 6862 template <class ELFT> 6863 void LLVMELFDumper<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) { 6864 ListScope SS(W, "VersionSymbols"); 6865 if (!Sec) 6866 return; 6867 6868 StringRef StrTable; 6869 ArrayRef<Elf_Sym> Syms; 6870 const Elf_Shdr *SymTabSec; 6871 Expected<ArrayRef<Elf_Versym>> VerTableOrErr = 6872 this->getVersionTable(*Sec, &Syms, &StrTable, &SymTabSec); 6873 if (!VerTableOrErr) { 6874 this->reportUniqueWarning(VerTableOrErr.takeError()); 6875 return; 6876 } 6877 6878 if (StrTable.empty() || Syms.empty() || Syms.size() != VerTableOrErr->size()) 6879 return; 6880 6881 ArrayRef<Elf_Word> ShNdxTable = this->getShndxTable(SymTabSec); 6882 for (size_t I = 0, E = Syms.size(); I < E; ++I) { 6883 DictScope S(W, "Symbol"); 6884 W.printNumber("Version", (*VerTableOrErr)[I].vs_index & VERSYM_VERSION); 6885 W.printString("Name", 6886 this->getFullSymbolName(Syms[I], I, ShNdxTable, StrTable, 6887 /*IsDynamic=*/true)); 6888 } 6889 } 6890 6891 const EnumEntry<unsigned> SymVersionFlags[] = { 6892 {"Base", "BASE", VER_FLG_BASE}, 6893 {"Weak", "WEAK", VER_FLG_WEAK}, 6894 {"Info", "INFO", VER_FLG_INFO}}; 6895 6896 template <class ELFT> 6897 void LLVMELFDumper<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) { 6898 ListScope SD(W, "VersionDefinitions"); 6899 if (!Sec) 6900 return; 6901 6902 Expected<std::vector<VerDef>> V = this->Obj.getVersionDefinitions(*Sec); 6903 if (!V) { 6904 this->reportUniqueWarning(V.takeError()); 6905 return; 6906 } 6907 6908 for (const VerDef &D : *V) { 6909 DictScope Def(W, "Definition"); 6910 W.printNumber("Version", D.Version); 6911 W.printFlags("Flags", D.Flags, makeArrayRef(SymVersionFlags)); 6912 W.printNumber("Index", D.Ndx); 6913 W.printNumber("Hash", D.Hash); 6914 W.printString("Name", D.Name.c_str()); 6915 W.printList( 6916 "Predecessors", D.AuxV, 6917 [](raw_ostream &OS, const VerdAux &Aux) { OS << Aux.Name.c_str(); }); 6918 } 6919 } 6920 6921 template <class ELFT> 6922 void LLVMELFDumper<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) { 6923 ListScope SD(W, "VersionRequirements"); 6924 if (!Sec) 6925 return; 6926 6927 Expected<std::vector<VerNeed>> V = 6928 this->Obj.getVersionDependencies(*Sec, this->WarningHandler); 6929 if (!V) { 6930 this->reportUniqueWarning(V.takeError()); 6931 return; 6932 } 6933 6934 for (const VerNeed &VN : *V) { 6935 DictScope Entry(W, "Dependency"); 6936 W.printNumber("Version", VN.Version); 6937 W.printNumber("Count", VN.Cnt); 6938 W.printString("FileName", VN.File.c_str()); 6939 6940 ListScope L(W, "Entries"); 6941 for (const VernAux &Aux : VN.AuxV) { 6942 DictScope Entry(W, "Entry"); 6943 W.printNumber("Hash", Aux.Hash); 6944 W.printFlags("Flags", Aux.Flags, makeArrayRef(SymVersionFlags)); 6945 W.printNumber("Index", Aux.Other); 6946 W.printString("Name", Aux.Name.c_str()); 6947 } 6948 } 6949 } 6950 6951 template <class ELFT> void LLVMELFDumper<ELFT>::printHashHistograms() { 6952 W.startLine() << "Hash Histogram not implemented!\n"; 6953 } 6954 6955 // Returns true if rel/rela section exists, and populates SymbolIndices. 6956 // Otherwise returns false. 6957 template <class ELFT> 6958 static bool getSymbolIndices(const typename ELFT::Shdr *CGRelSection, 6959 const ELFFile<ELFT> &Obj, 6960 const LLVMELFDumper<ELFT> *Dumper, 6961 SmallVector<uint32_t, 128> &SymbolIndices) { 6962 if (!CGRelSection) { 6963 Dumper->reportUniqueWarning( 6964 "relocation section for a call graph section doesn't exist"); 6965 return false; 6966 } 6967 6968 if (CGRelSection->sh_type == SHT_REL) { 6969 typename ELFT::RelRange CGProfileRel; 6970 Expected<typename ELFT::RelRange> CGProfileRelOrError = 6971 Obj.rels(*CGRelSection); 6972 if (!CGProfileRelOrError) { 6973 Dumper->reportUniqueWarning("unable to load relocations for " 6974 "SHT_LLVM_CALL_GRAPH_PROFILE section: " + 6975 toString(CGProfileRelOrError.takeError())); 6976 return false; 6977 } 6978 6979 CGProfileRel = *CGProfileRelOrError; 6980 for (const typename ELFT::Rel &Rel : CGProfileRel) 6981 SymbolIndices.push_back(Rel.getSymbol(Obj.isMips64EL())); 6982 } else { 6983 // MC unconditionally produces SHT_REL, but GNU strip/objcopy may convert 6984 // the format to SHT_RELA 6985 // (https://sourceware.org/bugzilla/show_bug.cgi?id=28035) 6986 typename ELFT::RelaRange CGProfileRela; 6987 Expected<typename ELFT::RelaRange> CGProfileRelaOrError = 6988 Obj.relas(*CGRelSection); 6989 if (!CGProfileRelaOrError) { 6990 Dumper->reportUniqueWarning("unable to load relocations for " 6991 "SHT_LLVM_CALL_GRAPH_PROFILE section: " + 6992 toString(CGProfileRelaOrError.takeError())); 6993 return false; 6994 } 6995 6996 CGProfileRela = *CGProfileRelaOrError; 6997 for (const typename ELFT::Rela &Rela : CGProfileRela) 6998 SymbolIndices.push_back(Rela.getSymbol(Obj.isMips64EL())); 6999 } 7000 7001 return true; 7002 } 7003 7004 template <class ELFT> void LLVMELFDumper<ELFT>::printCGProfile() { 7005 llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> SecToRelocMap; 7006 7007 auto IsMatch = [](const Elf_Shdr &Sec) -> bool { 7008 return Sec.sh_type == ELF::SHT_LLVM_CALL_GRAPH_PROFILE; 7009 }; 7010 this->getSectionAndRelocations(IsMatch, SecToRelocMap); 7011 7012 for (const auto &CGMapEntry : SecToRelocMap) { 7013 const Elf_Shdr *CGSection = CGMapEntry.first; 7014 const Elf_Shdr *CGRelSection = CGMapEntry.second; 7015 7016 Expected<ArrayRef<Elf_CGProfile>> CGProfileOrErr = 7017 this->Obj.template getSectionContentsAsArray<Elf_CGProfile>(*CGSection); 7018 if (!CGProfileOrErr) { 7019 this->reportUniqueWarning( 7020 "unable to load the SHT_LLVM_CALL_GRAPH_PROFILE section: " + 7021 toString(CGProfileOrErr.takeError())); 7022 return; 7023 } 7024 7025 SmallVector<uint32_t, 128> SymbolIndices; 7026 bool UseReloc = 7027 getSymbolIndices<ELFT>(CGRelSection, this->Obj, this, SymbolIndices); 7028 if (UseReloc && SymbolIndices.size() != CGProfileOrErr->size() * 2) { 7029 this->reportUniqueWarning( 7030 "number of from/to pairs does not match number of frequencies"); 7031 UseReloc = false; 7032 } 7033 7034 ListScope L(W, "CGProfile"); 7035 for (uint32_t I = 0, Size = CGProfileOrErr->size(); I != Size; ++I) { 7036 const Elf_CGProfile &CGPE = (*CGProfileOrErr)[I]; 7037 DictScope D(W, "CGProfileEntry"); 7038 if (UseReloc) { 7039 uint32_t From = SymbolIndices[I * 2]; 7040 uint32_t To = SymbolIndices[I * 2 + 1]; 7041 W.printNumber("From", this->getStaticSymbolName(From), From); 7042 W.printNumber("To", this->getStaticSymbolName(To), To); 7043 } 7044 W.printNumber("Weight", CGPE.cgp_weight); 7045 } 7046 } 7047 } 7048 7049 template <class ELFT> void LLVMELFDumper<ELFT>::printBBAddrMaps() { 7050 bool IsRelocatable = this->Obj.getHeader().e_type == ELF::ET_REL; 7051 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) { 7052 if (Sec.sh_type != SHT_LLVM_BB_ADDR_MAP && 7053 Sec.sh_type != SHT_LLVM_BB_ADDR_MAP_V0) { 7054 continue; 7055 } 7056 Optional<const Elf_Shdr *> FunctionSec = None; 7057 if (IsRelocatable) 7058 FunctionSec = 7059 unwrapOrError(this->FileName, this->Obj.getSection(Sec.sh_link)); 7060 ListScope L(W, "BBAddrMap"); 7061 Expected<std::vector<BBAddrMap>> BBAddrMapOrErr = 7062 this->Obj.decodeBBAddrMap(Sec); 7063 if (!BBAddrMapOrErr) { 7064 this->reportUniqueWarning("unable to dump " + this->describe(Sec) + ": " + 7065 toString(BBAddrMapOrErr.takeError())); 7066 continue; 7067 } 7068 for (const BBAddrMap &AM : *BBAddrMapOrErr) { 7069 DictScope D(W, "Function"); 7070 W.printHex("At", AM.Addr); 7071 SmallVector<uint32_t> FuncSymIndex = 7072 this->getSymbolIndexesForFunctionAddress(AM.Addr, FunctionSec); 7073 std::string FuncName = "<?>"; 7074 if (FuncSymIndex.empty()) 7075 this->reportUniqueWarning( 7076 "could not identify function symbol for address (0x" + 7077 Twine::utohexstr(AM.Addr) + ") in " + this->describe(Sec)); 7078 else 7079 FuncName = this->getStaticSymbolName(FuncSymIndex.front()); 7080 W.printString("Name", FuncName); 7081 7082 ListScope L(W, "BB entries"); 7083 for (const BBAddrMap::BBEntry &BBE : AM.BBEntries) { 7084 DictScope L(W); 7085 W.printHex("Offset", BBE.Offset); 7086 W.printHex("Size", BBE.Size); 7087 W.printBoolean("HasReturn", BBE.HasReturn); 7088 W.printBoolean("HasTailCall", BBE.HasTailCall); 7089 W.printBoolean("IsEHPad", BBE.IsEHPad); 7090 W.printBoolean("CanFallThrough", BBE.CanFallThrough); 7091 } 7092 } 7093 } 7094 } 7095 7096 template <class ELFT> void LLVMELFDumper<ELFT>::printAddrsig() { 7097 ListScope L(W, "Addrsig"); 7098 if (!this->DotAddrsigSec) 7099 return; 7100 7101 Expected<std::vector<uint64_t>> SymsOrErr = 7102 decodeAddrsigSection(this->Obj, *this->DotAddrsigSec); 7103 if (!SymsOrErr) { 7104 this->reportUniqueWarning(SymsOrErr.takeError()); 7105 return; 7106 } 7107 7108 for (uint64_t Sym : *SymsOrErr) 7109 W.printNumber("Sym", this->getStaticSymbolName(Sym), Sym); 7110 } 7111 7112 template <typename ELFT> 7113 static bool printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc, 7114 ScopedPrinter &W) { 7115 // Return true if we were able to pretty-print the note, false otherwise. 7116 switch (NoteType) { 7117 default: 7118 return false; 7119 case ELF::NT_GNU_ABI_TAG: { 7120 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc); 7121 if (!AbiTag.IsValid) { 7122 W.printString("ABI", "<corrupt GNU_ABI_TAG>"); 7123 return false; 7124 } else { 7125 W.printString("OS", AbiTag.OSName); 7126 W.printString("ABI", AbiTag.ABI); 7127 } 7128 break; 7129 } 7130 case ELF::NT_GNU_BUILD_ID: { 7131 W.printString("Build ID", getGNUBuildId(Desc)); 7132 break; 7133 } 7134 case ELF::NT_GNU_GOLD_VERSION: 7135 W.printString("Version", getDescAsStringRef(Desc)); 7136 break; 7137 case ELF::NT_GNU_PROPERTY_TYPE_0: 7138 ListScope D(W, "Property"); 7139 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc)) 7140 W.printString(Property); 7141 break; 7142 } 7143 return true; 7144 } 7145 7146 static bool printAndroidNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc, 7147 ScopedPrinter &W) { 7148 // Return true if we were able to pretty-print the note, false otherwise. 7149 AndroidNoteProperties Props = getAndroidNoteProperties(NoteType, Desc); 7150 if (Props.empty()) 7151 return false; 7152 for (const auto &KV : Props) 7153 W.printString(KV.first, KV.second); 7154 return true; 7155 } 7156 7157 template <typename ELFT> 7158 static bool printLLVMOMPOFFLOADNoteLLVMStyle(uint32_t NoteType, 7159 ArrayRef<uint8_t> Desc, 7160 ScopedPrinter &W) { 7161 switch (NoteType) { 7162 default: 7163 return false; 7164 case ELF::NT_LLVM_OPENMP_OFFLOAD_VERSION: 7165 W.printString("Version", getDescAsStringRef(Desc)); 7166 break; 7167 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER: 7168 W.printString("Producer", getDescAsStringRef(Desc)); 7169 break; 7170 case ELF::NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION: 7171 W.printString("Producer version", getDescAsStringRef(Desc)); 7172 break; 7173 } 7174 return true; 7175 } 7176 7177 static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) { 7178 W.printNumber("Page Size", Note.PageSize); 7179 for (const CoreFileMapping &Mapping : Note.Mappings) { 7180 ListScope D(W, "Mapping"); 7181 W.printHex("Start", Mapping.Start); 7182 W.printHex("End", Mapping.End); 7183 W.printHex("Offset", Mapping.Offset); 7184 W.printString("Filename", Mapping.Filename); 7185 } 7186 } 7187 7188 template <class ELFT> void LLVMELFDumper<ELFT>::printNotes() { 7189 ListScope L(W, "Notes"); 7190 7191 std::unique_ptr<DictScope> NoteScope; 7192 auto StartNotes = [&](Optional<StringRef> SecName, 7193 const typename ELFT::Off Offset, 7194 const typename ELFT::Addr Size) { 7195 NoteScope = std::make_unique<DictScope>(W, "NoteSection"); 7196 W.printString("Name", SecName ? *SecName : "<?>"); 7197 W.printHex("Offset", Offset); 7198 W.printHex("Size", Size); 7199 }; 7200 7201 auto EndNotes = [&] { NoteScope.reset(); }; 7202 7203 auto ProcessNote = [&](const Elf_Note &Note, bool IsCore) -> Error { 7204 DictScope D2(W, "Note"); 7205 StringRef Name = Note.getName(); 7206 ArrayRef<uint8_t> Descriptor = Note.getDesc(); 7207 Elf_Word Type = Note.getType(); 7208 7209 // Print the note owner/type. 7210 W.printString("Owner", Name); 7211 W.printHex("Data size", Descriptor.size()); 7212 7213 StringRef NoteType = 7214 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type); 7215 if (!NoteType.empty()) 7216 W.printString("Type", NoteType); 7217 else 7218 W.printString("Type", 7219 "Unknown (" + to_string(format_hex(Type, 10)) + ")"); 7220 7221 // Print the description, or fallback to printing raw bytes for unknown 7222 // owners/if we fail to pretty-print the contents. 7223 if (Name == "GNU") { 7224 if (printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W)) 7225 return Error::success(); 7226 } else if (Name == "FreeBSD") { 7227 if (Optional<FreeBSDNote> N = 7228 getFreeBSDNote<ELFT>(Type, Descriptor, IsCore)) { 7229 W.printString(N->Type, N->Value); 7230 return Error::success(); 7231 } 7232 } else if (Name == "AMD") { 7233 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor); 7234 if (!N.Type.empty()) { 7235 W.printString(N.Type, N.Value); 7236 return Error::success(); 7237 } 7238 } else if (Name == "AMDGPU") { 7239 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor); 7240 if (!N.Type.empty()) { 7241 W.printString(N.Type, N.Value); 7242 return Error::success(); 7243 } 7244 } else if (Name == "LLVMOMPOFFLOAD") { 7245 if (printLLVMOMPOFFLOADNoteLLVMStyle<ELFT>(Type, Descriptor, W)) 7246 return Error::success(); 7247 } else if (Name == "CORE") { 7248 if (Type == ELF::NT_FILE) { 7249 DataExtractor DescExtractor(Descriptor, 7250 ELFT::TargetEndianness == support::little, 7251 sizeof(Elf_Addr)); 7252 if (Expected<CoreNote> N = readCoreNote(DescExtractor)) { 7253 printCoreNoteLLVMStyle(*N, W); 7254 return Error::success(); 7255 } else { 7256 return N.takeError(); 7257 } 7258 } 7259 } else if (Name == "Android") { 7260 if (printAndroidNoteLLVMStyle(Type, Descriptor, W)) 7261 return Error::success(); 7262 } 7263 if (!Descriptor.empty()) { 7264 W.printBinaryBlock("Description data", Descriptor); 7265 } 7266 return Error::success(); 7267 }; 7268 7269 printNotesHelper(*this, StartNotes, ProcessNote, EndNotes); 7270 } 7271 7272 template <class ELFT> void LLVMELFDumper<ELFT>::printELFLinkerOptions() { 7273 ListScope L(W, "LinkerOptions"); 7274 7275 unsigned I = -1; 7276 for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) { 7277 ++I; 7278 if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS) 7279 continue; 7280 7281 Expected<ArrayRef<uint8_t>> ContentsOrErr = 7282 this->Obj.getSectionContents(Shdr); 7283 if (!ContentsOrErr) { 7284 this->reportUniqueWarning("unable to read the content of the " 7285 "SHT_LLVM_LINKER_OPTIONS section: " + 7286 toString(ContentsOrErr.takeError())); 7287 continue; 7288 } 7289 if (ContentsOrErr->empty()) 7290 continue; 7291 7292 if (ContentsOrErr->back() != 0) { 7293 this->reportUniqueWarning("SHT_LLVM_LINKER_OPTIONS section at index " + 7294 Twine(I) + 7295 " is broken: the " 7296 "content is not null-terminated"); 7297 continue; 7298 } 7299 7300 SmallVector<StringRef, 16> Strings; 7301 toStringRef(ContentsOrErr->drop_back()).split(Strings, '\0'); 7302 if (Strings.size() % 2 != 0) { 7303 this->reportUniqueWarning( 7304 "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) + 7305 " is broken: an incomplete " 7306 "key-value pair was found. The last possible key was: \"" + 7307 Strings.back() + "\""); 7308 continue; 7309 } 7310 7311 for (size_t I = 0; I < Strings.size(); I += 2) 7312 W.printString(Strings[I], Strings[I + 1]); 7313 } 7314 } 7315 7316 template <class ELFT> void LLVMELFDumper<ELFT>::printDependentLibs() { 7317 ListScope L(W, "DependentLibs"); 7318 this->printDependentLibsHelper( 7319 [](const Elf_Shdr &) {}, 7320 [this](StringRef Lib, uint64_t) { W.printString(Lib); }); 7321 } 7322 7323 template <class ELFT> void LLVMELFDumper<ELFT>::printStackSizes() { 7324 ListScope L(W, "StackSizes"); 7325 if (this->Obj.getHeader().e_type == ELF::ET_REL) 7326 this->printRelocatableStackSizes([]() {}); 7327 else 7328 this->printNonRelocatableStackSizes([]() {}); 7329 } 7330 7331 template <class ELFT> 7332 void LLVMELFDumper<ELFT>::printStackSizeEntry(uint64_t Size, 7333 ArrayRef<std::string> FuncNames) { 7334 DictScope D(W, "Entry"); 7335 W.printList("Functions", FuncNames); 7336 W.printHex("Size", Size); 7337 } 7338 7339 template <class ELFT> 7340 void LLVMELFDumper<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) { 7341 auto PrintEntry = [&](const Elf_Addr *E) { 7342 W.printHex("Address", Parser.getGotAddress(E)); 7343 W.printNumber("Access", Parser.getGotOffset(E)); 7344 W.printHex("Initial", *E); 7345 }; 7346 7347 DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT"); 7348 7349 W.printHex("Canonical gp value", Parser.getGp()); 7350 { 7351 ListScope RS(W, "Reserved entries"); 7352 { 7353 DictScope D(W, "Entry"); 7354 PrintEntry(Parser.getGotLazyResolver()); 7355 W.printString("Purpose", StringRef("Lazy resolver")); 7356 } 7357 7358 if (Parser.getGotModulePointer()) { 7359 DictScope D(W, "Entry"); 7360 PrintEntry(Parser.getGotModulePointer()); 7361 W.printString("Purpose", StringRef("Module pointer (GNU extension)")); 7362 } 7363 } 7364 { 7365 ListScope LS(W, "Local entries"); 7366 for (auto &E : Parser.getLocalEntries()) { 7367 DictScope D(W, "Entry"); 7368 PrintEntry(&E); 7369 } 7370 } 7371 7372 if (Parser.IsStatic) 7373 return; 7374 7375 { 7376 ListScope GS(W, "Global entries"); 7377 for (auto &E : Parser.getGlobalEntries()) { 7378 DictScope D(W, "Entry"); 7379 7380 PrintEntry(&E); 7381 7382 const Elf_Sym &Sym = *Parser.getGotSym(&E); 7383 W.printHex("Value", Sym.st_value); 7384 W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes)); 7385 7386 const unsigned SymIndex = &Sym - this->dynamic_symbols().begin(); 7387 DataRegion<Elf_Word> ShndxTable( 7388 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end()); 7389 printSymbolSection(Sym, SymIndex, ShndxTable); 7390 7391 std::string SymName = this->getFullSymbolName( 7392 Sym, SymIndex, ShndxTable, this->DynamicStringTable, true); 7393 W.printNumber("Name", SymName, Sym.st_name); 7394 } 7395 } 7396 7397 W.printNumber("Number of TLS and multi-GOT entries", 7398 uint64_t(Parser.getOtherEntries().size())); 7399 } 7400 7401 template <class ELFT> 7402 void LLVMELFDumper<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) { 7403 auto PrintEntry = [&](const Elf_Addr *E) { 7404 W.printHex("Address", Parser.getPltAddress(E)); 7405 W.printHex("Initial", *E); 7406 }; 7407 7408 DictScope GS(W, "PLT GOT"); 7409 7410 { 7411 ListScope RS(W, "Reserved entries"); 7412 { 7413 DictScope D(W, "Entry"); 7414 PrintEntry(Parser.getPltLazyResolver()); 7415 W.printString("Purpose", StringRef("PLT lazy resolver")); 7416 } 7417 7418 if (auto E = Parser.getPltModulePointer()) { 7419 DictScope D(W, "Entry"); 7420 PrintEntry(E); 7421 W.printString("Purpose", StringRef("Module pointer")); 7422 } 7423 } 7424 { 7425 ListScope LS(W, "Entries"); 7426 DataRegion<Elf_Word> ShndxTable( 7427 (const Elf_Word *)this->DynSymTabShndxRegion.Addr, this->Obj.end()); 7428 for (auto &E : Parser.getPltEntries()) { 7429 DictScope D(W, "Entry"); 7430 PrintEntry(&E); 7431 7432 const Elf_Sym &Sym = *Parser.getPltSym(&E); 7433 W.printHex("Value", Sym.st_value); 7434 W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes)); 7435 printSymbolSection(Sym, &Sym - this->dynamic_symbols().begin(), 7436 ShndxTable); 7437 7438 const Elf_Sym *FirstSym = cantFail( 7439 this->Obj.template getEntry<Elf_Sym>(*Parser.getPltSymTable(), 0)); 7440 std::string SymName = this->getFullSymbolName( 7441 Sym, &Sym - FirstSym, ShndxTable, Parser.getPltStrTable(), true); 7442 W.printNumber("Name", SymName, Sym.st_name); 7443 } 7444 } 7445 } 7446 7447 template <class ELFT> void LLVMELFDumper<ELFT>::printMipsABIFlags() { 7448 const Elf_Mips_ABIFlags<ELFT> *Flags; 7449 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr = 7450 getMipsAbiFlagsSection(*this)) { 7451 Flags = *SecOrErr; 7452 if (!Flags) { 7453 W.startLine() << "There is no .MIPS.abiflags section in the file.\n"; 7454 return; 7455 } 7456 } else { 7457 this->reportUniqueWarning(SecOrErr.takeError()); 7458 return; 7459 } 7460 7461 raw_ostream &OS = W.getOStream(); 7462 DictScope GS(W, "MIPS ABI Flags"); 7463 7464 W.printNumber("Version", Flags->version); 7465 W.startLine() << "ISA: "; 7466 if (Flags->isa_rev <= 1) 7467 OS << format("MIPS%u", Flags->isa_level); 7468 else 7469 OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev); 7470 OS << "\n"; 7471 W.printEnum("ISA Extension", Flags->isa_ext, makeArrayRef(ElfMipsISAExtType)); 7472 W.printFlags("ASEs", Flags->ases, makeArrayRef(ElfMipsASEFlags)); 7473 W.printEnum("FP ABI", Flags->fp_abi, makeArrayRef(ElfMipsFpABIType)); 7474 W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size)); 7475 W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size)); 7476 W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size)); 7477 W.printFlags("Flags 1", Flags->flags1, makeArrayRef(ElfMipsFlags1)); 7478 W.printHex("Flags 2", Flags->flags2); 7479 } 7480 7481 template <class ELFT> 7482 void JSONELFDumper<ELFT>::printFileSummary(StringRef FileStr, ObjectFile &Obj, 7483 ArrayRef<std::string> InputFilenames, 7484 const Archive *A) { 7485 FileScope = std::make_unique<DictScope>(this->W, FileStr); 7486 DictScope D(this->W, "FileSummary"); 7487 this->W.printString("File", FileStr); 7488 this->W.printString("Format", Obj.getFileFormatName()); 7489 this->W.printString("Arch", Triple::getArchTypeName(Obj.getArch())); 7490 this->W.printString( 7491 "AddressSize", 7492 std::string(formatv("{0}bit", 8 * Obj.getBytesInAddress()))); 7493 this->printLoadName(); 7494 } 7495