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