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