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