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