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