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