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