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