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