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