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