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