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