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