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 using Elf_Sym = typename ELFT::Sym; 4497 auto WarnAndReturn = [&](const Elf_Sym *Sym, 4498 const Twine &Reason) -> RelSymbol<ELFT> { 4499 reportWarning( 4500 createError("unable to get name of the dynamic symbol with index " + 4501 Twine(Reloc.Symbol) + ": " + Reason), 4502 FileName); 4503 return {Sym, "<corrupt>"}; 4504 }; 4505 4506 ArrayRef<Elf_Sym> Symbols = Dumper.dynamic_symbols(); 4507 const Elf_Sym *FirstSym = Symbols.begin(); 4508 if (!FirstSym) 4509 return WarnAndReturn(nullptr, "no dynamic symbol table found"); 4510 4511 // We might have an object without a section header. In this case the size of 4512 // Symbols is zero, because there is no way to know the size of the dynamic 4513 // table. We should allow this case and not print a warning. 4514 if (!Symbols.empty() && Reloc.Symbol >= Symbols.size()) 4515 return WarnAndReturn( 4516 nullptr, 4517 "index is greater than or equal to the number of dynamic symbols (" + 4518 Twine(Symbols.size()) + ")"); 4519 4520 const uint64_t FileSize = Obj.getBufSize(); 4521 const uint64_t SymOffset = ((const uint8_t *)FirstSym - Obj.base()) + 4522 (uint64_t)Reloc.Symbol * sizeof(Elf_Sym); 4523 if (SymOffset + sizeof(Elf_Sym) > FileSize) 4524 return WarnAndReturn(nullptr, "symbol at 0x" + Twine::utohexstr(SymOffset) + 4525 " goes past the end of the file (0x" + 4526 Twine::utohexstr(FileSize) + ")"); 4527 4528 const Elf_Sym *Sym = FirstSym + Reloc.Symbol; 4529 Expected<StringRef> ErrOrName = Sym->getName(Dumper.getDynamicStringTable()); 4530 if (!ErrOrName) 4531 return WarnAndReturn(Sym, toString(ErrOrName.takeError())); 4532 4533 return {Sym == FirstSym ? nullptr : Sym, maybeDemangle(*ErrOrName)}; 4534 } 4535 } // namespace 4536 4537 template <class ELFT> 4538 void GNUStyle<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) { 4539 printRelRelaReloc( 4540 R, getSymbolForReloc(this->Obj, this->FileName, this->dumper(), R)); 4541 } 4542 4543 template <class ELFT> 4544 static size_t getMaxDynamicTagSize(const ELFFile<ELFT> &Obj, 4545 typename ELFT::DynRange Tags) { 4546 size_t Max = 0; 4547 for (const typename ELFT::Dyn &Dyn : Tags) 4548 Max = std::max(Max, Obj.getDynamicTagAsString(Dyn.d_tag).size()); 4549 return Max; 4550 } 4551 4552 template <class ELFT> void GNUStyle<ELFT>::printDynamic() { 4553 Elf_Dyn_Range Table = this->dumper().dynamic_table(); 4554 if (Table.empty()) 4555 return; 4556 4557 OS << "Dynamic section at offset " 4558 << format_hex(reinterpret_cast<const uint8_t *>( 4559 this->dumper().getDynamicTableRegion().Addr) - 4560 this->Obj.base(), 4561 1) 4562 << " contains " << Table.size() << " entries:\n"; 4563 4564 // The type name is surrounded with round brackets, hence add 2. 4565 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table) + 2; 4566 // The "Name/Value" column should be indented from the "Type" column by N 4567 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing 4568 // space (1) = 3. 4569 OS << " Tag" + std::string(ELFT::Is64Bits ? 16 : 8, ' ') + "Type" 4570 << std::string(MaxTagSize - 3, ' ') << "Name/Value\n"; 4571 4572 std::string ValueFmt = " %-" + std::to_string(MaxTagSize) + "s "; 4573 for (auto Entry : Table) { 4574 uintX_t Tag = Entry.getTag(); 4575 std::string Type = 4576 std::string("(") + this->Obj.getDynamicTagAsString(Tag).c_str() + ")"; 4577 std::string Value = this->dumper().getDynamicEntry(Tag, Entry.getVal()); 4578 OS << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10) 4579 << format(ValueFmt.c_str(), Type.c_str()) << Value << "\n"; 4580 } 4581 } 4582 4583 template <class ELFT> void GNUStyle<ELFT>::printDynamicRelocations() { 4584 this->printDynamicRelocationsHelper(); 4585 } 4586 4587 template <class ELFT> void DumpStyle<ELFT>::printDynamicRelocationsHelper() { 4588 const bool IsMips64EL = this->Obj.isMips64EL(); 4589 const DynRegionInfo &DynRelaRegion = this->dumper().getDynRelaRegion(); 4590 if (DynRelaRegion.Size > 0) { 4591 printDynamicRelocHeader(ELF::SHT_RELA, "RELA", DynRelaRegion); 4592 for (const Elf_Rela &Rela : this->dumper().dyn_relas()) 4593 printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL)); 4594 } 4595 4596 const DynRegionInfo &DynRelRegion = this->dumper().getDynRelRegion(); 4597 if (DynRelRegion.Size > 0) { 4598 printDynamicRelocHeader(ELF::SHT_REL, "REL", DynRelRegion); 4599 for (const Elf_Rel &Rel : this->dumper().dyn_rels()) 4600 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL)); 4601 } 4602 4603 const DynRegionInfo &DynRelrRegion = this->dumper().getDynRelrRegion(); 4604 if (DynRelrRegion.Size > 0) { 4605 printDynamicRelocHeader(ELF::SHT_REL, "RELR", DynRelrRegion); 4606 Elf_Relr_Range Relrs = this->dumper().dyn_relrs(); 4607 for (const Elf_Rel &Rel : Obj.decode_relrs(Relrs)) 4608 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL)); 4609 } 4610 4611 const DynRegionInfo &DynPLTRelRegion = this->dumper().getDynPLTRelRegion(); 4612 if (DynPLTRelRegion.Size) { 4613 if (DynPLTRelRegion.EntSize == sizeof(Elf_Rela)) { 4614 printDynamicRelocHeader(ELF::SHT_RELA, "PLT", DynPLTRelRegion); 4615 for (const Elf_Rela &Rela : DynPLTRelRegion.getAsArrayRef<Elf_Rela>()) 4616 printDynamicReloc(Relocation<ELFT>(Rela, IsMips64EL)); 4617 } else { 4618 printDynamicRelocHeader(ELF::SHT_REL, "PLT", DynPLTRelRegion); 4619 for (const Elf_Rel &Rel : DynPLTRelRegion.getAsArrayRef<Elf_Rel>()) 4620 printDynamicReloc(Relocation<ELFT>(Rel, IsMips64EL)); 4621 } 4622 } 4623 } 4624 4625 template <class ELFT> 4626 void GNUStyle<ELFT>::printGNUVersionSectionProlog( 4627 const typename ELFT::Shdr *Sec, const Twine &Label, unsigned EntriesNum) { 4628 StringRef SecName = 4629 unwrapOrError(this->FileName, this->Obj.getSectionName(*Sec)); 4630 OS << Label << " section '" << SecName << "' " 4631 << "contains " << EntriesNum << " entries:\n"; 4632 4633 StringRef SymTabName = "<corrupt>"; 4634 Expected<const typename ELFT::Shdr *> SymTabOrErr = 4635 this->Obj.getSection(Sec->sh_link); 4636 if (SymTabOrErr) 4637 SymTabName = 4638 unwrapOrError(this->FileName, this->Obj.getSectionName(**SymTabOrErr)); 4639 else 4640 this->reportUniqueWarning(createError("invalid section linked to " + 4641 describe(this->Obj, *Sec) + ": " + 4642 toString(SymTabOrErr.takeError()))); 4643 4644 OS << " Addr: " << format_hex_no_prefix(Sec->sh_addr, 16) 4645 << " Offset: " << format_hex(Sec->sh_offset, 8) 4646 << " Link: " << Sec->sh_link << " (" << SymTabName << ")\n"; 4647 } 4648 4649 template <class ELFT> 4650 void GNUStyle<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) { 4651 if (!Sec) 4652 return; 4653 4654 printGNUVersionSectionProlog(Sec, "Version symbols", 4655 Sec->sh_size / sizeof(Elf_Versym)); 4656 Expected<ArrayRef<Elf_Versym>> VerTableOrErr = 4657 this->dumper().getVersionTable(*Sec, /*SymTab=*/nullptr, 4658 /*StrTab=*/nullptr); 4659 if (!VerTableOrErr) { 4660 this->reportUniqueWarning(VerTableOrErr.takeError()); 4661 return; 4662 } 4663 4664 ArrayRef<Elf_Versym> VerTable = *VerTableOrErr; 4665 std::vector<StringRef> Versions; 4666 for (size_t I = 0, E = VerTable.size(); I < E; ++I) { 4667 unsigned Ndx = VerTable[I].vs_index; 4668 if (Ndx == VER_NDX_LOCAL || Ndx == VER_NDX_GLOBAL) { 4669 Versions.emplace_back(Ndx == VER_NDX_LOCAL ? "*local*" : "*global*"); 4670 continue; 4671 } 4672 4673 bool IsDefault; 4674 Expected<StringRef> NameOrErr = 4675 this->dumper().getSymbolVersionByIndex(Ndx, IsDefault); 4676 if (!NameOrErr) { 4677 this->reportUniqueWarning(createError( 4678 "unable to get a version for entry " + Twine(I) + " of " + 4679 describe(this->Obj, *Sec) + ": " + toString(NameOrErr.takeError()))); 4680 Versions.emplace_back("<corrupt>"); 4681 continue; 4682 } 4683 Versions.emplace_back(*NameOrErr); 4684 } 4685 4686 // readelf prints 4 entries per line. 4687 uint64_t Entries = VerTable.size(); 4688 for (uint64_t VersymRow = 0; VersymRow < Entries; VersymRow += 4) { 4689 OS << " " << format_hex_no_prefix(VersymRow, 3) << ":"; 4690 for (uint64_t I = 0; (I < 4) && (I + VersymRow) < Entries; ++I) { 4691 unsigned Ndx = VerTable[VersymRow + I].vs_index; 4692 OS << format("%4x%c", Ndx & VERSYM_VERSION, 4693 Ndx & VERSYM_HIDDEN ? 'h' : ' '); 4694 OS << left_justify("(" + std::string(Versions[VersymRow + I]) + ")", 13); 4695 } 4696 OS << '\n'; 4697 } 4698 OS << '\n'; 4699 } 4700 4701 static std::string versionFlagToString(unsigned Flags) { 4702 if (Flags == 0) 4703 return "none"; 4704 4705 std::string Ret; 4706 auto AddFlag = [&Ret, &Flags](unsigned Flag, StringRef Name) { 4707 if (!(Flags & Flag)) 4708 return; 4709 if (!Ret.empty()) 4710 Ret += " | "; 4711 Ret += Name; 4712 Flags &= ~Flag; 4713 }; 4714 4715 AddFlag(VER_FLG_BASE, "BASE"); 4716 AddFlag(VER_FLG_WEAK, "WEAK"); 4717 AddFlag(VER_FLG_INFO, "INFO"); 4718 AddFlag(~0, "<unknown>"); 4719 return Ret; 4720 } 4721 4722 template <class ELFT> 4723 void GNUStyle<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) { 4724 if (!Sec) 4725 return; 4726 4727 printGNUVersionSectionProlog(Sec, "Version definition", Sec->sh_info); 4728 4729 Expected<std::vector<VerDef>> V = this->dumper().getVersionDefinitions(*Sec); 4730 if (!V) { 4731 this->reportUniqueWarning(V.takeError()); 4732 return; 4733 } 4734 4735 for (const VerDef &Def : *V) { 4736 OS << format(" 0x%04x: Rev: %u Flags: %s Index: %u Cnt: %u Name: %s\n", 4737 Def.Offset, Def.Version, 4738 versionFlagToString(Def.Flags).c_str(), Def.Ndx, Def.Cnt, 4739 Def.Name.data()); 4740 unsigned I = 0; 4741 for (const VerdAux &Aux : Def.AuxV) 4742 OS << format(" 0x%04x: Parent %u: %s\n", Aux.Offset, ++I, 4743 Aux.Name.data()); 4744 } 4745 4746 OS << '\n'; 4747 } 4748 4749 template <class ELFT> 4750 void GNUStyle<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) { 4751 if (!Sec) 4752 return; 4753 4754 unsigned VerneedNum = Sec->sh_info; 4755 printGNUVersionSectionProlog(Sec, "Version needs", VerneedNum); 4756 4757 Expected<std::vector<VerNeed>> V = 4758 this->dumper().getVersionDependencies(*Sec); 4759 if (!V) { 4760 this->reportUniqueWarning(V.takeError()); 4761 return; 4762 } 4763 4764 for (const VerNeed &VN : *V) { 4765 OS << format(" 0x%04x: Version: %u File: %s Cnt: %u\n", VN.Offset, 4766 VN.Version, VN.File.data(), VN.Cnt); 4767 for (const VernAux &Aux : VN.AuxV) 4768 OS << format(" 0x%04x: Name: %s Flags: %s Version: %u\n", Aux.Offset, 4769 Aux.Name.data(), versionFlagToString(Aux.Flags).c_str(), 4770 Aux.Other); 4771 } 4772 OS << '\n'; 4773 } 4774 4775 template <class ELFT> 4776 void GNUStyle<ELFT>::printHashHistogram(const Elf_Hash &HashTable) { 4777 size_t NBucket = HashTable.nbucket; 4778 size_t NChain = HashTable.nchain; 4779 ArrayRef<Elf_Word> Buckets = HashTable.buckets(); 4780 ArrayRef<Elf_Word> Chains = HashTable.chains(); 4781 size_t TotalSyms = 0; 4782 // If hash table is correct, we have at least chains with 0 length 4783 size_t MaxChain = 1; 4784 size_t CumulativeNonZero = 0; 4785 4786 if (NChain == 0 || NBucket == 0) 4787 return; 4788 4789 std::vector<size_t> ChainLen(NBucket, 0); 4790 // Go over all buckets and and note chain lengths of each bucket (total 4791 // unique chain lengths). 4792 for (size_t B = 0; B < NBucket; B++) { 4793 std::vector<bool> Visited(NChain); 4794 for (size_t C = Buckets[B]; C < NChain; C = Chains[C]) { 4795 if (C == ELF::STN_UNDEF) 4796 break; 4797 if (Visited[C]) { 4798 reportWarning(createError(".hash section is invalid: bucket " + 4799 Twine(C) + 4800 ": a cycle was detected in the linked chain"), 4801 this->FileName); 4802 break; 4803 } 4804 Visited[C] = true; 4805 if (MaxChain <= ++ChainLen[B]) 4806 MaxChain++; 4807 } 4808 TotalSyms += ChainLen[B]; 4809 } 4810 4811 if (!TotalSyms) 4812 return; 4813 4814 std::vector<size_t> Count(MaxChain, 0); 4815 // Count how long is the chain for each bucket 4816 for (size_t B = 0; B < NBucket; B++) 4817 ++Count[ChainLen[B]]; 4818 // Print Number of buckets with each chain lengths and their cumulative 4819 // coverage of the symbols 4820 OS << "Histogram for bucket list length (total of " << NBucket 4821 << " buckets)\n" 4822 << " Length Number % of total Coverage\n"; 4823 for (size_t I = 0; I < MaxChain; I++) { 4824 CumulativeNonZero += Count[I] * I; 4825 OS << format("%7lu %-10lu (%5.1f%%) %5.1f%%\n", I, Count[I], 4826 (Count[I] * 100.0) / NBucket, 4827 (CumulativeNonZero * 100.0) / TotalSyms); 4828 } 4829 } 4830 4831 template <class ELFT> 4832 void GNUStyle<ELFT>::printGnuHashHistogram(const Elf_GnuHash &GnuHashTable) { 4833 Expected<ArrayRef<Elf_Word>> ChainsOrErr = getGnuHashTableChains<ELFT>( 4834 this->dumper().getDynSymRegion(), &GnuHashTable); 4835 if (!ChainsOrErr) { 4836 this->reportUniqueWarning( 4837 createError("unable to print the GNU hash table histogram: " + 4838 toString(ChainsOrErr.takeError()))); 4839 return; 4840 } 4841 4842 ArrayRef<Elf_Word> Chains = *ChainsOrErr; 4843 size_t Symndx = GnuHashTable.symndx; 4844 size_t TotalSyms = 0; 4845 size_t MaxChain = 1; 4846 size_t CumulativeNonZero = 0; 4847 4848 size_t NBucket = GnuHashTable.nbuckets; 4849 if (Chains.empty() || NBucket == 0) 4850 return; 4851 4852 ArrayRef<Elf_Word> Buckets = GnuHashTable.buckets(); 4853 std::vector<size_t> ChainLen(NBucket, 0); 4854 for (size_t B = 0; B < NBucket; B++) { 4855 if (!Buckets[B]) 4856 continue; 4857 size_t Len = 1; 4858 for (size_t C = Buckets[B] - Symndx; 4859 C < Chains.size() && (Chains[C] & 1) == 0; C++) 4860 if (MaxChain < ++Len) 4861 MaxChain++; 4862 ChainLen[B] = Len; 4863 TotalSyms += Len; 4864 } 4865 MaxChain++; 4866 4867 if (!TotalSyms) 4868 return; 4869 4870 std::vector<size_t> Count(MaxChain, 0); 4871 for (size_t B = 0; B < NBucket; B++) 4872 ++Count[ChainLen[B]]; 4873 // Print Number of buckets with each chain lengths and their cumulative 4874 // coverage of the symbols 4875 OS << "Histogram for `.gnu.hash' bucket list length (total of " << NBucket 4876 << " buckets)\n" 4877 << " Length Number % of total Coverage\n"; 4878 for (size_t I = 0; I < MaxChain; I++) { 4879 CumulativeNonZero += Count[I] * I; 4880 OS << format("%7lu %-10lu (%5.1f%%) %5.1f%%\n", I, Count[I], 4881 (Count[I] * 100.0) / NBucket, 4882 (CumulativeNonZero * 100.0) / TotalSyms); 4883 } 4884 } 4885 4886 // Hash histogram shows statistics of how efficient the hash was for the 4887 // dynamic symbol table. The table shows the number of hash buckets for 4888 // different lengths of chains as an absolute number and percentage of the total 4889 // buckets, and the cumulative coverage of symbols for each set of buckets. 4890 template <class ELFT> void GNUStyle<ELFT>::printHashHistograms() { 4891 // Print histogram for the .hash section. 4892 if (const Elf_Hash *HashTable = this->dumper().getHashTable()) { 4893 if (Error E = checkHashTable<ELFT>(this->dumper(), HashTable)) 4894 this->reportUniqueWarning(std::move(E)); 4895 else 4896 printHashHistogram(*HashTable); 4897 } 4898 4899 // Print histogram for the .gnu.hash section. 4900 if (const Elf_GnuHash *GnuHashTable = this->dumper().getGnuHashTable()) { 4901 if (Error E = checkGNUHashTable<ELFT>(this->Obj, GnuHashTable)) 4902 this->reportUniqueWarning(std::move(E)); 4903 else 4904 printGnuHashHistogram(*GnuHashTable); 4905 } 4906 } 4907 4908 template <class ELFT> void GNUStyle<ELFT>::printCGProfile() { 4909 OS << "GNUStyle::printCGProfile not implemented\n"; 4910 } 4911 4912 static Expected<std::vector<uint64_t>> toULEB128Array(ArrayRef<uint8_t> Data) { 4913 std::vector<uint64_t> Ret; 4914 const uint8_t *Cur = Data.begin(); 4915 const uint8_t *End = Data.end(); 4916 while (Cur != End) { 4917 unsigned Size; 4918 const char *Err; 4919 Ret.push_back(decodeULEB128(Cur, &Size, End, &Err)); 4920 if (Err) 4921 return createError(Err); 4922 Cur += Size; 4923 } 4924 return Ret; 4925 } 4926 4927 template <class ELFT> 4928 static Expected<std::vector<uint64_t>> 4929 decodeAddrsigSection(const ELFFile<ELFT> &Obj, const typename ELFT::Shdr &Sec) { 4930 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Sec); 4931 if (!ContentsOrErr) 4932 return ContentsOrErr.takeError(); 4933 4934 if (Expected<std::vector<uint64_t>> SymsOrErr = 4935 toULEB128Array(*ContentsOrErr)) 4936 return *SymsOrErr; 4937 else 4938 return createError("unable to decode " + describe(Obj, Sec) + ": " + 4939 toString(SymsOrErr.takeError())); 4940 } 4941 4942 template <class ELFT> void GNUStyle<ELFT>::printAddrsig() { 4943 const Elf_Shdr *Sec = this->dumper().getDotAddrsigSec(); 4944 if (!Sec) 4945 return; 4946 4947 Expected<std::vector<uint64_t>> SymsOrErr = 4948 decodeAddrsigSection(this->Obj, *Sec); 4949 if (!SymsOrErr) { 4950 this->reportUniqueWarning(SymsOrErr.takeError()); 4951 return; 4952 } 4953 4954 StringRef Name = this->getPrintableSectionName(*Sec); 4955 OS << "\nAddress-significant symbols section '" << Name << "'" 4956 << " contains " << SymsOrErr->size() << " entries:\n"; 4957 OS << " Num: Name\n"; 4958 4959 Field Fields[2] = {0, 8}; 4960 size_t SymIndex = 0; 4961 for (uint64_t Sym : *SymsOrErr) { 4962 Fields[0].Str = to_string(format_decimal(++SymIndex, 6)) + ":"; 4963 Fields[1].Str = this->dumper().getStaticSymbolName(Sym); 4964 for (const Field &Entry : Fields) 4965 printField(Entry); 4966 OS << "\n"; 4967 } 4968 } 4969 4970 template <typename ELFT> 4971 static std::string getGNUProperty(uint32_t Type, uint32_t DataSize, 4972 ArrayRef<uint8_t> Data) { 4973 std::string str; 4974 raw_string_ostream OS(str); 4975 uint32_t PrData; 4976 auto DumpBit = [&](uint32_t Flag, StringRef Name) { 4977 if (PrData & Flag) { 4978 PrData &= ~Flag; 4979 OS << Name; 4980 if (PrData) 4981 OS << ", "; 4982 } 4983 }; 4984 4985 switch (Type) { 4986 default: 4987 OS << format("<application-specific type 0x%x>", Type); 4988 return OS.str(); 4989 case GNU_PROPERTY_STACK_SIZE: { 4990 OS << "stack size: "; 4991 if (DataSize == sizeof(typename ELFT::uint)) 4992 OS << formatv("{0:x}", 4993 (uint64_t)(*(const typename ELFT::Addr *)Data.data())); 4994 else 4995 OS << format("<corrupt length: 0x%x>", DataSize); 4996 return OS.str(); 4997 } 4998 case GNU_PROPERTY_NO_COPY_ON_PROTECTED: 4999 OS << "no copy on protected"; 5000 if (DataSize) 5001 OS << format(" <corrupt length: 0x%x>", DataSize); 5002 return OS.str(); 5003 case GNU_PROPERTY_AARCH64_FEATURE_1_AND: 5004 case GNU_PROPERTY_X86_FEATURE_1_AND: 5005 OS << ((Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) ? "aarch64 feature: " 5006 : "x86 feature: "); 5007 if (DataSize != 4) { 5008 OS << format("<corrupt length: 0x%x>", DataSize); 5009 return OS.str(); 5010 } 5011 PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data()); 5012 if (PrData == 0) { 5013 OS << "<None>"; 5014 return OS.str(); 5015 } 5016 if (Type == GNU_PROPERTY_AARCH64_FEATURE_1_AND) { 5017 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_BTI, "BTI"); 5018 DumpBit(GNU_PROPERTY_AARCH64_FEATURE_1_PAC, "PAC"); 5019 } else { 5020 DumpBit(GNU_PROPERTY_X86_FEATURE_1_IBT, "IBT"); 5021 DumpBit(GNU_PROPERTY_X86_FEATURE_1_SHSTK, "SHSTK"); 5022 } 5023 if (PrData) 5024 OS << format("<unknown flags: 0x%x>", PrData); 5025 return OS.str(); 5026 case GNU_PROPERTY_X86_ISA_1_NEEDED: 5027 case GNU_PROPERTY_X86_ISA_1_USED: 5028 OS << "x86 ISA " 5029 << (Type == GNU_PROPERTY_X86_ISA_1_NEEDED ? "needed: " : "used: "); 5030 if (DataSize != 4) { 5031 OS << format("<corrupt length: 0x%x>", DataSize); 5032 return OS.str(); 5033 } 5034 PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data()); 5035 if (PrData == 0) { 5036 OS << "<None>"; 5037 return OS.str(); 5038 } 5039 DumpBit(GNU_PROPERTY_X86_ISA_1_CMOV, "CMOV"); 5040 DumpBit(GNU_PROPERTY_X86_ISA_1_SSE, "SSE"); 5041 DumpBit(GNU_PROPERTY_X86_ISA_1_SSE2, "SSE2"); 5042 DumpBit(GNU_PROPERTY_X86_ISA_1_SSE3, "SSE3"); 5043 DumpBit(GNU_PROPERTY_X86_ISA_1_SSSE3, "SSSE3"); 5044 DumpBit(GNU_PROPERTY_X86_ISA_1_SSE4_1, "SSE4_1"); 5045 DumpBit(GNU_PROPERTY_X86_ISA_1_SSE4_2, "SSE4_2"); 5046 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX, "AVX"); 5047 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX2, "AVX2"); 5048 DumpBit(GNU_PROPERTY_X86_ISA_1_FMA, "FMA"); 5049 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512F, "AVX512F"); 5050 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512CD, "AVX512CD"); 5051 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512ER, "AVX512ER"); 5052 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512PF, "AVX512PF"); 5053 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512VL, "AVX512VL"); 5054 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512DQ, "AVX512DQ"); 5055 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512BW, "AVX512BW"); 5056 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_4FMAPS, "AVX512_4FMAPS"); 5057 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_4VNNIW, "AVX512_4VNNIW"); 5058 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_BITALG, "AVX512_BITALG"); 5059 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_IFMA, "AVX512_IFMA"); 5060 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_VBMI, "AVX512_VBMI"); 5061 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_VBMI2, "AVX512_VBMI2"); 5062 DumpBit(GNU_PROPERTY_X86_ISA_1_AVX512_VNNI, "AVX512_VNNI"); 5063 if (PrData) 5064 OS << format("<unknown flags: 0x%x>", PrData); 5065 return OS.str(); 5066 break; 5067 case GNU_PROPERTY_X86_FEATURE_2_NEEDED: 5068 case GNU_PROPERTY_X86_FEATURE_2_USED: 5069 OS << "x86 feature " 5070 << (Type == GNU_PROPERTY_X86_FEATURE_2_NEEDED ? "needed: " : "used: "); 5071 if (DataSize != 4) { 5072 OS << format("<corrupt length: 0x%x>", DataSize); 5073 return OS.str(); 5074 } 5075 PrData = support::endian::read32<ELFT::TargetEndianness>(Data.data()); 5076 if (PrData == 0) { 5077 OS << "<None>"; 5078 return OS.str(); 5079 } 5080 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X86, "x86"); 5081 DumpBit(GNU_PROPERTY_X86_FEATURE_2_X87, "x87"); 5082 DumpBit(GNU_PROPERTY_X86_FEATURE_2_MMX, "MMX"); 5083 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XMM, "XMM"); 5084 DumpBit(GNU_PROPERTY_X86_FEATURE_2_YMM, "YMM"); 5085 DumpBit(GNU_PROPERTY_X86_FEATURE_2_ZMM, "ZMM"); 5086 DumpBit(GNU_PROPERTY_X86_FEATURE_2_FXSR, "FXSR"); 5087 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVE, "XSAVE"); 5088 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT, "XSAVEOPT"); 5089 DumpBit(GNU_PROPERTY_X86_FEATURE_2_XSAVEC, "XSAVEC"); 5090 if (PrData) 5091 OS << format("<unknown flags: 0x%x>", PrData); 5092 return OS.str(); 5093 } 5094 } 5095 5096 template <typename ELFT> 5097 static SmallVector<std::string, 4> getGNUPropertyList(ArrayRef<uint8_t> Arr) { 5098 using Elf_Word = typename ELFT::Word; 5099 5100 SmallVector<std::string, 4> Properties; 5101 while (Arr.size() >= 8) { 5102 uint32_t Type = *reinterpret_cast<const Elf_Word *>(Arr.data()); 5103 uint32_t DataSize = *reinterpret_cast<const Elf_Word *>(Arr.data() + 4); 5104 Arr = Arr.drop_front(8); 5105 5106 // Take padding size into account if present. 5107 uint64_t PaddedSize = alignTo(DataSize, sizeof(typename ELFT::uint)); 5108 std::string str; 5109 raw_string_ostream OS(str); 5110 if (Arr.size() < PaddedSize) { 5111 OS << format("<corrupt type (0x%x) datasz: 0x%x>", Type, DataSize); 5112 Properties.push_back(OS.str()); 5113 break; 5114 } 5115 Properties.push_back( 5116 getGNUProperty<ELFT>(Type, DataSize, Arr.take_front(PaddedSize))); 5117 Arr = Arr.drop_front(PaddedSize); 5118 } 5119 5120 if (!Arr.empty()) 5121 Properties.push_back("<corrupted GNU_PROPERTY_TYPE_0>"); 5122 5123 return Properties; 5124 } 5125 5126 struct GNUAbiTag { 5127 std::string OSName; 5128 std::string ABI; 5129 bool IsValid; 5130 }; 5131 5132 template <typename ELFT> static GNUAbiTag getGNUAbiTag(ArrayRef<uint8_t> Desc) { 5133 typedef typename ELFT::Word Elf_Word; 5134 5135 ArrayRef<Elf_Word> Words(reinterpret_cast<const Elf_Word *>(Desc.begin()), 5136 reinterpret_cast<const Elf_Word *>(Desc.end())); 5137 5138 if (Words.size() < 4) 5139 return {"", "", /*IsValid=*/false}; 5140 5141 static const char *OSNames[] = { 5142 "Linux", "Hurd", "Solaris", "FreeBSD", "NetBSD", "Syllable", "NaCl", 5143 }; 5144 StringRef OSName = "Unknown"; 5145 if (Words[0] < array_lengthof(OSNames)) 5146 OSName = OSNames[Words[0]]; 5147 uint32_t Major = Words[1], Minor = Words[2], Patch = Words[3]; 5148 std::string str; 5149 raw_string_ostream ABI(str); 5150 ABI << Major << "." << Minor << "." << Patch; 5151 return {std::string(OSName), ABI.str(), /*IsValid=*/true}; 5152 } 5153 5154 static std::string getGNUBuildId(ArrayRef<uint8_t> Desc) { 5155 std::string str; 5156 raw_string_ostream OS(str); 5157 for (uint8_t B : Desc) 5158 OS << format_hex_no_prefix(B, 2); 5159 return OS.str(); 5160 } 5161 5162 static StringRef getGNUGoldVersion(ArrayRef<uint8_t> Desc) { 5163 return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size()); 5164 } 5165 5166 template <typename ELFT> 5167 static void printGNUNote(raw_ostream &OS, uint32_t NoteType, 5168 ArrayRef<uint8_t> Desc) { 5169 switch (NoteType) { 5170 default: 5171 return; 5172 case ELF::NT_GNU_ABI_TAG: { 5173 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc); 5174 if (!AbiTag.IsValid) 5175 OS << " <corrupt GNU_ABI_TAG>"; 5176 else 5177 OS << " OS: " << AbiTag.OSName << ", ABI: " << AbiTag.ABI; 5178 break; 5179 } 5180 case ELF::NT_GNU_BUILD_ID: { 5181 OS << " Build ID: " << getGNUBuildId(Desc); 5182 break; 5183 } 5184 case ELF::NT_GNU_GOLD_VERSION: 5185 OS << " Version: " << getGNUGoldVersion(Desc); 5186 break; 5187 case ELF::NT_GNU_PROPERTY_TYPE_0: 5188 OS << " Properties:"; 5189 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc)) 5190 OS << " " << Property << "\n"; 5191 break; 5192 } 5193 OS << '\n'; 5194 } 5195 5196 struct AMDNote { 5197 std::string Type; 5198 std::string Value; 5199 }; 5200 5201 template <typename ELFT> 5202 static AMDNote getAMDNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) { 5203 switch (NoteType) { 5204 default: 5205 return {"", ""}; 5206 case ELF::NT_AMD_AMDGPU_HSA_METADATA: 5207 return { 5208 "HSA Metadata", 5209 std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())}; 5210 case ELF::NT_AMD_AMDGPU_ISA: 5211 return { 5212 "ISA Version", 5213 std::string(reinterpret_cast<const char *>(Desc.data()), Desc.size())}; 5214 } 5215 } 5216 5217 struct AMDGPUNote { 5218 std::string Type; 5219 std::string Value; 5220 }; 5221 5222 template <typename ELFT> 5223 static AMDGPUNote getAMDGPUNote(uint32_t NoteType, ArrayRef<uint8_t> Desc) { 5224 switch (NoteType) { 5225 default: 5226 return {"", ""}; 5227 case ELF::NT_AMDGPU_METADATA: { 5228 StringRef MsgPackString = 5229 StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size()); 5230 msgpack::Document MsgPackDoc; 5231 if (!MsgPackDoc.readFromBlob(MsgPackString, /*Multi=*/false)) 5232 return {"AMDGPU Metadata", "Invalid AMDGPU Metadata"}; 5233 5234 AMDGPU::HSAMD::V3::MetadataVerifier Verifier(true); 5235 std::string HSAMetadataString; 5236 if (!Verifier.verify(MsgPackDoc.getRoot())) 5237 HSAMetadataString = "Invalid AMDGPU Metadata\n"; 5238 5239 raw_string_ostream StrOS(HSAMetadataString); 5240 MsgPackDoc.toYAML(StrOS); 5241 5242 return {"AMDGPU Metadata", StrOS.str()}; 5243 } 5244 } 5245 } 5246 5247 struct CoreFileMapping { 5248 uint64_t Start, End, Offset; 5249 StringRef Filename; 5250 }; 5251 5252 struct CoreNote { 5253 uint64_t PageSize; 5254 std::vector<CoreFileMapping> Mappings; 5255 }; 5256 5257 static Expected<CoreNote> readCoreNote(DataExtractor Desc) { 5258 // Expected format of the NT_FILE note description: 5259 // 1. # of file mappings (call it N) 5260 // 2. Page size 5261 // 3. N (start, end, offset) triples 5262 // 4. N packed filenames (null delimited) 5263 // Each field is an Elf_Addr, except for filenames which are char* strings. 5264 5265 CoreNote Ret; 5266 const int Bytes = Desc.getAddressSize(); 5267 5268 if (!Desc.isValidOffsetForAddress(2)) 5269 return createStringError(object_error::parse_failed, 5270 "malformed note: header too short"); 5271 if (Desc.getData().back() != 0) 5272 return createStringError(object_error::parse_failed, 5273 "malformed note: not NUL terminated"); 5274 5275 uint64_t DescOffset = 0; 5276 uint64_t FileCount = Desc.getAddress(&DescOffset); 5277 Ret.PageSize = Desc.getAddress(&DescOffset); 5278 5279 if (!Desc.isValidOffsetForAddress(3 * FileCount * Bytes)) 5280 return createStringError(object_error::parse_failed, 5281 "malformed note: too short for number of files"); 5282 5283 uint64_t FilenamesOffset = 0; 5284 DataExtractor Filenames( 5285 Desc.getData().drop_front(DescOffset + 3 * FileCount * Bytes), 5286 Desc.isLittleEndian(), Desc.getAddressSize()); 5287 5288 Ret.Mappings.resize(FileCount); 5289 for (CoreFileMapping &Mapping : Ret.Mappings) { 5290 if (!Filenames.isValidOffsetForDataOfSize(FilenamesOffset, 1)) 5291 return createStringError(object_error::parse_failed, 5292 "malformed note: too few filenames"); 5293 Mapping.Start = Desc.getAddress(&DescOffset); 5294 Mapping.End = Desc.getAddress(&DescOffset); 5295 Mapping.Offset = Desc.getAddress(&DescOffset); 5296 Mapping.Filename = Filenames.getCStrRef(&FilenamesOffset); 5297 } 5298 5299 return Ret; 5300 } 5301 5302 template <typename ELFT> 5303 static void printCoreNote(raw_ostream &OS, const CoreNote &Note) { 5304 // Length of "0x<address>" string. 5305 const int FieldWidth = ELFT::Is64Bits ? 18 : 10; 5306 5307 OS << " Page size: " << format_decimal(Note.PageSize, 0) << '\n'; 5308 OS << " " << right_justify("Start", FieldWidth) << " " 5309 << right_justify("End", FieldWidth) << " " 5310 << right_justify("Page Offset", FieldWidth) << '\n'; 5311 for (const CoreFileMapping &Mapping : Note.Mappings) { 5312 OS << " " << format_hex(Mapping.Start, FieldWidth) << " " 5313 << format_hex(Mapping.End, FieldWidth) << " " 5314 << format_hex(Mapping.Offset, FieldWidth) << "\n " 5315 << Mapping.Filename << '\n'; 5316 } 5317 } 5318 5319 static const NoteType GenericNoteTypes[] = { 5320 {ELF::NT_VERSION, "NT_VERSION (version)"}, 5321 {ELF::NT_ARCH, "NT_ARCH (architecture)"}, 5322 {ELF::NT_GNU_BUILD_ATTRIBUTE_OPEN, "OPEN"}, 5323 {ELF::NT_GNU_BUILD_ATTRIBUTE_FUNC, "func"}, 5324 }; 5325 5326 static const NoteType GNUNoteTypes[] = { 5327 {ELF::NT_GNU_ABI_TAG, "NT_GNU_ABI_TAG (ABI version tag)"}, 5328 {ELF::NT_GNU_HWCAP, "NT_GNU_HWCAP (DSO-supplied software HWCAP info)"}, 5329 {ELF::NT_GNU_BUILD_ID, "NT_GNU_BUILD_ID (unique build ID bitstring)"}, 5330 {ELF::NT_GNU_GOLD_VERSION, "NT_GNU_GOLD_VERSION (gold version)"}, 5331 {ELF::NT_GNU_PROPERTY_TYPE_0, "NT_GNU_PROPERTY_TYPE_0 (property note)"}, 5332 }; 5333 5334 static const NoteType FreeBSDNoteTypes[] = { 5335 {ELF::NT_FREEBSD_THRMISC, "NT_THRMISC (thrmisc structure)"}, 5336 {ELF::NT_FREEBSD_PROCSTAT_PROC, "NT_PROCSTAT_PROC (proc data)"}, 5337 {ELF::NT_FREEBSD_PROCSTAT_FILES, "NT_PROCSTAT_FILES (files data)"}, 5338 {ELF::NT_FREEBSD_PROCSTAT_VMMAP, "NT_PROCSTAT_VMMAP (vmmap data)"}, 5339 {ELF::NT_FREEBSD_PROCSTAT_GROUPS, "NT_PROCSTAT_GROUPS (groups data)"}, 5340 {ELF::NT_FREEBSD_PROCSTAT_UMASK, "NT_PROCSTAT_UMASK (umask data)"}, 5341 {ELF::NT_FREEBSD_PROCSTAT_RLIMIT, "NT_PROCSTAT_RLIMIT (rlimit data)"}, 5342 {ELF::NT_FREEBSD_PROCSTAT_OSREL, "NT_PROCSTAT_OSREL (osreldate data)"}, 5343 {ELF::NT_FREEBSD_PROCSTAT_PSSTRINGS, 5344 "NT_PROCSTAT_PSSTRINGS (ps_strings data)"}, 5345 {ELF::NT_FREEBSD_PROCSTAT_AUXV, "NT_PROCSTAT_AUXV (auxv data)"}, 5346 }; 5347 5348 static const NoteType AMDNoteTypes[] = { 5349 {ELF::NT_AMD_AMDGPU_HSA_METADATA, 5350 "NT_AMD_AMDGPU_HSA_METADATA (HSA Metadata)"}, 5351 {ELF::NT_AMD_AMDGPU_ISA, "NT_AMD_AMDGPU_ISA (ISA Version)"}, 5352 {ELF::NT_AMD_AMDGPU_PAL_METADATA, 5353 "NT_AMD_AMDGPU_PAL_METADATA (PAL Metadata)"}, 5354 }; 5355 5356 static const NoteType AMDGPUNoteTypes[] = { 5357 {ELF::NT_AMDGPU_METADATA, "NT_AMDGPU_METADATA (AMDGPU Metadata)"}, 5358 }; 5359 5360 static const NoteType CoreNoteTypes[] = { 5361 {ELF::NT_PRSTATUS, "NT_PRSTATUS (prstatus structure)"}, 5362 {ELF::NT_FPREGSET, "NT_FPREGSET (floating point registers)"}, 5363 {ELF::NT_PRPSINFO, "NT_PRPSINFO (prpsinfo structure)"}, 5364 {ELF::NT_TASKSTRUCT, "NT_TASKSTRUCT (task structure)"}, 5365 {ELF::NT_AUXV, "NT_AUXV (auxiliary vector)"}, 5366 {ELF::NT_PSTATUS, "NT_PSTATUS (pstatus structure)"}, 5367 {ELF::NT_FPREGS, "NT_FPREGS (floating point registers)"}, 5368 {ELF::NT_PSINFO, "NT_PSINFO (psinfo structure)"}, 5369 {ELF::NT_LWPSTATUS, "NT_LWPSTATUS (lwpstatus_t structure)"}, 5370 {ELF::NT_LWPSINFO, "NT_LWPSINFO (lwpsinfo_t structure)"}, 5371 {ELF::NT_WIN32PSTATUS, "NT_WIN32PSTATUS (win32_pstatus structure)"}, 5372 5373 {ELF::NT_PPC_VMX, "NT_PPC_VMX (ppc Altivec registers)"}, 5374 {ELF::NT_PPC_VSX, "NT_PPC_VSX (ppc VSX registers)"}, 5375 {ELF::NT_PPC_TAR, "NT_PPC_TAR (ppc TAR register)"}, 5376 {ELF::NT_PPC_PPR, "NT_PPC_PPR (ppc PPR register)"}, 5377 {ELF::NT_PPC_DSCR, "NT_PPC_DSCR (ppc DSCR register)"}, 5378 {ELF::NT_PPC_EBB, "NT_PPC_EBB (ppc EBB registers)"}, 5379 {ELF::NT_PPC_PMU, "NT_PPC_PMU (ppc PMU registers)"}, 5380 {ELF::NT_PPC_TM_CGPR, "NT_PPC_TM_CGPR (ppc checkpointed GPR registers)"}, 5381 {ELF::NT_PPC_TM_CFPR, 5382 "NT_PPC_TM_CFPR (ppc checkpointed floating point registers)"}, 5383 {ELF::NT_PPC_TM_CVMX, 5384 "NT_PPC_TM_CVMX (ppc checkpointed Altivec registers)"}, 5385 {ELF::NT_PPC_TM_CVSX, "NT_PPC_TM_CVSX (ppc checkpointed VSX registers)"}, 5386 {ELF::NT_PPC_TM_SPR, "NT_PPC_TM_SPR (ppc TM special purpose registers)"}, 5387 {ELF::NT_PPC_TM_CTAR, "NT_PPC_TM_CTAR (ppc checkpointed TAR register)"}, 5388 {ELF::NT_PPC_TM_CPPR, "NT_PPC_TM_CPPR (ppc checkpointed PPR register)"}, 5389 {ELF::NT_PPC_TM_CDSCR, "NT_PPC_TM_CDSCR (ppc checkpointed DSCR register)"}, 5390 5391 {ELF::NT_386_TLS, "NT_386_TLS (x86 TLS information)"}, 5392 {ELF::NT_386_IOPERM, "NT_386_IOPERM (x86 I/O permissions)"}, 5393 {ELF::NT_X86_XSTATE, "NT_X86_XSTATE (x86 XSAVE extended state)"}, 5394 5395 {ELF::NT_S390_HIGH_GPRS, "NT_S390_HIGH_GPRS (s390 upper register halves)"}, 5396 {ELF::NT_S390_TIMER, "NT_S390_TIMER (s390 timer register)"}, 5397 {ELF::NT_S390_TODCMP, "NT_S390_TODCMP (s390 TOD comparator register)"}, 5398 {ELF::NT_S390_TODPREG, "NT_S390_TODPREG (s390 TOD programmable register)"}, 5399 {ELF::NT_S390_CTRS, "NT_S390_CTRS (s390 control registers)"}, 5400 {ELF::NT_S390_PREFIX, "NT_S390_PREFIX (s390 prefix register)"}, 5401 {ELF::NT_S390_LAST_BREAK, 5402 "NT_S390_LAST_BREAK (s390 last breaking event address)"}, 5403 {ELF::NT_S390_SYSTEM_CALL, 5404 "NT_S390_SYSTEM_CALL (s390 system call restart data)"}, 5405 {ELF::NT_S390_TDB, "NT_S390_TDB (s390 transaction diagnostic block)"}, 5406 {ELF::NT_S390_VXRS_LOW, 5407 "NT_S390_VXRS_LOW (s390 vector registers 0-15 upper half)"}, 5408 {ELF::NT_S390_VXRS_HIGH, "NT_S390_VXRS_HIGH (s390 vector registers 16-31)"}, 5409 {ELF::NT_S390_GS_CB, "NT_S390_GS_CB (s390 guarded-storage registers)"}, 5410 {ELF::NT_S390_GS_BC, 5411 "NT_S390_GS_BC (s390 guarded-storage broadcast control)"}, 5412 5413 {ELF::NT_ARM_VFP, "NT_ARM_VFP (arm VFP registers)"}, 5414 {ELF::NT_ARM_TLS, "NT_ARM_TLS (AArch TLS registers)"}, 5415 {ELF::NT_ARM_HW_BREAK, 5416 "NT_ARM_HW_BREAK (AArch hardware breakpoint registers)"}, 5417 {ELF::NT_ARM_HW_WATCH, 5418 "NT_ARM_HW_WATCH (AArch hardware watchpoint registers)"}, 5419 5420 {ELF::NT_FILE, "NT_FILE (mapped files)"}, 5421 {ELF::NT_PRXFPREG, "NT_PRXFPREG (user_xfpregs structure)"}, 5422 {ELF::NT_SIGINFO, "NT_SIGINFO (siginfo_t data)"}, 5423 }; 5424 5425 template <class ELFT> 5426 const StringRef getNoteTypeName(const typename ELFT::Note &Note, 5427 unsigned ELFType) { 5428 uint32_t Type = Note.getType(); 5429 auto FindNote = [&](ArrayRef<NoteType> V) -> StringRef { 5430 for (const NoteType &N : V) 5431 if (N.ID == Type) 5432 return N.Name; 5433 return ""; 5434 }; 5435 5436 StringRef Name = Note.getName(); 5437 if (Name == "GNU") 5438 return FindNote(GNUNoteTypes); 5439 if (Name == "FreeBSD") 5440 return FindNote(FreeBSDNoteTypes); 5441 if (Name == "AMD") 5442 return FindNote(AMDNoteTypes); 5443 if (Name == "AMDGPU") 5444 return FindNote(AMDGPUNoteTypes); 5445 5446 if (ELFType == ELF::ET_CORE) 5447 return FindNote(CoreNoteTypes); 5448 return FindNote(GenericNoteTypes); 5449 } 5450 5451 template <class ELFT> void GNUStyle<ELFT>::printNotes() { 5452 auto PrintHeader = [&](Optional<StringRef> SecName, 5453 const typename ELFT::Off Offset, 5454 const typename ELFT::Addr Size) { 5455 OS << "Displaying notes found "; 5456 5457 if (SecName) 5458 OS << "in: " << *SecName << "\n"; 5459 else 5460 OS << "at file offset " << format_hex(Offset, 10) << " with length " 5461 << format_hex(Size, 10) << ":\n"; 5462 5463 OS << " Owner Data size \tDescription\n"; 5464 }; 5465 5466 auto ProcessNote = [&](const Elf_Note &Note) { 5467 StringRef Name = Note.getName(); 5468 ArrayRef<uint8_t> Descriptor = Note.getDesc(); 5469 Elf_Word Type = Note.getType(); 5470 5471 // Print the note owner/type. 5472 OS << " " << left_justify(Name, 20) << ' ' 5473 << format_hex(Descriptor.size(), 10) << '\t'; 5474 5475 StringRef NoteType = 5476 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type); 5477 if (!NoteType.empty()) 5478 OS << NoteType << '\n'; 5479 else 5480 OS << "Unknown note type: (" << format_hex(Type, 10) << ")\n"; 5481 5482 // Print the description, or fallback to printing raw bytes for unknown 5483 // owners. 5484 if (Name == "GNU") { 5485 printGNUNote<ELFT>(OS, Type, Descriptor); 5486 } else if (Name == "AMD") { 5487 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor); 5488 if (!N.Type.empty()) 5489 OS << " " << N.Type << ":\n " << N.Value << '\n'; 5490 } else if (Name == "AMDGPU") { 5491 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor); 5492 if (!N.Type.empty()) 5493 OS << " " << N.Type << ":\n " << N.Value << '\n'; 5494 } else if (Name == "CORE") { 5495 if (Type == ELF::NT_FILE) { 5496 DataExtractor DescExtractor(Descriptor, 5497 ELFT::TargetEndianness == support::little, 5498 sizeof(Elf_Addr)); 5499 Expected<CoreNote> Note = readCoreNote(DescExtractor); 5500 if (Note) 5501 printCoreNote<ELFT>(OS, *Note); 5502 else 5503 reportWarning(Note.takeError(), this->FileName); 5504 } 5505 } else if (!Descriptor.empty()) { 5506 OS << " description data:"; 5507 for (uint8_t B : Descriptor) 5508 OS << " " << format("%02x", B); 5509 OS << '\n'; 5510 } 5511 }; 5512 5513 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections()); 5514 if (this->Obj.getHeader().e_type != ELF::ET_CORE && !Sections.empty()) { 5515 for (const Elf_Shdr &S : Sections) { 5516 if (S.sh_type != SHT_NOTE) 5517 continue; 5518 PrintHeader(expectedToOptional(this->Obj.getSectionName(S)), S.sh_offset, 5519 S.sh_size); 5520 Error Err = Error::success(); 5521 for (const Elf_Note Note : this->Obj.notes(S, Err)) 5522 ProcessNote(Note); 5523 if (Err) 5524 reportError(std::move(Err), this->FileName); 5525 } 5526 } else { 5527 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers(); 5528 if (!PhdrsOrErr) { 5529 this->reportUniqueWarning(createError( 5530 "unable to read program headers to locate the PT_NOTE segment: " + 5531 toString(PhdrsOrErr.takeError()))); 5532 return; 5533 } 5534 5535 for (const Elf_Phdr &P : *PhdrsOrErr) { 5536 if (P.p_type != PT_NOTE) 5537 continue; 5538 PrintHeader(/*SecName=*/None, P.p_offset, P.p_filesz); 5539 Error Err = Error::success(); 5540 for (const Elf_Note Note : this->Obj.notes(P, Err)) 5541 ProcessNote(Note); 5542 if (Err) 5543 reportError(std::move(Err), this->FileName); 5544 } 5545 } 5546 } 5547 5548 template <class ELFT> void GNUStyle<ELFT>::printELFLinkerOptions() { 5549 OS << "printELFLinkerOptions not implemented!\n"; 5550 } 5551 5552 template <class ELFT> 5553 void DumpStyle<ELFT>::printDependentLibsHelper( 5554 function_ref<void(const Elf_Shdr &)> OnSectionStart, 5555 function_ref<void(StringRef, uint64_t)> OnLibEntry) { 5556 auto Warn = [this](unsigned SecNdx, StringRef Msg) { 5557 this->reportUniqueWarning( 5558 createError("SHT_LLVM_DEPENDENT_LIBRARIES section at index " + 5559 Twine(SecNdx) + " is broken: " + Msg)); 5560 }; 5561 5562 unsigned I = -1; 5563 for (const Elf_Shdr &Shdr : cantFail(Obj.sections())) { 5564 ++I; 5565 if (Shdr.sh_type != ELF::SHT_LLVM_DEPENDENT_LIBRARIES) 5566 continue; 5567 5568 OnSectionStart(Shdr); 5569 5570 Expected<ArrayRef<uint8_t>> ContentsOrErr = Obj.getSectionContents(Shdr); 5571 if (!ContentsOrErr) { 5572 Warn(I, toString(ContentsOrErr.takeError())); 5573 continue; 5574 } 5575 5576 ArrayRef<uint8_t> Contents = *ContentsOrErr; 5577 if (!Contents.empty() && Contents.back() != 0) { 5578 Warn(I, "the content is not null-terminated"); 5579 continue; 5580 } 5581 5582 for (const uint8_t *I = Contents.begin(), *E = Contents.end(); I < E;) { 5583 StringRef Lib((const char *)I); 5584 OnLibEntry(Lib, I - Contents.begin()); 5585 I += Lib.size() + 1; 5586 } 5587 } 5588 } 5589 5590 template <class ELFT> 5591 void DumpStyle<ELFT>::printRelocationsHelper(const Elf_Shdr &Sec) { 5592 auto Warn = [&](Error &&E, 5593 const Twine &Prefix = "unable to read relocations from") { 5594 this->reportUniqueWarning(createError(Prefix + " " + describe(Obj, Sec) + 5595 ": " + toString(std::move(E)))); 5596 }; 5597 5598 // SHT_RELR/SHT_ANDROID_RELR sections do not have an associated symbol table. 5599 // For them we should not treat the value of the sh_link field as an index of 5600 // a symbol table. 5601 const Elf_Shdr *SymTab; 5602 if (Sec.sh_type != ELF::SHT_RELR && Sec.sh_type != ELF::SHT_ANDROID_RELR) { 5603 Expected<const Elf_Shdr *> SymTabOrErr = Obj.getSection(Sec.sh_link); 5604 if (!SymTabOrErr) { 5605 Warn(SymTabOrErr.takeError(), "unable to locate a symbol table for"); 5606 return; 5607 } 5608 SymTab = *SymTabOrErr; 5609 } 5610 5611 unsigned RelNdx = 0; 5612 const bool IsMips64EL = this->Obj.isMips64EL(); 5613 switch (Sec.sh_type) { 5614 case ELF::SHT_REL: 5615 if (Expected<Elf_Rel_Range> RangeOrErr = Obj.rels(Sec)) { 5616 for (const Elf_Rel &R : *RangeOrErr) 5617 printReloc(Relocation<ELFT>(R, IsMips64EL), ++RelNdx, Sec, SymTab); 5618 } else { 5619 Warn(RangeOrErr.takeError()); 5620 } 5621 break; 5622 case ELF::SHT_RELA: 5623 if (Expected<Elf_Rela_Range> RangeOrErr = Obj.relas(Sec)) { 5624 for (const Elf_Rela &R : *RangeOrErr) 5625 printReloc(Relocation<ELFT>(R, IsMips64EL), ++RelNdx, Sec, SymTab); 5626 } else { 5627 Warn(RangeOrErr.takeError()); 5628 } 5629 break; 5630 case ELF::SHT_RELR: 5631 case ELF::SHT_ANDROID_RELR: { 5632 Expected<Elf_Relr_Range> RangeOrErr = Obj.relrs(Sec); 5633 if (!RangeOrErr) { 5634 Warn(RangeOrErr.takeError()); 5635 break; 5636 } 5637 if (opts::RawRelr) { 5638 for (const Elf_Relr &R : *RangeOrErr) 5639 printRelrReloc(R); 5640 break; 5641 } 5642 5643 for (const Elf_Rel &R : Obj.decode_relrs(*RangeOrErr)) 5644 printReloc(Relocation<ELFT>(R, IsMips64EL), ++RelNdx, Sec, 5645 /*SymTab=*/nullptr); 5646 break; 5647 } 5648 case ELF::SHT_ANDROID_REL: 5649 case ELF::SHT_ANDROID_RELA: 5650 if (Expected<std::vector<Elf_Rela>> RelasOrErr = Obj.android_relas(Sec)) { 5651 for (const Elf_Rela &R : *RelasOrErr) 5652 printReloc(Relocation<ELFT>(R, IsMips64EL), ++RelNdx, Sec, SymTab); 5653 } else { 5654 Warn(RelasOrErr.takeError()); 5655 } 5656 break; 5657 } 5658 } 5659 5660 template <class ELFT> 5661 StringRef DumpStyle<ELFT>::getPrintableSectionName(const Elf_Shdr &Sec) const { 5662 StringRef Name = "<?>"; 5663 if (Expected<StringRef> SecNameOrErr = 5664 Obj.getSectionName(Sec, this->dumper().WarningHandler)) 5665 Name = *SecNameOrErr; 5666 else 5667 this->reportUniqueWarning(createError("unable to get the name of " + 5668 describe(Obj, Sec) + ": " + 5669 toString(SecNameOrErr.takeError()))); 5670 return Name; 5671 } 5672 5673 template <class ELFT> void GNUStyle<ELFT>::printDependentLibs() { 5674 bool SectionStarted = false; 5675 struct NameOffset { 5676 StringRef Name; 5677 uint64_t Offset; 5678 }; 5679 std::vector<NameOffset> SecEntries; 5680 NameOffset Current; 5681 auto PrintSection = [&]() { 5682 OS << "Dependent libraries section " << Current.Name << " at offset " 5683 << format_hex(Current.Offset, 1) << " contains " << SecEntries.size() 5684 << " entries:\n"; 5685 for (NameOffset Entry : SecEntries) 5686 OS << " [" << format("%6" PRIx64, Entry.Offset) << "] " << Entry.Name 5687 << "\n"; 5688 OS << "\n"; 5689 SecEntries.clear(); 5690 }; 5691 5692 auto OnSectionStart = [&](const Elf_Shdr &Shdr) { 5693 if (SectionStarted) 5694 PrintSection(); 5695 SectionStarted = true; 5696 Current.Offset = Shdr.sh_offset; 5697 Current.Name = this->getPrintableSectionName(Shdr); 5698 }; 5699 auto OnLibEntry = [&](StringRef Lib, uint64_t Offset) { 5700 SecEntries.push_back(NameOffset{Lib, Offset}); 5701 }; 5702 5703 this->printDependentLibsHelper(OnSectionStart, OnLibEntry); 5704 if (SectionStarted) 5705 PrintSection(); 5706 } 5707 5708 // Used for printing symbol names in places where possible errors can be 5709 // ignored. 5710 static std::string getSymbolName(const ELFSymbolRef &Sym) { 5711 Expected<StringRef> NameOrErr = Sym.getName(); 5712 if (NameOrErr) 5713 return maybeDemangle(*NameOrErr); 5714 consumeError(NameOrErr.takeError()); 5715 return "<?>"; 5716 } 5717 5718 template <class ELFT> 5719 void DumpStyle<ELFT>::printFunctionStackSize( 5720 uint64_t SymValue, Optional<const Elf_Shdr *> FunctionSec, 5721 const Elf_Shdr &StackSizeSec, DataExtractor Data, uint64_t *Offset) { 5722 // This function ignores potentially erroneous input, unless it is directly 5723 // related to stack size reporting. 5724 SymbolRef FuncSym; 5725 for (const ELFSymbolRef &Symbol : ElfObj.symbols()) { 5726 Expected<uint64_t> SymAddrOrErr = Symbol.getAddress(); 5727 if (!SymAddrOrErr) { 5728 consumeError(SymAddrOrErr.takeError()); 5729 continue; 5730 } 5731 if (Expected<uint32_t> SymFlags = Symbol.getFlags()) { 5732 if (*SymFlags & SymbolRef::SF_Undefined) 5733 continue; 5734 } else 5735 consumeError(SymFlags.takeError()); 5736 if (Symbol.getELFType() == ELF::STT_FUNC && *SymAddrOrErr == SymValue) { 5737 // Check if the symbol is in the right section. FunctionSec == None means 5738 // "any section". 5739 if (!FunctionSec || 5740 ElfObj.toSectionRef(*FunctionSec).containsSymbol(Symbol)) { 5741 FuncSym = Symbol; 5742 break; 5743 } 5744 } 5745 } 5746 5747 std::string FuncName = "?"; 5748 // A valid SymbolRef has a non-null object file pointer. 5749 if (FuncSym.BasicSymbolRef::getObject()) 5750 FuncName = getSymbolName(FuncSym); 5751 else 5752 reportWarning( 5753 createError("could not identify function symbol for stack size entry"), 5754 FileName); 5755 5756 // Extract the size. The expectation is that Offset is pointing to the right 5757 // place, i.e. past the function address. 5758 uint64_t PrevOffset = *Offset; 5759 uint64_t StackSize = Data.getULEB128(Offset); 5760 // getULEB128() does not advance Offset if it is not able to extract a valid 5761 // integer. 5762 if (*Offset == PrevOffset) { 5763 reportWarning(createStringError(object_error::parse_failed, 5764 "could not extract a valid stack size in " + 5765 describe(Obj, StackSizeSec)), 5766 FileName); 5767 return; 5768 } 5769 5770 printStackSizeEntry(StackSize, FuncName); 5771 } 5772 5773 template <class ELFT> 5774 void GNUStyle<ELFT>::printStackSizeEntry(uint64_t Size, StringRef FuncName) { 5775 OS.PadToColumn(2); 5776 OS << format_decimal(Size, 11); 5777 OS.PadToColumn(18); 5778 OS << FuncName << "\n"; 5779 } 5780 5781 template <class ELFT> 5782 void DumpStyle<ELFT>::printStackSize(RelocationRef Reloc, 5783 const Elf_Shdr *FunctionSec, 5784 const Elf_Shdr &StackSizeSec, 5785 const RelocationResolver &Resolver, 5786 DataExtractor Data) { 5787 // This function ignores potentially erroneous input, unless it is directly 5788 // related to stack size reporting. 5789 object::symbol_iterator RelocSym = Reloc.getSymbol(); 5790 uint64_t RelocSymValue = 0; 5791 if (RelocSym != ElfObj.symbol_end()) { 5792 // Ensure that the relocation symbol is in the function section, i.e. the 5793 // section where the functions whose stack sizes we are reporting are 5794 // located. 5795 auto SectionOrErr = RelocSym->getSection(); 5796 if (!SectionOrErr) { 5797 reportWarning( 5798 createError("cannot identify the section for relocation symbol '" + 5799 getSymbolName(*RelocSym) + "'"), 5800 FileName); 5801 consumeError(SectionOrErr.takeError()); 5802 } else if (*SectionOrErr != ElfObj.toSectionRef(FunctionSec)) { 5803 reportWarning(createError("relocation symbol '" + 5804 getSymbolName(*RelocSym) + 5805 "' is not in the expected section"), 5806 FileName); 5807 // Pretend that the symbol is in the correct section and report its 5808 // stack size anyway. 5809 FunctionSec = ElfObj.getSection((*SectionOrErr)->getRawDataRefImpl()); 5810 } 5811 5812 Expected<uint64_t> RelocSymValueOrErr = RelocSym->getValue(); 5813 if (RelocSymValueOrErr) 5814 RelocSymValue = *RelocSymValueOrErr; 5815 else 5816 consumeError(RelocSymValueOrErr.takeError()); 5817 } 5818 5819 uint64_t Offset = Reloc.getOffset(); 5820 if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) { 5821 reportUniqueWarning(createStringError( 5822 object_error::parse_failed, 5823 "found invalid relocation offset (0x" + Twine::utohexstr(Offset) + 5824 ") into " + describe(Obj, StackSizeSec) + 5825 " while trying to extract a stack size entry")); 5826 return; 5827 } 5828 5829 uint64_t Addend = Data.getAddress(&Offset); 5830 uint64_t SymValue = Resolver(Reloc, RelocSymValue, Addend); 5831 this->printFunctionStackSize(SymValue, FunctionSec, StackSizeSec, Data, 5832 &Offset); 5833 } 5834 5835 template <class ELFT> 5836 void DumpStyle<ELFT>::printNonRelocatableStackSizes( 5837 std::function<void()> PrintHeader) { 5838 // This function ignores potentially erroneous input, unless it is directly 5839 // related to stack size reporting. 5840 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) { 5841 if (this->getPrintableSectionName(Sec) != ".stack_sizes") 5842 continue; 5843 PrintHeader(); 5844 ArrayRef<uint8_t> Contents = 5845 unwrapOrError(this->FileName, Obj.getSectionContents(Sec)); 5846 DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr)); 5847 uint64_t Offset = 0; 5848 while (Offset < Contents.size()) { 5849 // The function address is followed by a ULEB representing the stack 5850 // size. Check for an extra byte before we try to process the entry. 5851 if (!Data.isValidOffsetForDataOfSize(Offset, sizeof(Elf_Addr) + 1)) { 5852 reportUniqueWarning(createStringError( 5853 object_error::parse_failed, 5854 describe(Obj, Sec) + 5855 " ended while trying to extract a stack size entry")); 5856 break; 5857 } 5858 uint64_t SymValue = Data.getAddress(&Offset); 5859 printFunctionStackSize(SymValue, /*FunctionSec=*/None, Sec, Data, 5860 &Offset); 5861 } 5862 } 5863 } 5864 5865 template <class ELFT> 5866 void DumpStyle<ELFT>::printRelocatableStackSizes( 5867 std::function<void()> PrintHeader) { 5868 // Build a map between stack size sections and their corresponding relocation 5869 // sections. 5870 llvm::MapVector<const Elf_Shdr *, const Elf_Shdr *> StackSizeRelocMap; 5871 for (const Elf_Shdr &Sec : cantFail(Obj.sections())) { 5872 StringRef SectionName; 5873 if (Expected<StringRef> NameOrErr = Obj.getSectionName(Sec)) 5874 SectionName = *NameOrErr; 5875 else 5876 consumeError(NameOrErr.takeError()); 5877 5878 // A stack size section that we haven't encountered yet is mapped to the 5879 // null section until we find its corresponding relocation section. 5880 if (SectionName == ".stack_sizes") 5881 if (StackSizeRelocMap 5882 .insert(std::make_pair(&Sec, (const Elf_Shdr *)nullptr)) 5883 .second) 5884 continue; 5885 5886 // Check relocation sections if they are relocating contents of a 5887 // stack sizes section. 5888 if (Sec.sh_type != ELF::SHT_RELA && Sec.sh_type != ELF::SHT_REL) 5889 continue; 5890 5891 Expected<const Elf_Shdr *> RelSecOrErr = Obj.getSection(Sec.sh_info); 5892 if (!RelSecOrErr) { 5893 reportUniqueWarning(createStringError( 5894 object_error::parse_failed, 5895 describe(Obj, Sec) + ": failed to get a relocated section: " + 5896 toString(RelSecOrErr.takeError()))); 5897 continue; 5898 } 5899 5900 const Elf_Shdr *ContentsSec = *RelSecOrErr; 5901 if (this->getPrintableSectionName(**RelSecOrErr) != ".stack_sizes") 5902 continue; 5903 5904 // Insert a mapping from the stack sizes section to its relocation section. 5905 StackSizeRelocMap[ContentsSec] = &Sec; 5906 } 5907 5908 for (const auto &StackSizeMapEntry : StackSizeRelocMap) { 5909 PrintHeader(); 5910 const Elf_Shdr *StackSizesELFSec = StackSizeMapEntry.first; 5911 const Elf_Shdr *RelocSec = StackSizeMapEntry.second; 5912 5913 // Warn about stack size sections without a relocation section. 5914 if (!RelocSec) { 5915 reportWarning(createError(".stack_sizes (" + 5916 describe(Obj, *StackSizesELFSec) + 5917 ") does not have a corresponding " 5918 "relocation section"), 5919 FileName); 5920 continue; 5921 } 5922 5923 // A .stack_sizes section header's sh_link field is supposed to point 5924 // to the section that contains the functions whose stack sizes are 5925 // described in it. 5926 const Elf_Shdr *FunctionSec = unwrapOrError( 5927 this->FileName, Obj.getSection(StackSizesELFSec->sh_link)); 5928 bool (*IsSupportedFn)(uint64_t); 5929 RelocationResolver Resolver; 5930 std::tie(IsSupportedFn, Resolver) = getRelocationResolver(ElfObj); 5931 ArrayRef<uint8_t> Contents = 5932 unwrapOrError(this->FileName, Obj.getSectionContents(*StackSizesELFSec)); 5933 DataExtractor Data(Contents, Obj.isLE(), sizeof(Elf_Addr)); 5934 5935 size_t I = 0; 5936 for (const RelocationRef &Reloc : 5937 ElfObj.toSectionRef(RelocSec).relocations()) { 5938 ++I; 5939 if (!IsSupportedFn || !IsSupportedFn(Reloc.getType())) { 5940 reportUniqueWarning(createStringError( 5941 object_error::parse_failed, 5942 describe(Obj, *RelocSec) + 5943 " contains an unsupported relocation with index " + Twine(I) + 5944 ": " + Obj.getRelocationTypeName(Reloc.getType()))); 5945 continue; 5946 } 5947 this->printStackSize(Reloc, FunctionSec, *StackSizesELFSec, Resolver, 5948 Data); 5949 } 5950 } 5951 } 5952 5953 template <class ELFT> 5954 void GNUStyle<ELFT>::printStackSizes() { 5955 bool HeaderHasBeenPrinted = false; 5956 auto PrintHeader = [&]() { 5957 if (HeaderHasBeenPrinted) 5958 return; 5959 OS << "\nStack Sizes:\n"; 5960 OS.PadToColumn(9); 5961 OS << "Size"; 5962 OS.PadToColumn(18); 5963 OS << "Function\n"; 5964 HeaderHasBeenPrinted = true; 5965 }; 5966 5967 // For non-relocatable objects, look directly for sections whose name starts 5968 // with .stack_sizes and process the contents. 5969 if (this->Obj.getHeader().e_type == ELF::ET_REL) 5970 this->printRelocatableStackSizes(PrintHeader); 5971 else 5972 this->printNonRelocatableStackSizes(PrintHeader); 5973 } 5974 5975 template <class ELFT> 5976 void GNUStyle<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) { 5977 size_t Bias = ELFT::Is64Bits ? 8 : 0; 5978 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) { 5979 OS.PadToColumn(2); 5980 OS << format_hex_no_prefix(Parser.getGotAddress(E), 8 + Bias); 5981 OS.PadToColumn(11 + Bias); 5982 OS << format_decimal(Parser.getGotOffset(E), 6) << "(gp)"; 5983 OS.PadToColumn(22 + Bias); 5984 OS << format_hex_no_prefix(*E, 8 + Bias); 5985 OS.PadToColumn(31 + 2 * Bias); 5986 OS << Purpose << "\n"; 5987 }; 5988 5989 OS << (Parser.IsStatic ? "Static GOT:\n" : "Primary GOT:\n"); 5990 OS << " Canonical gp value: " 5991 << format_hex_no_prefix(Parser.getGp(), 8 + Bias) << "\n\n"; 5992 5993 OS << " Reserved entries:\n"; 5994 if (ELFT::Is64Bits) 5995 OS << " Address Access Initial Purpose\n"; 5996 else 5997 OS << " Address Access Initial Purpose\n"; 5998 PrintEntry(Parser.getGotLazyResolver(), "Lazy resolver"); 5999 if (Parser.getGotModulePointer()) 6000 PrintEntry(Parser.getGotModulePointer(), "Module pointer (GNU extension)"); 6001 6002 if (!Parser.getLocalEntries().empty()) { 6003 OS << "\n"; 6004 OS << " Local entries:\n"; 6005 if (ELFT::Is64Bits) 6006 OS << " Address Access Initial\n"; 6007 else 6008 OS << " Address Access Initial\n"; 6009 for (auto &E : Parser.getLocalEntries()) 6010 PrintEntry(&E, ""); 6011 } 6012 6013 if (Parser.IsStatic) 6014 return; 6015 6016 if (!Parser.getGlobalEntries().empty()) { 6017 OS << "\n"; 6018 OS << " Global entries:\n"; 6019 if (ELFT::Is64Bits) 6020 OS << " Address Access Initial Sym.Val." 6021 << " Type Ndx Name\n"; 6022 else 6023 OS << " Address Access Initial Sym.Val. Type Ndx Name\n"; 6024 for (auto &E : Parser.getGlobalEntries()) { 6025 const Elf_Sym &Sym = *Parser.getGotSym(&E); 6026 const Elf_Sym &FirstSym = this->dumper().dynamic_symbols()[0]; 6027 std::string SymName = this->dumper().getFullSymbolName( 6028 Sym, &Sym - &FirstSym, this->dumper().getDynamicStringTable(), false); 6029 6030 OS.PadToColumn(2); 6031 OS << to_string(format_hex_no_prefix(Parser.getGotAddress(&E), 8 + Bias)); 6032 OS.PadToColumn(11 + Bias); 6033 OS << to_string(format_decimal(Parser.getGotOffset(&E), 6)) + "(gp)"; 6034 OS.PadToColumn(22 + Bias); 6035 OS << to_string(format_hex_no_prefix(E, 8 + Bias)); 6036 OS.PadToColumn(31 + 2 * Bias); 6037 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias)); 6038 OS.PadToColumn(40 + 3 * Bias); 6039 OS << printEnum(Sym.getType(), makeArrayRef(ElfSymbolTypes)); 6040 OS.PadToColumn(48 + 3 * Bias); 6041 OS << getSymbolSectionNdx( 6042 Sym, &Sym - this->dumper().dynamic_symbols().begin()); 6043 OS.PadToColumn(52 + 3 * Bias); 6044 OS << SymName << "\n"; 6045 } 6046 } 6047 6048 if (!Parser.getOtherEntries().empty()) 6049 OS << "\n Number of TLS and multi-GOT entries " 6050 << Parser.getOtherEntries().size() << "\n"; 6051 } 6052 6053 template <class ELFT> 6054 void GNUStyle<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) { 6055 size_t Bias = ELFT::Is64Bits ? 8 : 0; 6056 auto PrintEntry = [&](const Elf_Addr *E, StringRef Purpose) { 6057 OS.PadToColumn(2); 6058 OS << format_hex_no_prefix(Parser.getPltAddress(E), 8 + Bias); 6059 OS.PadToColumn(11 + Bias); 6060 OS << format_hex_no_prefix(*E, 8 + Bias); 6061 OS.PadToColumn(20 + 2 * Bias); 6062 OS << Purpose << "\n"; 6063 }; 6064 6065 OS << "PLT GOT:\n\n"; 6066 6067 OS << " Reserved entries:\n"; 6068 OS << " Address Initial Purpose\n"; 6069 PrintEntry(Parser.getPltLazyResolver(), "PLT lazy resolver"); 6070 if (Parser.getPltModulePointer()) 6071 PrintEntry(Parser.getPltModulePointer(), "Module pointer"); 6072 6073 if (!Parser.getPltEntries().empty()) { 6074 OS << "\n"; 6075 OS << " Entries:\n"; 6076 OS << " Address Initial Sym.Val. Type Ndx Name\n"; 6077 for (auto &E : Parser.getPltEntries()) { 6078 const Elf_Sym &Sym = *Parser.getPltSym(&E); 6079 const Elf_Sym &FirstSym = 6080 *cantFail(this->Obj.template getEntry<const Elf_Sym>( 6081 *Parser.getPltSymTable(), 0)); 6082 std::string SymName = this->dumper().getFullSymbolName( 6083 Sym, &Sym - &FirstSym, this->dumper().getDynamicStringTable(), false); 6084 6085 OS.PadToColumn(2); 6086 OS << to_string(format_hex_no_prefix(Parser.getPltAddress(&E), 8 + Bias)); 6087 OS.PadToColumn(11 + Bias); 6088 OS << to_string(format_hex_no_prefix(E, 8 + Bias)); 6089 OS.PadToColumn(20 + 2 * Bias); 6090 OS << to_string(format_hex_no_prefix(Sym.st_value, 8 + Bias)); 6091 OS.PadToColumn(29 + 3 * Bias); 6092 OS << printEnum(Sym.getType(), makeArrayRef(ElfSymbolTypes)); 6093 OS.PadToColumn(37 + 3 * Bias); 6094 OS << getSymbolSectionNdx( 6095 Sym, &Sym - this->dumper().dynamic_symbols().begin()); 6096 OS.PadToColumn(41 + 3 * Bias); 6097 OS << SymName << "\n"; 6098 } 6099 } 6100 } 6101 6102 template <class ELFT> 6103 Expected<const Elf_Mips_ABIFlags<ELFT> *> 6104 getMipsAbiFlagsSection(const ELFDumper<ELFT> &Dumper) { 6105 const typename ELFT::Shdr *Sec = Dumper.findSectionByName(".MIPS.abiflags"); 6106 if (Sec == nullptr) 6107 return nullptr; 6108 6109 constexpr StringRef ErrPrefix = "unable to read the .MIPS.abiflags section: "; 6110 Expected<ArrayRef<uint8_t>> DataOrErr = 6111 Dumper.getElfObject().getELFFile()->getSectionContents(*Sec); 6112 if (!DataOrErr) 6113 return createError(ErrPrefix + toString(DataOrErr.takeError())); 6114 6115 if (DataOrErr->size() != sizeof(Elf_Mips_ABIFlags<ELFT>)) 6116 return createError(ErrPrefix + "it has a wrong size (" + 6117 Twine(DataOrErr->size()) + ")"); 6118 return reinterpret_cast<const Elf_Mips_ABIFlags<ELFT> *>(DataOrErr->data()); 6119 } 6120 6121 template <class ELFT> void GNUStyle<ELFT>::printMipsABIFlags() { 6122 const Elf_Mips_ABIFlags<ELFT> *Flags = nullptr; 6123 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr = 6124 getMipsAbiFlagsSection(this->dumper())) 6125 Flags = *SecOrErr; 6126 else 6127 this->reportUniqueWarning(SecOrErr.takeError()); 6128 if (!Flags) 6129 return; 6130 6131 OS << "MIPS ABI Flags Version: " << Flags->version << "\n\n"; 6132 OS << "ISA: MIPS" << int(Flags->isa_level); 6133 if (Flags->isa_rev > 1) 6134 OS << "r" << int(Flags->isa_rev); 6135 OS << "\n"; 6136 OS << "GPR size: " << getMipsRegisterSize(Flags->gpr_size) << "\n"; 6137 OS << "CPR1 size: " << getMipsRegisterSize(Flags->cpr1_size) << "\n"; 6138 OS << "CPR2 size: " << getMipsRegisterSize(Flags->cpr2_size) << "\n"; 6139 OS << "FP ABI: " << printEnum(Flags->fp_abi, makeArrayRef(ElfMipsFpABIType)) 6140 << "\n"; 6141 OS << "ISA Extension: " 6142 << printEnum(Flags->isa_ext, makeArrayRef(ElfMipsISAExtType)) << "\n"; 6143 if (Flags->ases == 0) 6144 OS << "ASEs: None\n"; 6145 else 6146 // FIXME: Print each flag on a separate line. 6147 OS << "ASEs: " << printFlags(Flags->ases, makeArrayRef(ElfMipsASEFlags)) 6148 << "\n"; 6149 OS << "FLAGS 1: " << format_hex_no_prefix(Flags->flags1, 8, false) << "\n"; 6150 OS << "FLAGS 2: " << format_hex_no_prefix(Flags->flags2, 8, false) << "\n"; 6151 OS << "\n"; 6152 } 6153 6154 template <class ELFT> void LLVMStyle<ELFT>::printFileHeaders() { 6155 const Elf_Ehdr &E = this->Obj.getHeader(); 6156 { 6157 DictScope D(W, "ElfHeader"); 6158 { 6159 DictScope D(W, "Ident"); 6160 W.printBinary("Magic", makeArrayRef(E.e_ident).slice(ELF::EI_MAG0, 4)); 6161 W.printEnum("Class", E.e_ident[ELF::EI_CLASS], makeArrayRef(ElfClass)); 6162 W.printEnum("DataEncoding", E.e_ident[ELF::EI_DATA], 6163 makeArrayRef(ElfDataEncoding)); 6164 W.printNumber("FileVersion", E.e_ident[ELF::EI_VERSION]); 6165 6166 auto OSABI = makeArrayRef(ElfOSABI); 6167 if (E.e_ident[ELF::EI_OSABI] >= ELF::ELFOSABI_FIRST_ARCH && 6168 E.e_ident[ELF::EI_OSABI] <= ELF::ELFOSABI_LAST_ARCH) { 6169 switch (E.e_machine) { 6170 case ELF::EM_AMDGPU: 6171 OSABI = makeArrayRef(AMDGPUElfOSABI); 6172 break; 6173 case ELF::EM_ARM: 6174 OSABI = makeArrayRef(ARMElfOSABI); 6175 break; 6176 case ELF::EM_TI_C6000: 6177 OSABI = makeArrayRef(C6000ElfOSABI); 6178 break; 6179 } 6180 } 6181 W.printEnum("OS/ABI", E.e_ident[ELF::EI_OSABI], OSABI); 6182 W.printNumber("ABIVersion", E.e_ident[ELF::EI_ABIVERSION]); 6183 W.printBinary("Unused", makeArrayRef(E.e_ident).slice(ELF::EI_PAD)); 6184 } 6185 6186 W.printEnum("Type", E.e_type, makeArrayRef(ElfObjectFileType)); 6187 W.printEnum("Machine", E.e_machine, makeArrayRef(ElfMachineType)); 6188 W.printNumber("Version", E.e_version); 6189 W.printHex("Entry", E.e_entry); 6190 W.printHex("ProgramHeaderOffset", E.e_phoff); 6191 W.printHex("SectionHeaderOffset", E.e_shoff); 6192 if (E.e_machine == EM_MIPS) 6193 W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderMipsFlags), 6194 unsigned(ELF::EF_MIPS_ARCH), unsigned(ELF::EF_MIPS_ABI), 6195 unsigned(ELF::EF_MIPS_MACH)); 6196 else if (E.e_machine == EM_AMDGPU) 6197 W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderAMDGPUFlags), 6198 unsigned(ELF::EF_AMDGPU_MACH)); 6199 else if (E.e_machine == EM_RISCV) 6200 W.printFlags("Flags", E.e_flags, makeArrayRef(ElfHeaderRISCVFlags)); 6201 else 6202 W.printFlags("Flags", E.e_flags); 6203 W.printNumber("HeaderSize", E.e_ehsize); 6204 W.printNumber("ProgramHeaderEntrySize", E.e_phentsize); 6205 W.printNumber("ProgramHeaderCount", E.e_phnum); 6206 W.printNumber("SectionHeaderEntrySize", E.e_shentsize); 6207 W.printString("SectionHeaderCount", 6208 getSectionHeadersNumString(this->Obj, this->FileName)); 6209 W.printString("StringTableSectionIndex", 6210 getSectionHeaderTableIndexString(this->Obj, this->FileName)); 6211 } 6212 } 6213 6214 template <class ELFT> void LLVMStyle<ELFT>::printGroupSections() { 6215 DictScope Lists(W, "Groups"); 6216 std::vector<GroupSection> V = getGroups<ELFT>(this->Obj, this->FileName); 6217 DenseMap<uint64_t, const GroupSection *> Map = mapSectionsToGroups(V); 6218 for (const GroupSection &G : V) { 6219 DictScope D(W, "Group"); 6220 W.printNumber("Name", G.Name, G.ShName); 6221 W.printNumber("Index", G.Index); 6222 W.printNumber("Link", G.Link); 6223 W.printNumber("Info", G.Info); 6224 W.printHex("Type", getGroupType(G.Type), G.Type); 6225 W.startLine() << "Signature: " << G.Signature << "\n"; 6226 6227 ListScope L(W, "Section(s) in group"); 6228 for (const GroupMember &GM : G.Members) { 6229 const GroupSection *MainGroup = Map[GM.Index]; 6230 if (MainGroup != &G) 6231 this->reportUniqueWarning( 6232 createError("section with index " + Twine(GM.Index) + 6233 ", included in the group section with index " + 6234 Twine(MainGroup->Index) + 6235 ", was also found in the group section with index " + 6236 Twine(G.Index))); 6237 W.startLine() << GM.Name << " (" << GM.Index << ")\n"; 6238 } 6239 } 6240 6241 if (V.empty()) 6242 W.startLine() << "There are no group sections in the file.\n"; 6243 } 6244 6245 template <class ELFT> void LLVMStyle<ELFT>::printRelocations() { 6246 ListScope D(W, "Relocations"); 6247 6248 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) { 6249 if (!isRelocationSec<ELFT>(Sec)) 6250 continue; 6251 6252 StringRef Name = this->getPrintableSectionName(Sec); 6253 unsigned SecNdx = &Sec - &cantFail(this->Obj.sections()).front(); 6254 W.startLine() << "Section (" << SecNdx << ") " << Name << " {\n"; 6255 W.indent(); 6256 this->printRelocationsHelper(Sec); 6257 W.unindent(); 6258 W.startLine() << "}\n"; 6259 } 6260 } 6261 6262 template <class ELFT> void LLVMStyle<ELFT>::printRelrReloc(const Elf_Relr &R) { 6263 W.startLine() << W.hex(R) << "\n"; 6264 } 6265 6266 template <class ELFT> 6267 void LLVMStyle<ELFT>::printReloc(const Relocation<ELFT> &R, unsigned RelIndex, 6268 const Elf_Shdr &Sec, const Elf_Shdr *SymTab) { 6269 Expected<RelSymbol<ELFT>> Target = 6270 this->dumper().getRelocationTarget(R, SymTab); 6271 if (!Target) { 6272 this->reportUniqueWarning(createError( 6273 "unable to print relocation " + Twine(RelIndex) + " in " + 6274 describe(this->Obj, Sec) + ": " + toString(Target.takeError()))); 6275 return; 6276 } 6277 6278 printRelRelaReloc(R, Target->Name); 6279 } 6280 6281 template <class ELFT> 6282 void LLVMStyle<ELFT>::printRelRelaReloc(const Relocation<ELFT> &R, 6283 StringRef SymbolName) { 6284 SmallString<32> RelocName; 6285 this->Obj.getRelocationTypeName(R.Type, RelocName); 6286 6287 uintX_t Addend = R.Addend.getValueOr(0); 6288 if (opts::ExpandRelocs) { 6289 DictScope Group(W, "Relocation"); 6290 W.printHex("Offset", R.Offset); 6291 W.printNumber("Type", RelocName, R.Type); 6292 W.printNumber("Symbol", !SymbolName.empty() ? SymbolName : "-", R.Symbol); 6293 W.printHex("Addend", Addend); 6294 } else { 6295 raw_ostream &OS = W.startLine(); 6296 OS << W.hex(R.Offset) << " " << RelocName << " " 6297 << (!SymbolName.empty() ? SymbolName : "-") << " " << W.hex(Addend) 6298 << "\n"; 6299 } 6300 } 6301 6302 template <class ELFT> void LLVMStyle<ELFT>::printSectionHeaders() { 6303 ListScope SectionsD(W, "Sections"); 6304 6305 int SectionIndex = -1; 6306 std::vector<EnumEntry<unsigned>> FlagsList = 6307 getSectionFlagsForTarget(this->Obj.getHeader().e_machine); 6308 for (const Elf_Shdr &Sec : cantFail(this->Obj.sections())) { 6309 DictScope SectionD(W, "Section"); 6310 W.printNumber("Index", ++SectionIndex); 6311 W.printNumber("Name", this->getPrintableSectionName(Sec), Sec.sh_name); 6312 W.printHex("Type", 6313 object::getELFSectionTypeName(this->Obj.getHeader().e_machine, 6314 Sec.sh_type), 6315 Sec.sh_type); 6316 W.printFlags("Flags", Sec.sh_flags, makeArrayRef(FlagsList)); 6317 W.printHex("Address", Sec.sh_addr); 6318 W.printHex("Offset", Sec.sh_offset); 6319 W.printNumber("Size", Sec.sh_size); 6320 W.printNumber("Link", Sec.sh_link); 6321 W.printNumber("Info", Sec.sh_info); 6322 W.printNumber("AddressAlignment", Sec.sh_addralign); 6323 W.printNumber("EntrySize", Sec.sh_entsize); 6324 6325 if (opts::SectionRelocations) { 6326 ListScope D(W, "Relocations"); 6327 this->printRelocationsHelper(Sec); 6328 } 6329 6330 if (opts::SectionSymbols) { 6331 ListScope D(W, "Symbols"); 6332 if (const Elf_Shdr *Symtab = this->dumper().getDotSymtabSec()) { 6333 StringRef StrTable = unwrapOrError( 6334 this->FileName, this->Obj.getStringTableForSymtab(*Symtab)); 6335 6336 typename ELFT::SymRange Symbols = 6337 unwrapOrError(this->FileName, this->Obj.symbols(Symtab)); 6338 for (const Elf_Sym &Sym : Symbols) { 6339 const Elf_Shdr *SymSec = unwrapOrError( 6340 this->FileName, this->Obj.getSection( 6341 Sym, Symtab, this->dumper().getShndxTable())); 6342 if (SymSec == &Sec) 6343 printSymbol(Sym, &Sym - &Symbols[0], StrTable, false, false); 6344 } 6345 } 6346 } 6347 6348 if (opts::SectionData && Sec.sh_type != ELF::SHT_NOBITS) { 6349 ArrayRef<uint8_t> Data = 6350 unwrapOrError(this->FileName, this->Obj.getSectionContents(Sec)); 6351 W.printBinaryBlock( 6352 "SectionData", 6353 StringRef(reinterpret_cast<const char *>(Data.data()), Data.size())); 6354 } 6355 } 6356 } 6357 6358 template <class ELFT> 6359 void LLVMStyle<ELFT>::printSymbolSection(const Elf_Sym &Symbol, 6360 unsigned SymIndex) { 6361 auto GetSectionSpecialType = [&]() -> Optional<StringRef> { 6362 if (Symbol.isUndefined()) 6363 return StringRef("Undefined"); 6364 if (Symbol.isProcessorSpecific()) 6365 return StringRef("Processor Specific"); 6366 if (Symbol.isOSSpecific()) 6367 return StringRef("Operating System Specific"); 6368 if (Symbol.isAbsolute()) 6369 return StringRef("Absolute"); 6370 if (Symbol.isCommon()) 6371 return StringRef("Common"); 6372 if (Symbol.isReserved() && Symbol.st_shndx != SHN_XINDEX) 6373 return StringRef("Reserved"); 6374 return None; 6375 }; 6376 6377 if (Optional<StringRef> Type = GetSectionSpecialType()) { 6378 W.printHex("Section", *Type, Symbol.st_shndx); 6379 return; 6380 } 6381 6382 Expected<unsigned> SectionIndex = 6383 this->dumper().getSymbolSectionIndex(Symbol, SymIndex); 6384 if (!SectionIndex) { 6385 assert(Symbol.st_shndx == SHN_XINDEX && 6386 "getSymbolSectionIndex should only fail due to an invalid " 6387 "SHT_SYMTAB_SHNDX table/reference"); 6388 this->reportUniqueWarning(SectionIndex.takeError()); 6389 W.printHex("Section", "Reserved", SHN_XINDEX); 6390 return; 6391 } 6392 6393 Expected<StringRef> SectionName = 6394 this->dumper().getSymbolSectionName(Symbol, *SectionIndex); 6395 if (!SectionName) { 6396 // Don't report an invalid section name if the section headers are missing. 6397 // In such situations, all sections will be "invalid". 6398 if (!this->dumper().getElfObject().sections().empty()) 6399 this->reportUniqueWarning(SectionName.takeError()); 6400 else 6401 consumeError(SectionName.takeError()); 6402 W.printHex("Section", "<?>", *SectionIndex); 6403 } else { 6404 W.printHex("Section", *SectionName, *SectionIndex); 6405 } 6406 } 6407 6408 template <class ELFT> 6409 void LLVMStyle<ELFT>::printSymbol(const Elf_Sym &Symbol, unsigned SymIndex, 6410 Optional<StringRef> StrTable, bool IsDynamic, 6411 bool /*NonVisibilityBitsUsed*/) { 6412 std::string FullSymbolName = 6413 this->dumper().getFullSymbolName(Symbol, SymIndex, StrTable, IsDynamic); 6414 unsigned char SymbolType = Symbol.getType(); 6415 6416 DictScope D(W, "Symbol"); 6417 W.printNumber("Name", FullSymbolName, Symbol.st_name); 6418 W.printHex("Value", Symbol.st_value); 6419 W.printNumber("Size", Symbol.st_size); 6420 W.printEnum("Binding", Symbol.getBinding(), makeArrayRef(ElfSymbolBindings)); 6421 if (this->Obj.getHeader().e_machine == ELF::EM_AMDGPU && 6422 SymbolType >= ELF::STT_LOOS && SymbolType < ELF::STT_HIOS) 6423 W.printEnum("Type", SymbolType, makeArrayRef(AMDGPUSymbolTypes)); 6424 else 6425 W.printEnum("Type", SymbolType, makeArrayRef(ElfSymbolTypes)); 6426 if (Symbol.st_other == 0) 6427 // Usually st_other flag is zero. Do not pollute the output 6428 // by flags enumeration in that case. 6429 W.printNumber("Other", 0); 6430 else { 6431 std::vector<EnumEntry<unsigned>> SymOtherFlags(std::begin(ElfSymOtherFlags), 6432 std::end(ElfSymOtherFlags)); 6433 if (this->Obj.getHeader().e_machine == EM_MIPS) { 6434 // Someones in their infinite wisdom decided to make STO_MIPS_MIPS16 6435 // flag overlapped with other ST_MIPS_xxx flags. So consider both 6436 // cases separately. 6437 if ((Symbol.st_other & STO_MIPS_MIPS16) == STO_MIPS_MIPS16) 6438 SymOtherFlags.insert(SymOtherFlags.end(), 6439 std::begin(ElfMips16SymOtherFlags), 6440 std::end(ElfMips16SymOtherFlags)); 6441 else 6442 SymOtherFlags.insert(SymOtherFlags.end(), 6443 std::begin(ElfMipsSymOtherFlags), 6444 std::end(ElfMipsSymOtherFlags)); 6445 } 6446 W.printFlags("Other", Symbol.st_other, makeArrayRef(SymOtherFlags), 0x3u); 6447 } 6448 printSymbolSection(Symbol, SymIndex); 6449 } 6450 6451 template <class ELFT> 6452 void LLVMStyle<ELFT>::printSymbols(bool PrintSymbols, 6453 bool PrintDynamicSymbols) { 6454 if (PrintSymbols) 6455 printSymbols(); 6456 if (PrintDynamicSymbols) 6457 printDynamicSymbols(); 6458 } 6459 6460 template <class ELFT> void LLVMStyle<ELFT>::printSymbols() { 6461 ListScope Group(W, "Symbols"); 6462 this->dumper().printSymbolsHelper(false); 6463 } 6464 6465 template <class ELFT> void LLVMStyle<ELFT>::printDynamicSymbols() { 6466 ListScope Group(W, "DynamicSymbols"); 6467 this->dumper().printSymbolsHelper(true); 6468 } 6469 6470 template <class ELFT> void LLVMStyle<ELFT>::printDynamic() { 6471 Elf_Dyn_Range Table = this->dumper().dynamic_table(); 6472 if (Table.empty()) 6473 return; 6474 6475 W.startLine() << "DynamicSection [ (" << Table.size() << " entries)\n"; 6476 6477 size_t MaxTagSize = getMaxDynamicTagSize(this->Obj, Table); 6478 // The "Name/Value" column should be indented from the "Type" column by N 6479 // spaces, where N = MaxTagSize - length of "Type" (4) + trailing 6480 // space (1) = -3. 6481 W.startLine() << " Tag" << std::string(ELFT::Is64Bits ? 16 : 8, ' ') 6482 << "Type" << std::string(MaxTagSize - 3, ' ') << "Name/Value\n"; 6483 6484 std::string ValueFmt = "%-" + std::to_string(MaxTagSize) + "s "; 6485 for (auto Entry : Table) { 6486 uintX_t Tag = Entry.getTag(); 6487 std::string Value = this->dumper().getDynamicEntry(Tag, Entry.getVal()); 6488 W.startLine() << " " << format_hex(Tag, ELFT::Is64Bits ? 18 : 10, true) 6489 << " " 6490 << format(ValueFmt.c_str(), 6491 this->Obj.getDynamicTagAsString(Tag).c_str()) 6492 << Value << "\n"; 6493 } 6494 W.startLine() << "]\n"; 6495 } 6496 6497 template <class ELFT> void LLVMStyle<ELFT>::printDynamicRelocations() { 6498 W.startLine() << "Dynamic Relocations {\n"; 6499 W.indent(); 6500 this->printDynamicRelocationsHelper(); 6501 W.unindent(); 6502 W.startLine() << "}\n"; 6503 } 6504 6505 template <class ELFT> 6506 void LLVMStyle<ELFT>::printDynamicReloc(const Relocation<ELFT> &R) { 6507 RelSymbol<ELFT> S = 6508 getSymbolForReloc(this->Obj, this->FileName, this->dumper(), R); 6509 printRelRelaReloc(R, S.Name); 6510 } 6511 6512 template <class ELFT> 6513 void LLVMStyle<ELFT>::printProgramHeaders( 6514 bool PrintProgramHeaders, cl::boolOrDefault PrintSectionMapping) { 6515 if (PrintProgramHeaders) 6516 printProgramHeaders(); 6517 if (PrintSectionMapping == cl::BOU_TRUE) 6518 printSectionMapping(); 6519 } 6520 6521 template <class ELFT> void LLVMStyle<ELFT>::printProgramHeaders() { 6522 ListScope L(W, "ProgramHeaders"); 6523 6524 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers(); 6525 if (!PhdrsOrErr) { 6526 this->reportUniqueWarning(createError("unable to dump program headers: " + 6527 toString(PhdrsOrErr.takeError()))); 6528 return; 6529 } 6530 6531 for (const Elf_Phdr &Phdr : *PhdrsOrErr) { 6532 DictScope P(W, "ProgramHeader"); 6533 StringRef Type = 6534 segmentTypeToString(this->Obj.getHeader().e_machine, Phdr.p_type); 6535 6536 W.printHex("Type", Type.empty() ? "Unknown" : Type, Phdr.p_type); 6537 W.printHex("Offset", Phdr.p_offset); 6538 W.printHex("VirtualAddress", Phdr.p_vaddr); 6539 W.printHex("PhysicalAddress", Phdr.p_paddr); 6540 W.printNumber("FileSize", Phdr.p_filesz); 6541 W.printNumber("MemSize", Phdr.p_memsz); 6542 W.printFlags("Flags", Phdr.p_flags, makeArrayRef(ElfSegmentFlags)); 6543 W.printNumber("Alignment", Phdr.p_align); 6544 } 6545 } 6546 6547 template <class ELFT> 6548 void LLVMStyle<ELFT>::printVersionSymbolSection(const Elf_Shdr *Sec) { 6549 ListScope SS(W, "VersionSymbols"); 6550 if (!Sec) 6551 return; 6552 6553 StringRef StrTable; 6554 ArrayRef<Elf_Sym> Syms; 6555 Expected<ArrayRef<Elf_Versym>> VerTableOrErr = 6556 this->dumper().getVersionTable(*Sec, &Syms, &StrTable); 6557 if (!VerTableOrErr) { 6558 this->reportUniqueWarning(VerTableOrErr.takeError()); 6559 return; 6560 } 6561 6562 if (StrTable.empty() || Syms.empty() || Syms.size() != VerTableOrErr->size()) 6563 return; 6564 6565 for (size_t I = 0, E = Syms.size(); I < E; ++I) { 6566 DictScope S(W, "Symbol"); 6567 W.printNumber("Version", (*VerTableOrErr)[I].vs_index & VERSYM_VERSION); 6568 W.printString("Name", this->dumper().getFullSymbolName(Syms[I], I, StrTable, 6569 /*IsDynamic=*/true)); 6570 } 6571 } 6572 6573 static const EnumEntry<unsigned> SymVersionFlags[] = { 6574 {"Base", "BASE", VER_FLG_BASE}, 6575 {"Weak", "WEAK", VER_FLG_WEAK}, 6576 {"Info", "INFO", VER_FLG_INFO}}; 6577 6578 template <class ELFT> 6579 void LLVMStyle<ELFT>::printVersionDefinitionSection(const Elf_Shdr *Sec) { 6580 ListScope SD(W, "VersionDefinitions"); 6581 if (!Sec) 6582 return; 6583 6584 Expected<std::vector<VerDef>> V = this->dumper().getVersionDefinitions(*Sec); 6585 if (!V) { 6586 this->reportUniqueWarning(V.takeError()); 6587 return; 6588 } 6589 6590 for (const VerDef &D : *V) { 6591 DictScope Def(W, "Definition"); 6592 W.printNumber("Version", D.Version); 6593 W.printFlags("Flags", D.Flags, makeArrayRef(SymVersionFlags)); 6594 W.printNumber("Index", D.Ndx); 6595 W.printNumber("Hash", D.Hash); 6596 W.printString("Name", D.Name.c_str()); 6597 W.printList( 6598 "Predecessors", D.AuxV, 6599 [](raw_ostream &OS, const VerdAux &Aux) { OS << Aux.Name.c_str(); }); 6600 } 6601 } 6602 6603 template <class ELFT> 6604 void LLVMStyle<ELFT>::printVersionDependencySection(const Elf_Shdr *Sec) { 6605 ListScope SD(W, "VersionRequirements"); 6606 if (!Sec) 6607 return; 6608 6609 Expected<std::vector<VerNeed>> V = this->dumper().getVersionDependencies(*Sec); 6610 if (!V) { 6611 this->reportUniqueWarning(V.takeError()); 6612 return; 6613 } 6614 6615 for (const VerNeed &VN : *V) { 6616 DictScope Entry(W, "Dependency"); 6617 W.printNumber("Version", VN.Version); 6618 W.printNumber("Count", VN.Cnt); 6619 W.printString("FileName", VN.File.c_str()); 6620 6621 ListScope L(W, "Entries"); 6622 for (const VernAux &Aux : VN.AuxV) { 6623 DictScope Entry(W, "Entry"); 6624 W.printNumber("Hash", Aux.Hash); 6625 W.printFlags("Flags", Aux.Flags, makeArrayRef(SymVersionFlags)); 6626 W.printNumber("Index", Aux.Other); 6627 W.printString("Name", Aux.Name.c_str()); 6628 } 6629 } 6630 } 6631 6632 template <class ELFT> void LLVMStyle<ELFT>::printHashHistograms() { 6633 W.startLine() << "Hash Histogram not implemented!\n"; 6634 } 6635 6636 template <class ELFT> void LLVMStyle<ELFT>::printCGProfile() { 6637 ListScope L(W, "CGProfile"); 6638 if (!this->dumper().getDotCGProfileSec()) 6639 return; 6640 6641 Expected<ArrayRef<Elf_CGProfile>> CGProfileOrErr = 6642 this->Obj.template getSectionContentsAsArray<Elf_CGProfile>( 6643 *this->dumper().getDotCGProfileSec()); 6644 if (!CGProfileOrErr) { 6645 this->reportUniqueWarning( 6646 createError("unable to dump the SHT_LLVM_CALL_GRAPH_PROFILE section: " + 6647 toString(CGProfileOrErr.takeError()))); 6648 return; 6649 } 6650 6651 for (const Elf_CGProfile &CGPE : *CGProfileOrErr) { 6652 DictScope D(W, "CGProfileEntry"); 6653 W.printNumber("From", this->dumper().getStaticSymbolName(CGPE.cgp_from), 6654 CGPE.cgp_from); 6655 W.printNumber("To", this->dumper().getStaticSymbolName(CGPE.cgp_to), 6656 CGPE.cgp_to); 6657 W.printNumber("Weight", CGPE.cgp_weight); 6658 } 6659 } 6660 6661 template <class ELFT> void LLVMStyle<ELFT>::printAddrsig() { 6662 ListScope L(W, "Addrsig"); 6663 const Elf_Shdr *Sec = this->dumper().getDotAddrsigSec(); 6664 if (!Sec) 6665 return; 6666 6667 Expected<std::vector<uint64_t>> SymsOrErr = 6668 decodeAddrsigSection(this->Obj, *Sec); 6669 if (!SymsOrErr) { 6670 this->reportUniqueWarning(SymsOrErr.takeError()); 6671 return; 6672 } 6673 6674 for (uint64_t Sym : *SymsOrErr) 6675 W.printNumber("Sym", this->dumper().getStaticSymbolName(Sym), Sym); 6676 } 6677 6678 template <typename ELFT> 6679 static void printGNUNoteLLVMStyle(uint32_t NoteType, ArrayRef<uint8_t> Desc, 6680 ScopedPrinter &W) { 6681 switch (NoteType) { 6682 default: 6683 return; 6684 case ELF::NT_GNU_ABI_TAG: { 6685 const GNUAbiTag &AbiTag = getGNUAbiTag<ELFT>(Desc); 6686 if (!AbiTag.IsValid) { 6687 W.printString("ABI", "<corrupt GNU_ABI_TAG>"); 6688 } else { 6689 W.printString("OS", AbiTag.OSName); 6690 W.printString("ABI", AbiTag.ABI); 6691 } 6692 break; 6693 } 6694 case ELF::NT_GNU_BUILD_ID: { 6695 W.printString("Build ID", getGNUBuildId(Desc)); 6696 break; 6697 } 6698 case ELF::NT_GNU_GOLD_VERSION: 6699 W.printString("Version", getGNUGoldVersion(Desc)); 6700 break; 6701 case ELF::NT_GNU_PROPERTY_TYPE_0: 6702 ListScope D(W, "Property"); 6703 for (const std::string &Property : getGNUPropertyList<ELFT>(Desc)) 6704 W.printString(Property); 6705 break; 6706 } 6707 } 6708 6709 static void printCoreNoteLLVMStyle(const CoreNote &Note, ScopedPrinter &W) { 6710 W.printNumber("Page Size", Note.PageSize); 6711 for (const CoreFileMapping &Mapping : Note.Mappings) { 6712 ListScope D(W, "Mapping"); 6713 W.printHex("Start", Mapping.Start); 6714 W.printHex("End", Mapping.End); 6715 W.printHex("Offset", Mapping.Offset); 6716 W.printString("Filename", Mapping.Filename); 6717 } 6718 } 6719 6720 template <class ELFT> void LLVMStyle<ELFT>::printNotes() { 6721 ListScope L(W, "Notes"); 6722 6723 auto PrintHeader = [&](Optional<StringRef> SecName, 6724 const typename ELFT::Off Offset, 6725 const typename ELFT::Addr Size) { 6726 W.printString("Name", SecName ? *SecName : "<?>"); 6727 W.printHex("Offset", Offset); 6728 W.printHex("Size", Size); 6729 }; 6730 6731 auto ProcessNote = [&](const Elf_Note &Note) { 6732 DictScope D2(W, "Note"); 6733 StringRef Name = Note.getName(); 6734 ArrayRef<uint8_t> Descriptor = Note.getDesc(); 6735 Elf_Word Type = Note.getType(); 6736 6737 // Print the note owner/type. 6738 W.printString("Owner", Name); 6739 W.printHex("Data size", Descriptor.size()); 6740 6741 StringRef NoteType = 6742 getNoteTypeName<ELFT>(Note, this->Obj.getHeader().e_type); 6743 if (!NoteType.empty()) 6744 W.printString("Type", NoteType); 6745 else 6746 W.printString("Type", 6747 "Unknown (" + to_string(format_hex(Type, 10)) + ")"); 6748 6749 // Print the description, or fallback to printing raw bytes for unknown 6750 // owners. 6751 if (Name == "GNU") { 6752 printGNUNoteLLVMStyle<ELFT>(Type, Descriptor, W); 6753 } else if (Name == "AMD") { 6754 const AMDNote N = getAMDNote<ELFT>(Type, Descriptor); 6755 if (!N.Type.empty()) 6756 W.printString(N.Type, N.Value); 6757 } else if (Name == "AMDGPU") { 6758 const AMDGPUNote N = getAMDGPUNote<ELFT>(Type, Descriptor); 6759 if (!N.Type.empty()) 6760 W.printString(N.Type, N.Value); 6761 } else if (Name == "CORE") { 6762 if (Type == ELF::NT_FILE) { 6763 DataExtractor DescExtractor(Descriptor, 6764 ELFT::TargetEndianness == support::little, 6765 sizeof(Elf_Addr)); 6766 Expected<CoreNote> Note = readCoreNote(DescExtractor); 6767 if (Note) 6768 printCoreNoteLLVMStyle(*Note, W); 6769 else 6770 reportWarning(Note.takeError(), this->FileName); 6771 } 6772 } else if (!Descriptor.empty()) { 6773 W.printBinaryBlock("Description data", Descriptor); 6774 } 6775 }; 6776 6777 ArrayRef<Elf_Shdr> Sections = cantFail(this->Obj.sections()); 6778 if (this->Obj.getHeader().e_type != ELF::ET_CORE && !Sections.empty()) { 6779 for (const Elf_Shdr &S : Sections) { 6780 if (S.sh_type != SHT_NOTE) 6781 continue; 6782 DictScope D(W, "NoteSection"); 6783 PrintHeader(expectedToOptional(this->Obj.getSectionName(S)), S.sh_offset, 6784 S.sh_size); 6785 Error Err = Error::success(); 6786 for (auto Note : this->Obj.notes(S, Err)) 6787 ProcessNote(Note); 6788 if (Err) 6789 reportError(std::move(Err), this->FileName); 6790 } 6791 } else { 6792 Expected<ArrayRef<Elf_Phdr>> PhdrsOrErr = this->Obj.program_headers(); 6793 if (!PhdrsOrErr) { 6794 this->reportUniqueWarning(createError( 6795 "unable to read program headers to locate the PT_NOTE segment: " + 6796 toString(PhdrsOrErr.takeError()))); 6797 return; 6798 } 6799 6800 for (const Elf_Phdr &P : *PhdrsOrErr) { 6801 if (P.p_type != PT_NOTE) 6802 continue; 6803 DictScope D(W, "NoteSection"); 6804 PrintHeader(/*SecName=*/None, P.p_offset, P.p_filesz); 6805 Error Err = Error::success(); 6806 for (auto Note : this->Obj.notes(P, Err)) 6807 ProcessNote(Note); 6808 if (Err) 6809 reportError(std::move(Err), this->FileName); 6810 } 6811 } 6812 } 6813 6814 template <class ELFT> void LLVMStyle<ELFT>::printELFLinkerOptions() { 6815 ListScope L(W, "LinkerOptions"); 6816 6817 unsigned I = -1; 6818 for (const Elf_Shdr &Shdr : cantFail(this->Obj.sections())) { 6819 ++I; 6820 if (Shdr.sh_type != ELF::SHT_LLVM_LINKER_OPTIONS) 6821 continue; 6822 6823 Expected<ArrayRef<uint8_t>> ContentsOrErr = 6824 this->Obj.getSectionContents(Shdr); 6825 if (!ContentsOrErr) { 6826 this->reportUniqueWarning( 6827 createError("unable to read the content of the " 6828 "SHT_LLVM_LINKER_OPTIONS section: " + 6829 toString(ContentsOrErr.takeError()))); 6830 continue; 6831 } 6832 if (ContentsOrErr->empty()) 6833 continue; 6834 6835 if (ContentsOrErr->back() != 0) { 6836 this->reportUniqueWarning( 6837 createError("SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) + 6838 " is broken: the " 6839 "content is not null-terminated")); 6840 continue; 6841 } 6842 6843 SmallVector<StringRef, 16> Strings; 6844 toStringRef(ContentsOrErr->drop_back()).split(Strings, '\0'); 6845 if (Strings.size() % 2 != 0) { 6846 this->reportUniqueWarning(createError( 6847 "SHT_LLVM_LINKER_OPTIONS section at index " + Twine(I) + 6848 " is broken: an incomplete " 6849 "key-value pair was found. The last possible key was: \"" + 6850 Strings.back() + "\"")); 6851 continue; 6852 } 6853 6854 for (size_t I = 0; I < Strings.size(); I += 2) 6855 W.printString(Strings[I], Strings[I + 1]); 6856 } 6857 } 6858 6859 template <class ELFT> void LLVMStyle<ELFT>::printDependentLibs() { 6860 ListScope L(W, "DependentLibs"); 6861 this->printDependentLibsHelper( 6862 [](const Elf_Shdr &) {}, 6863 [this](StringRef Lib, uint64_t) { W.printString(Lib); }); 6864 } 6865 6866 template <class ELFT> 6867 void LLVMStyle<ELFT>::printStackSizes() { 6868 ListScope L(W, "StackSizes"); 6869 if (this->Obj.getHeader().e_type == ELF::ET_REL) 6870 this->printRelocatableStackSizes([]() {}); 6871 else 6872 this->printNonRelocatableStackSizes([]() {}); 6873 } 6874 6875 template <class ELFT> 6876 void LLVMStyle<ELFT>::printStackSizeEntry(uint64_t Size, StringRef FuncName) { 6877 DictScope D(W, "Entry"); 6878 W.printString("Function", FuncName); 6879 W.printHex("Size", Size); 6880 } 6881 6882 template <class ELFT> 6883 void LLVMStyle<ELFT>::printMipsGOT(const MipsGOTParser<ELFT> &Parser) { 6884 auto PrintEntry = [&](const Elf_Addr *E) { 6885 W.printHex("Address", Parser.getGotAddress(E)); 6886 W.printNumber("Access", Parser.getGotOffset(E)); 6887 W.printHex("Initial", *E); 6888 }; 6889 6890 DictScope GS(W, Parser.IsStatic ? "Static GOT" : "Primary GOT"); 6891 6892 W.printHex("Canonical gp value", Parser.getGp()); 6893 { 6894 ListScope RS(W, "Reserved entries"); 6895 { 6896 DictScope D(W, "Entry"); 6897 PrintEntry(Parser.getGotLazyResolver()); 6898 W.printString("Purpose", StringRef("Lazy resolver")); 6899 } 6900 6901 if (Parser.getGotModulePointer()) { 6902 DictScope D(W, "Entry"); 6903 PrintEntry(Parser.getGotModulePointer()); 6904 W.printString("Purpose", StringRef("Module pointer (GNU extension)")); 6905 } 6906 } 6907 { 6908 ListScope LS(W, "Local entries"); 6909 for (auto &E : Parser.getLocalEntries()) { 6910 DictScope D(W, "Entry"); 6911 PrintEntry(&E); 6912 } 6913 } 6914 6915 if (Parser.IsStatic) 6916 return; 6917 6918 { 6919 ListScope GS(W, "Global entries"); 6920 for (auto &E : Parser.getGlobalEntries()) { 6921 DictScope D(W, "Entry"); 6922 6923 PrintEntry(&E); 6924 6925 const Elf_Sym &Sym = *Parser.getGotSym(&E); 6926 W.printHex("Value", Sym.st_value); 6927 W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes)); 6928 6929 const unsigned SymIndex = &Sym - this->dumper().dynamic_symbols().begin(); 6930 printSymbolSection(Sym, SymIndex); 6931 6932 std::string SymName = this->dumper().getFullSymbolName( 6933 Sym, SymIndex, this->dumper().getDynamicStringTable(), true); 6934 W.printNumber("Name", SymName, Sym.st_name); 6935 } 6936 } 6937 6938 W.printNumber("Number of TLS and multi-GOT entries", 6939 uint64_t(Parser.getOtherEntries().size())); 6940 } 6941 6942 template <class ELFT> 6943 void LLVMStyle<ELFT>::printMipsPLT(const MipsGOTParser<ELFT> &Parser) { 6944 auto PrintEntry = [&](const Elf_Addr *E) { 6945 W.printHex("Address", Parser.getPltAddress(E)); 6946 W.printHex("Initial", *E); 6947 }; 6948 6949 DictScope GS(W, "PLT GOT"); 6950 6951 { 6952 ListScope RS(W, "Reserved entries"); 6953 { 6954 DictScope D(W, "Entry"); 6955 PrintEntry(Parser.getPltLazyResolver()); 6956 W.printString("Purpose", StringRef("PLT lazy resolver")); 6957 } 6958 6959 if (auto E = Parser.getPltModulePointer()) { 6960 DictScope D(W, "Entry"); 6961 PrintEntry(E); 6962 W.printString("Purpose", StringRef("Module pointer")); 6963 } 6964 } 6965 { 6966 ListScope LS(W, "Entries"); 6967 for (auto &E : Parser.getPltEntries()) { 6968 DictScope D(W, "Entry"); 6969 PrintEntry(&E); 6970 6971 const Elf_Sym &Sym = *Parser.getPltSym(&E); 6972 W.printHex("Value", Sym.st_value); 6973 W.printEnum("Type", Sym.getType(), makeArrayRef(ElfSymbolTypes)); 6974 printSymbolSection(Sym, &Sym - this->dumper().dynamic_symbols().begin()); 6975 6976 const Elf_Sym *FirstSym = 6977 cantFail(this->Obj.template getEntry<const Elf_Sym>( 6978 *Parser.getPltSymTable(), 0)); 6979 std::string SymName = this->dumper().getFullSymbolName( 6980 Sym, &Sym - FirstSym, Parser.getPltStrTable(), true); 6981 W.printNumber("Name", SymName, Sym.st_name); 6982 } 6983 } 6984 } 6985 6986 template <class ELFT> void LLVMStyle<ELFT>::printMipsABIFlags() { 6987 const Elf_Mips_ABIFlags<ELFT> *Flags; 6988 if (Expected<const Elf_Mips_ABIFlags<ELFT> *> SecOrErr = 6989 getMipsAbiFlagsSection(this->dumper())) { 6990 Flags = *SecOrErr; 6991 if (!Flags) { 6992 W.startLine() << "There is no .MIPS.abiflags section in the file.\n"; 6993 return; 6994 } 6995 } else { 6996 this->reportUniqueWarning(SecOrErr.takeError()); 6997 return; 6998 } 6999 7000 raw_ostream &OS = W.getOStream(); 7001 DictScope GS(W, "MIPS ABI Flags"); 7002 7003 W.printNumber("Version", Flags->version); 7004 W.startLine() << "ISA: "; 7005 if (Flags->isa_rev <= 1) 7006 OS << format("MIPS%u", Flags->isa_level); 7007 else 7008 OS << format("MIPS%ur%u", Flags->isa_level, Flags->isa_rev); 7009 OS << "\n"; 7010 W.printEnum("ISA Extension", Flags->isa_ext, makeArrayRef(ElfMipsISAExtType)); 7011 W.printFlags("ASEs", Flags->ases, makeArrayRef(ElfMipsASEFlags)); 7012 W.printEnum("FP ABI", Flags->fp_abi, makeArrayRef(ElfMipsFpABIType)); 7013 W.printNumber("GPR size", getMipsRegisterSize(Flags->gpr_size)); 7014 W.printNumber("CPR1 size", getMipsRegisterSize(Flags->cpr1_size)); 7015 W.printNumber("CPR2 size", getMipsRegisterSize(Flags->cpr2_size)); 7016 W.printFlags("Flags 1", Flags->flags1, makeArrayRef(ElfMipsFlags1)); 7017 W.printHex("Flags 2", Flags->flags2); 7018 } 7019