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