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