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