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