Home | History | Annotate | Download | only in Object
      1 //===- ELFObjectFile.h - ELF object file implementation ---------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file declares the ELFObjectFile template class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_OBJECT_ELFOBJECTFILE_H
     15 #define LLVM_OBJECT_ELFOBJECTFILE_H
     16 
     17 #include "llvm/ADT/ArrayRef.h"
     18 #include "llvm/ADT/SmallVector.h"
     19 #include "llvm/ADT/StringRef.h"
     20 #include "llvm/ADT/Triple.h"
     21 #include "llvm/ADT/iterator_range.h"
     22 #include "llvm/BinaryFormat/ELF.h"
     23 #include "llvm/MC/SubtargetFeature.h"
     24 #include "llvm/Object/Binary.h"
     25 #include "llvm/Object/ELF.h"
     26 #include "llvm/Object/ELFTypes.h"
     27 #include "llvm/Object/Error.h"
     28 #include "llvm/Object/ObjectFile.h"
     29 #include "llvm/Object/SymbolicFile.h"
     30 #include "llvm/Support/ARMAttributeParser.h"
     31 #include "llvm/Support/ARMBuildAttributes.h"
     32 #include "llvm/Support/Casting.h"
     33 #include "llvm/Support/Endian.h"
     34 #include "llvm/Support/Error.h"
     35 #include "llvm/Support/ErrorHandling.h"
     36 #include "llvm/Support/ErrorOr.h"
     37 #include "llvm/Support/MemoryBuffer.h"
     38 #include <cassert>
     39 #include <cstdint>
     40 #include <system_error>
     41 
     42 namespace llvm {
     43 namespace object {
     44 
     45 class elf_symbol_iterator;
     46 
     47 class ELFObjectFileBase : public ObjectFile {
     48   friend class ELFRelocationRef;
     49   friend class ELFSectionRef;
     50   friend class ELFSymbolRef;
     51 
     52 protected:
     53   ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source);
     54 
     55   virtual uint16_t getEMachine() const = 0;
     56   virtual uint64_t getSymbolSize(DataRefImpl Symb) const = 0;
     57   virtual uint8_t getSymbolOther(DataRefImpl Symb) const = 0;
     58   virtual uint8_t getSymbolELFType(DataRefImpl Symb) const = 0;
     59 
     60   virtual uint32_t getSectionType(DataRefImpl Sec) const = 0;
     61   virtual uint64_t getSectionFlags(DataRefImpl Sec) const = 0;
     62   virtual uint64_t getSectionOffset(DataRefImpl Sec) const = 0;
     63 
     64   virtual ErrorOr<int64_t> getRelocationAddend(DataRefImpl Rel) const = 0;
     65 
     66 public:
     67   using elf_symbol_iterator_range = iterator_range<elf_symbol_iterator>;
     68 
     69   virtual elf_symbol_iterator_range getDynamicSymbolIterators() const = 0;
     70 
     71   elf_symbol_iterator_range symbols() const;
     72 
     73   static inline bool classof(const Binary *v) { return v->isELF(); }
     74 
     75   SubtargetFeatures getFeatures() const override;
     76 
     77   SubtargetFeatures getMIPSFeatures() const;
     78 
     79   SubtargetFeatures getARMFeatures() const;
     80 
     81   void setARMSubArch(Triple &TheTriple) const override;
     82 };
     83 
     84 class ELFSectionRef : public SectionRef {
     85 public:
     86   ELFSectionRef(const SectionRef &B) : SectionRef(B) {
     87     assert(isa<ELFObjectFileBase>(SectionRef::getObject()));
     88   }
     89 
     90   const ELFObjectFileBase *getObject() const {
     91     return cast<ELFObjectFileBase>(SectionRef::getObject());
     92   }
     93 
     94   uint32_t getType() const {
     95     return getObject()->getSectionType(getRawDataRefImpl());
     96   }
     97 
     98   uint64_t getFlags() const {
     99     return getObject()->getSectionFlags(getRawDataRefImpl());
    100   }
    101 
    102   uint64_t getOffset() const {
    103     return getObject()->getSectionOffset(getRawDataRefImpl());
    104   }
    105 };
    106 
    107 class elf_section_iterator : public section_iterator {
    108 public:
    109   elf_section_iterator(const section_iterator &B) : section_iterator(B) {
    110     assert(isa<ELFObjectFileBase>(B->getObject()));
    111   }
    112 
    113   const ELFSectionRef *operator->() const {
    114     return static_cast<const ELFSectionRef *>(section_iterator::operator->());
    115   }
    116 
    117   const ELFSectionRef &operator*() const {
    118     return static_cast<const ELFSectionRef &>(section_iterator::operator*());
    119   }
    120 };
    121 
    122 class ELFSymbolRef : public SymbolRef {
    123 public:
    124   ELFSymbolRef(const SymbolRef &B) : SymbolRef(B) {
    125     assert(isa<ELFObjectFileBase>(SymbolRef::getObject()));
    126   }
    127 
    128   const ELFObjectFileBase *getObject() const {
    129     return cast<ELFObjectFileBase>(BasicSymbolRef::getObject());
    130   }
    131 
    132   uint64_t getSize() const {
    133     return getObject()->getSymbolSize(getRawDataRefImpl());
    134   }
    135 
    136   uint8_t getOther() const {
    137     return getObject()->getSymbolOther(getRawDataRefImpl());
    138   }
    139 
    140   uint8_t getELFType() const {
    141     return getObject()->getSymbolELFType(getRawDataRefImpl());
    142   }
    143 };
    144 
    145 class elf_symbol_iterator : public symbol_iterator {
    146 public:
    147   elf_symbol_iterator(const basic_symbol_iterator &B)
    148       : symbol_iterator(SymbolRef(B->getRawDataRefImpl(),
    149                                   cast<ELFObjectFileBase>(B->getObject()))) {}
    150 
    151   const ELFSymbolRef *operator->() const {
    152     return static_cast<const ELFSymbolRef *>(symbol_iterator::operator->());
    153   }
    154 
    155   const ELFSymbolRef &operator*() const {
    156     return static_cast<const ELFSymbolRef &>(symbol_iterator::operator*());
    157   }
    158 };
    159 
    160 class ELFRelocationRef : public RelocationRef {
    161 public:
    162   ELFRelocationRef(const RelocationRef &B) : RelocationRef(B) {
    163     assert(isa<ELFObjectFileBase>(RelocationRef::getObject()));
    164   }
    165 
    166   const ELFObjectFileBase *getObject() const {
    167     return cast<ELFObjectFileBase>(RelocationRef::getObject());
    168   }
    169 
    170   ErrorOr<int64_t> getAddend() const {
    171     return getObject()->getRelocationAddend(getRawDataRefImpl());
    172   }
    173 };
    174 
    175 class elf_relocation_iterator : public relocation_iterator {
    176 public:
    177   elf_relocation_iterator(const relocation_iterator &B)
    178       : relocation_iterator(RelocationRef(
    179             B->getRawDataRefImpl(), cast<ELFObjectFileBase>(B->getObject()))) {}
    180 
    181   const ELFRelocationRef *operator->() const {
    182     return static_cast<const ELFRelocationRef *>(
    183         relocation_iterator::operator->());
    184   }
    185 
    186   const ELFRelocationRef &operator*() const {
    187     return static_cast<const ELFRelocationRef &>(
    188         relocation_iterator::operator*());
    189   }
    190 };
    191 
    192 inline ELFObjectFileBase::elf_symbol_iterator_range
    193 ELFObjectFileBase::symbols() const {
    194   return elf_symbol_iterator_range(symbol_begin(), symbol_end());
    195 }
    196 
    197 template <class ELFT> class ELFObjectFile : public ELFObjectFileBase {
    198   uint16_t getEMachine() const override;
    199   uint64_t getSymbolSize(DataRefImpl Sym) const override;
    200 
    201 public:
    202   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
    203 
    204   using uintX_t = typename ELFFile<ELFT>::uintX_t;
    205 
    206   using Elf_Sym = typename ELFFile<ELFT>::Elf_Sym;
    207   using Elf_Shdr = typename ELFFile<ELFT>::Elf_Shdr;
    208   using Elf_Ehdr = typename ELFFile<ELFT>::Elf_Ehdr;
    209   using Elf_Rel = typename ELFFile<ELFT>::Elf_Rel;
    210   using Elf_Rela = typename ELFFile<ELFT>::Elf_Rela;
    211   using Elf_Dyn = typename ELFFile<ELFT>::Elf_Dyn;
    212 
    213 protected:
    214   ELFFile<ELFT> EF;
    215 
    216   const Elf_Shdr *DotDynSymSec = nullptr; // Dynamic symbol table section.
    217   const Elf_Shdr *DotSymtabSec = nullptr; // Symbol table section.
    218   ArrayRef<Elf_Word> ShndxTable;
    219 
    220   void moveSymbolNext(DataRefImpl &Symb) const override;
    221   Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
    222   Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
    223   uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
    224   uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
    225   uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
    226   uint32_t getSymbolFlags(DataRefImpl Symb) const override;
    227   uint8_t getSymbolOther(DataRefImpl Symb) const override;
    228   uint8_t getSymbolELFType(DataRefImpl Symb) const override;
    229   Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
    230   Expected<section_iterator> getSymbolSection(const Elf_Sym *Symb,
    231                                               const Elf_Shdr *SymTab) const;
    232   Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
    233 
    234   void moveSectionNext(DataRefImpl &Sec) const override;
    235   std::error_code getSectionName(DataRefImpl Sec,
    236                                  StringRef &Res) const override;
    237   uint64_t getSectionAddress(DataRefImpl Sec) const override;
    238   uint64_t getSectionIndex(DataRefImpl Sec) const override;
    239   uint64_t getSectionSize(DataRefImpl Sec) const override;
    240   std::error_code getSectionContents(DataRefImpl Sec,
    241                                      StringRef &Res) const override;
    242   uint64_t getSectionAlignment(DataRefImpl Sec) const override;
    243   bool isSectionCompressed(DataRefImpl Sec) const override;
    244   bool isSectionText(DataRefImpl Sec) const override;
    245   bool isSectionData(DataRefImpl Sec) const override;
    246   bool isSectionBSS(DataRefImpl Sec) const override;
    247   bool isSectionVirtual(DataRefImpl Sec) const override;
    248   relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
    249   relocation_iterator section_rel_end(DataRefImpl Sec) const override;
    250   section_iterator getRelocatedSection(DataRefImpl Sec) const override;
    251 
    252   void moveRelocationNext(DataRefImpl &Rel) const override;
    253   uint64_t getRelocationOffset(DataRefImpl Rel) const override;
    254   symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
    255   uint64_t getRelocationType(DataRefImpl Rel) const override;
    256   void getRelocationTypeName(DataRefImpl Rel,
    257                              SmallVectorImpl<char> &Result) const override;
    258 
    259   uint32_t getSectionType(DataRefImpl Sec) const override;
    260   uint64_t getSectionFlags(DataRefImpl Sec) const override;
    261   uint64_t getSectionOffset(DataRefImpl Sec) const override;
    262   StringRef getRelocationTypeName(uint32_t Type) const;
    263 
    264   /// \brief Get the relocation section that contains \a Rel.
    265   const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
    266     auto RelSecOrErr = EF.getSection(Rel.d.a);
    267     if (!RelSecOrErr)
    268       report_fatal_error(errorToErrorCode(RelSecOrErr.takeError()).message());
    269     return *RelSecOrErr;
    270   }
    271 
    272   DataRefImpl toDRI(const Elf_Shdr *SymTable, unsigned SymbolNum) const {
    273     DataRefImpl DRI;
    274     if (!SymTable) {
    275       DRI.d.a = 0;
    276       DRI.d.b = 0;
    277       return DRI;
    278     }
    279     assert(SymTable->sh_type == ELF::SHT_SYMTAB ||
    280            SymTable->sh_type == ELF::SHT_DYNSYM);
    281 
    282     auto SectionsOrErr = EF.sections();
    283     if (!SectionsOrErr) {
    284       DRI.d.a = 0;
    285       DRI.d.b = 0;
    286       return DRI;
    287     }
    288     uintptr_t SHT = reinterpret_cast<uintptr_t>((*SectionsOrErr).begin());
    289     unsigned SymTableIndex =
    290         (reinterpret_cast<uintptr_t>(SymTable) - SHT) / sizeof(Elf_Shdr);
    291 
    292     DRI.d.a = SymTableIndex;
    293     DRI.d.b = SymbolNum;
    294     return DRI;
    295   }
    296 
    297   const Elf_Shdr *toELFShdrIter(DataRefImpl Sec) const {
    298     return reinterpret_cast<const Elf_Shdr *>(Sec.p);
    299   }
    300 
    301   DataRefImpl toDRI(const Elf_Shdr *Sec) const {
    302     DataRefImpl DRI;
    303     DRI.p = reinterpret_cast<uintptr_t>(Sec);
    304     return DRI;
    305   }
    306 
    307   DataRefImpl toDRI(const Elf_Dyn *Dyn) const {
    308     DataRefImpl DRI;
    309     DRI.p = reinterpret_cast<uintptr_t>(Dyn);
    310     return DRI;
    311   }
    312 
    313   bool isExportedToOtherDSO(const Elf_Sym *ESym) const {
    314     unsigned char Binding = ESym->getBinding();
    315     unsigned char Visibility = ESym->getVisibility();
    316 
    317     // A symbol is exported if its binding is either GLOBAL or WEAK, and its
    318     // visibility is either DEFAULT or PROTECTED. All other symbols are not
    319     // exported.
    320     return ((Binding == ELF::STB_GLOBAL || Binding == ELF::STB_WEAK) &&
    321             (Visibility == ELF::STV_DEFAULT ||
    322              Visibility == ELF::STV_PROTECTED));
    323   }
    324 
    325   // This flag is used for classof, to distinguish ELFObjectFile from
    326   // its subclass. If more subclasses will be created, this flag will
    327   // have to become an enum.
    328   bool isDyldELFObject;
    329 
    330 public:
    331   ELFObjectFile(MemoryBufferRef Object, std::error_code &EC);
    332 
    333   const Elf_Rel *getRel(DataRefImpl Rel) const;
    334   const Elf_Rela *getRela(DataRefImpl Rela) const;
    335 
    336   const Elf_Sym *getSymbol(DataRefImpl Sym) const {
    337     auto Ret = EF.template getEntry<Elf_Sym>(Sym.d.a, Sym.d.b);
    338     if (!Ret)
    339       report_fatal_error(errorToErrorCode(Ret.takeError()).message());
    340     return *Ret;
    341   }
    342 
    343   const Elf_Shdr *getSection(DataRefImpl Sec) const {
    344     return reinterpret_cast<const Elf_Shdr *>(Sec.p);
    345   }
    346 
    347   basic_symbol_iterator symbol_begin() const override;
    348   basic_symbol_iterator symbol_end() const override;
    349 
    350   elf_symbol_iterator dynamic_symbol_begin() const;
    351   elf_symbol_iterator dynamic_symbol_end() const;
    352 
    353   section_iterator section_begin() const override;
    354   section_iterator section_end() const override;
    355 
    356   ErrorOr<int64_t> getRelocationAddend(DataRefImpl Rel) const override;
    357 
    358   uint8_t getBytesInAddress() const override;
    359   StringRef getFileFormatName() const override;
    360   unsigned getArch() const override;
    361 
    362   std::error_code getPlatformFlags(unsigned &Result) const override {
    363     Result = EF.getHeader()->e_flags;
    364     return std::error_code();
    365   }
    366 
    367   std::error_code getBuildAttributes(ARMAttributeParser &Attributes) const override {
    368     auto SectionsOrErr = EF.sections();
    369     if (!SectionsOrErr)
    370       return errorToErrorCode(SectionsOrErr.takeError());
    371 
    372     for (const Elf_Shdr &Sec : *SectionsOrErr) {
    373       if (Sec.sh_type == ELF::SHT_ARM_ATTRIBUTES) {
    374         auto ErrorOrContents = EF.getSectionContents(&Sec);
    375         if (!ErrorOrContents)
    376           return errorToErrorCode(ErrorOrContents.takeError());
    377 
    378         auto Contents = ErrorOrContents.get();
    379         if (Contents[0] != ARMBuildAttrs::Format_Version || Contents.size() == 1)
    380           return std::error_code();
    381 
    382         Attributes.Parse(Contents, ELFT::TargetEndianness == support::little);
    383         break;
    384       }
    385     }
    386     return std::error_code();
    387   }
    388 
    389   const ELFFile<ELFT> *getELFFile() const { return &EF; }
    390 
    391   bool isDyldType() const { return isDyldELFObject; }
    392   static inline bool classof(const Binary *v) {
    393     return v->getType() == getELFType(ELFT::TargetEndianness == support::little,
    394                                       ELFT::Is64Bits);
    395   }
    396 
    397   elf_symbol_iterator_range getDynamicSymbolIterators() const override;
    398 
    399   bool isRelocatableObject() const override;
    400 };
    401 
    402 using ELF32LEObjectFile = ELFObjectFile<ELFType<support::little, false>>;
    403 using ELF64LEObjectFile = ELFObjectFile<ELFType<support::little, true>>;
    404 using ELF32BEObjectFile = ELFObjectFile<ELFType<support::big, false>>;
    405 using ELF64BEObjectFile = ELFObjectFile<ELFType<support::big, true>>;
    406 
    407 template <class ELFT>
    408 void ELFObjectFile<ELFT>::moveSymbolNext(DataRefImpl &Sym) const {
    409   ++Sym.d.b;
    410 }
    411 
    412 template <class ELFT>
    413 Expected<StringRef> ELFObjectFile<ELFT>::getSymbolName(DataRefImpl Sym) const {
    414   const Elf_Sym *ESym = getSymbol(Sym);
    415   auto SymTabOrErr = EF.getSection(Sym.d.a);
    416   if (!SymTabOrErr)
    417     return SymTabOrErr.takeError();
    418   const Elf_Shdr *SymTableSec = *SymTabOrErr;
    419   auto StrTabOrErr = EF.getSection(SymTableSec->sh_link);
    420   if (!StrTabOrErr)
    421     return StrTabOrErr.takeError();
    422   const Elf_Shdr *StringTableSec = *StrTabOrErr;
    423   auto SymStrTabOrErr = EF.getStringTable(StringTableSec);
    424   if (!SymStrTabOrErr)
    425     return SymStrTabOrErr.takeError();
    426   return ESym->getName(*SymStrTabOrErr);
    427 }
    428 
    429 template <class ELFT>
    430 uint64_t ELFObjectFile<ELFT>::getSectionFlags(DataRefImpl Sec) const {
    431   return getSection(Sec)->sh_flags;
    432 }
    433 
    434 template <class ELFT>
    435 uint32_t ELFObjectFile<ELFT>::getSectionType(DataRefImpl Sec) const {
    436   return getSection(Sec)->sh_type;
    437 }
    438 
    439 template <class ELFT>
    440 uint64_t ELFObjectFile<ELFT>::getSectionOffset(DataRefImpl Sec) const {
    441   return getSection(Sec)->sh_offset;
    442 }
    443 
    444 template <class ELFT>
    445 uint64_t ELFObjectFile<ELFT>::getSymbolValueImpl(DataRefImpl Symb) const {
    446   const Elf_Sym *ESym = getSymbol(Symb);
    447   uint64_t Ret = ESym->st_value;
    448   if (ESym->st_shndx == ELF::SHN_ABS)
    449     return Ret;
    450 
    451   const Elf_Ehdr *Header = EF.getHeader();
    452   // Clear the ARM/Thumb or microMIPS indicator flag.
    453   if ((Header->e_machine == ELF::EM_ARM || Header->e_machine == ELF::EM_MIPS) &&
    454       ESym->getType() == ELF::STT_FUNC)
    455     Ret &= ~1;
    456 
    457   return Ret;
    458 }
    459 
    460 template <class ELFT>
    461 Expected<uint64_t>
    462 ELFObjectFile<ELFT>::getSymbolAddress(DataRefImpl Symb) const {
    463   uint64_t Result = getSymbolValue(Symb);
    464   const Elf_Sym *ESym = getSymbol(Symb);
    465   switch (ESym->st_shndx) {
    466   case ELF::SHN_COMMON:
    467   case ELF::SHN_UNDEF:
    468   case ELF::SHN_ABS:
    469     return Result;
    470   }
    471 
    472   const Elf_Ehdr *Header = EF.getHeader();
    473   auto SymTabOrErr = EF.getSection(Symb.d.a);
    474   if (!SymTabOrErr)
    475     return SymTabOrErr.takeError();
    476   const Elf_Shdr *SymTab = *SymTabOrErr;
    477 
    478   if (Header->e_type == ELF::ET_REL) {
    479     auto SectionOrErr = EF.getSection(ESym, SymTab, ShndxTable);
    480     if (!SectionOrErr)
    481       return SectionOrErr.takeError();
    482     const Elf_Shdr *Section = *SectionOrErr;
    483     if (Section)
    484       Result += Section->sh_addr;
    485   }
    486 
    487   return Result;
    488 }
    489 
    490 template <class ELFT>
    491 uint32_t ELFObjectFile<ELFT>::getSymbolAlignment(DataRefImpl Symb) const {
    492   const Elf_Sym *Sym = getSymbol(Symb);
    493   if (Sym->st_shndx == ELF::SHN_COMMON)
    494     return Sym->st_value;
    495   return 0;
    496 }
    497 
    498 template <class ELFT>
    499 uint16_t ELFObjectFile<ELFT>::getEMachine() const {
    500   return EF.getHeader()->e_machine;
    501 }
    502 
    503 template <class ELFT>
    504 uint64_t ELFObjectFile<ELFT>::getSymbolSize(DataRefImpl Sym) const {
    505   return getSymbol(Sym)->st_size;
    506 }
    507 
    508 template <class ELFT>
    509 uint64_t ELFObjectFile<ELFT>::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
    510   return getSymbol(Symb)->st_size;
    511 }
    512 
    513 template <class ELFT>
    514 uint8_t ELFObjectFile<ELFT>::getSymbolOther(DataRefImpl Symb) const {
    515   return getSymbol(Symb)->st_other;
    516 }
    517 
    518 template <class ELFT>
    519 uint8_t ELFObjectFile<ELFT>::getSymbolELFType(DataRefImpl Symb) const {
    520   return getSymbol(Symb)->getType();
    521 }
    522 
    523 template <class ELFT>
    524 Expected<SymbolRef::Type>
    525 ELFObjectFile<ELFT>::getSymbolType(DataRefImpl Symb) const {
    526   const Elf_Sym *ESym = getSymbol(Symb);
    527 
    528   switch (ESym->getType()) {
    529   case ELF::STT_NOTYPE:
    530     return SymbolRef::ST_Unknown;
    531   case ELF::STT_SECTION:
    532     return SymbolRef::ST_Debug;
    533   case ELF::STT_FILE:
    534     return SymbolRef::ST_File;
    535   case ELF::STT_FUNC:
    536     return SymbolRef::ST_Function;
    537   case ELF::STT_OBJECT:
    538   case ELF::STT_COMMON:
    539   case ELF::STT_TLS:
    540     return SymbolRef::ST_Data;
    541   default:
    542     return SymbolRef::ST_Other;
    543   }
    544 }
    545 
    546 template <class ELFT>
    547 uint32_t ELFObjectFile<ELFT>::getSymbolFlags(DataRefImpl Sym) const {
    548   const Elf_Sym *ESym = getSymbol(Sym);
    549 
    550   uint32_t Result = SymbolRef::SF_None;
    551 
    552   if (ESym->getBinding() != ELF::STB_LOCAL)
    553     Result |= SymbolRef::SF_Global;
    554 
    555   if (ESym->getBinding() == ELF::STB_WEAK)
    556     Result |= SymbolRef::SF_Weak;
    557 
    558   if (ESym->st_shndx == ELF::SHN_ABS)
    559     Result |= SymbolRef::SF_Absolute;
    560 
    561   if (ESym->getType() == ELF::STT_FILE || ESym->getType() == ELF::STT_SECTION)
    562     Result |= SymbolRef::SF_FormatSpecific;
    563 
    564   auto DotSymtabSecSyms = EF.symbols(DotSymtabSec);
    565   if (DotSymtabSecSyms && ESym == (*DotSymtabSecSyms).begin())
    566     Result |= SymbolRef::SF_FormatSpecific;
    567   auto DotDynSymSecSyms = EF.symbols(DotDynSymSec);
    568   if (DotDynSymSecSyms && ESym == (*DotDynSymSecSyms).begin())
    569     Result |= SymbolRef::SF_FormatSpecific;
    570 
    571   if (EF.getHeader()->e_machine == ELF::EM_ARM) {
    572     if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
    573       StringRef Name = *NameOrErr;
    574       if (Name.startswith("$d") || Name.startswith("$t") ||
    575           Name.startswith("$a"))
    576         Result |= SymbolRef::SF_FormatSpecific;
    577     } else {
    578       // TODO: Actually report errors helpfully.
    579       consumeError(NameOrErr.takeError());
    580     }
    581     if (ESym->getType() == ELF::STT_FUNC && (ESym->st_value & 1) == 1)
    582       Result |= SymbolRef::SF_Thumb;
    583   }
    584 
    585   if (ESym->st_shndx == ELF::SHN_UNDEF)
    586     Result |= SymbolRef::SF_Undefined;
    587 
    588   if (ESym->getType() == ELF::STT_COMMON || ESym->st_shndx == ELF::SHN_COMMON)
    589     Result |= SymbolRef::SF_Common;
    590 
    591   if (isExportedToOtherDSO(ESym))
    592     Result |= SymbolRef::SF_Exported;
    593 
    594   if (ESym->getVisibility() == ELF::STV_HIDDEN)
    595     Result |= SymbolRef::SF_Hidden;
    596 
    597   return Result;
    598 }
    599 
    600 template <class ELFT>
    601 Expected<section_iterator>
    602 ELFObjectFile<ELFT>::getSymbolSection(const Elf_Sym *ESym,
    603                                       const Elf_Shdr *SymTab) const {
    604   auto ESecOrErr = EF.getSection(ESym, SymTab, ShndxTable);
    605   if (!ESecOrErr)
    606     return ESecOrErr.takeError();
    607 
    608   const Elf_Shdr *ESec = *ESecOrErr;
    609   if (!ESec)
    610     return section_end();
    611 
    612   DataRefImpl Sec;
    613   Sec.p = reinterpret_cast<intptr_t>(ESec);
    614   return section_iterator(SectionRef(Sec, this));
    615 }
    616 
    617 template <class ELFT>
    618 Expected<section_iterator>
    619 ELFObjectFile<ELFT>::getSymbolSection(DataRefImpl Symb) const {
    620   const Elf_Sym *Sym = getSymbol(Symb);
    621   auto SymTabOrErr = EF.getSection(Symb.d.a);
    622   if (!SymTabOrErr)
    623     return SymTabOrErr.takeError();
    624   const Elf_Shdr *SymTab = *SymTabOrErr;
    625   return getSymbolSection(Sym, SymTab);
    626 }
    627 
    628 template <class ELFT>
    629 void ELFObjectFile<ELFT>::moveSectionNext(DataRefImpl &Sec) const {
    630   const Elf_Shdr *ESec = getSection(Sec);
    631   Sec = toDRI(++ESec);
    632 }
    633 
    634 template <class ELFT>
    635 std::error_code ELFObjectFile<ELFT>::getSectionName(DataRefImpl Sec,
    636                                                     StringRef &Result) const {
    637   auto Name = EF.getSectionName(&*getSection(Sec));
    638   if (!Name)
    639     return errorToErrorCode(Name.takeError());
    640   Result = *Name;
    641   return std::error_code();
    642 }
    643 
    644 template <class ELFT>
    645 uint64_t ELFObjectFile<ELFT>::getSectionAddress(DataRefImpl Sec) const {
    646   return getSection(Sec)->sh_addr;
    647 }
    648 
    649 template <class ELFT>
    650 uint64_t ELFObjectFile<ELFT>::getSectionIndex(DataRefImpl Sec) const {
    651   auto SectionsOrErr = EF.sections();
    652   handleAllErrors(std::move(SectionsOrErr.takeError()),
    653                   [](const ErrorInfoBase &) {
    654                     llvm_unreachable("unable to get section index");
    655                   });
    656   const Elf_Shdr *First = SectionsOrErr->begin();
    657   return getSection(Sec) - First;
    658 }
    659 
    660 template <class ELFT>
    661 uint64_t ELFObjectFile<ELFT>::getSectionSize(DataRefImpl Sec) const {
    662   return getSection(Sec)->sh_size;
    663 }
    664 
    665 template <class ELFT>
    666 std::error_code
    667 ELFObjectFile<ELFT>::getSectionContents(DataRefImpl Sec,
    668                                         StringRef &Result) const {
    669   const Elf_Shdr *EShdr = getSection(Sec);
    670   Result = StringRef((const char *)base() + EShdr->sh_offset, EShdr->sh_size);
    671   return std::error_code();
    672 }
    673 
    674 template <class ELFT>
    675 uint64_t ELFObjectFile<ELFT>::getSectionAlignment(DataRefImpl Sec) const {
    676   return getSection(Sec)->sh_addralign;
    677 }
    678 
    679 template <class ELFT>
    680 bool ELFObjectFile<ELFT>::isSectionCompressed(DataRefImpl Sec) const {
    681   return getSection(Sec)->sh_flags & ELF::SHF_COMPRESSED;
    682 }
    683 
    684 template <class ELFT>
    685 bool ELFObjectFile<ELFT>::isSectionText(DataRefImpl Sec) const {
    686   return getSection(Sec)->sh_flags & ELF::SHF_EXECINSTR;
    687 }
    688 
    689 template <class ELFT>
    690 bool ELFObjectFile<ELFT>::isSectionData(DataRefImpl Sec) const {
    691   const Elf_Shdr *EShdr = getSection(Sec);
    692   return EShdr->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE) &&
    693          EShdr->sh_type == ELF::SHT_PROGBITS;
    694 }
    695 
    696 template <class ELFT>
    697 bool ELFObjectFile<ELFT>::isSectionBSS(DataRefImpl Sec) const {
    698   const Elf_Shdr *EShdr = getSection(Sec);
    699   return EShdr->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE) &&
    700          EShdr->sh_type == ELF::SHT_NOBITS;
    701 }
    702 
    703 template <class ELFT>
    704 bool ELFObjectFile<ELFT>::isSectionVirtual(DataRefImpl Sec) const {
    705   return getSection(Sec)->sh_type == ELF::SHT_NOBITS;
    706 }
    707 
    708 template <class ELFT>
    709 relocation_iterator
    710 ELFObjectFile<ELFT>::section_rel_begin(DataRefImpl Sec) const {
    711   DataRefImpl RelData;
    712   auto SectionsOrErr = EF.sections();
    713   if (!SectionsOrErr)
    714     return relocation_iterator(RelocationRef());
    715   uintptr_t SHT = reinterpret_cast<uintptr_t>((*SectionsOrErr).begin());
    716   RelData.d.a = (Sec.p - SHT) / EF.getHeader()->e_shentsize;
    717   RelData.d.b = 0;
    718   return relocation_iterator(RelocationRef(RelData, this));
    719 }
    720 
    721 template <class ELFT>
    722 relocation_iterator
    723 ELFObjectFile<ELFT>::section_rel_end(DataRefImpl Sec) const {
    724   const Elf_Shdr *S = reinterpret_cast<const Elf_Shdr *>(Sec.p);
    725   relocation_iterator Begin = section_rel_begin(Sec);
    726   if (S->sh_type != ELF::SHT_RELA && S->sh_type != ELF::SHT_REL)
    727     return Begin;
    728   DataRefImpl RelData = Begin->getRawDataRefImpl();
    729   const Elf_Shdr *RelSec = getRelSection(RelData);
    730 
    731   // Error check sh_link here so that getRelocationSymbol can just use it.
    732   auto SymSecOrErr = EF.getSection(RelSec->sh_link);
    733   if (!SymSecOrErr)
    734     report_fatal_error(errorToErrorCode(SymSecOrErr.takeError()).message());
    735 
    736   RelData.d.b += S->sh_size / S->sh_entsize;
    737   return relocation_iterator(RelocationRef(RelData, this));
    738 }
    739 
    740 template <class ELFT>
    741 section_iterator
    742 ELFObjectFile<ELFT>::getRelocatedSection(DataRefImpl Sec) const {
    743   if (EF.getHeader()->e_type != ELF::ET_REL)
    744     return section_end();
    745 
    746   const Elf_Shdr *EShdr = getSection(Sec);
    747   uintX_t Type = EShdr->sh_type;
    748   if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
    749     return section_end();
    750 
    751   auto R = EF.getSection(EShdr->sh_info);
    752   if (!R)
    753     report_fatal_error(errorToErrorCode(R.takeError()).message());
    754   return section_iterator(SectionRef(toDRI(*R), this));
    755 }
    756 
    757 // Relocations
    758 template <class ELFT>
    759 void ELFObjectFile<ELFT>::moveRelocationNext(DataRefImpl &Rel) const {
    760   ++Rel.d.b;
    761 }
    762 
    763 template <class ELFT>
    764 symbol_iterator
    765 ELFObjectFile<ELFT>::getRelocationSymbol(DataRefImpl Rel) const {
    766   uint32_t symbolIdx;
    767   const Elf_Shdr *sec = getRelSection(Rel);
    768   if (sec->sh_type == ELF::SHT_REL)
    769     symbolIdx = getRel(Rel)->getSymbol(EF.isMips64EL());
    770   else
    771     symbolIdx = getRela(Rel)->getSymbol(EF.isMips64EL());
    772   if (!symbolIdx)
    773     return symbol_end();
    774 
    775   // FIXME: error check symbolIdx
    776   DataRefImpl SymbolData;
    777   SymbolData.d.a = sec->sh_link;
    778   SymbolData.d.b = symbolIdx;
    779   return symbol_iterator(SymbolRef(SymbolData, this));
    780 }
    781 
    782 template <class ELFT>
    783 uint64_t ELFObjectFile<ELFT>::getRelocationOffset(DataRefImpl Rel) const {
    784   assert(EF.getHeader()->e_type == ELF::ET_REL &&
    785          "Only relocatable object files have relocation offsets");
    786   const Elf_Shdr *sec = getRelSection(Rel);
    787   if (sec->sh_type == ELF::SHT_REL)
    788     return getRel(Rel)->r_offset;
    789 
    790   return getRela(Rel)->r_offset;
    791 }
    792 
    793 template <class ELFT>
    794 uint64_t ELFObjectFile<ELFT>::getRelocationType(DataRefImpl Rel) const {
    795   const Elf_Shdr *sec = getRelSection(Rel);
    796   if (sec->sh_type == ELF::SHT_REL)
    797     return getRel(Rel)->getType(EF.isMips64EL());
    798   else
    799     return getRela(Rel)->getType(EF.isMips64EL());
    800 }
    801 
    802 template <class ELFT>
    803 StringRef ELFObjectFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
    804   return getELFRelocationTypeName(EF.getHeader()->e_machine, Type);
    805 }
    806 
    807 template <class ELFT>
    808 void ELFObjectFile<ELFT>::getRelocationTypeName(
    809     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
    810   uint32_t type = getRelocationType(Rel);
    811   EF.getRelocationTypeName(type, Result);
    812 }
    813 
    814 template <class ELFT>
    815 ErrorOr<int64_t>
    816 ELFObjectFile<ELFT>::getRelocationAddend(DataRefImpl Rel) const {
    817   if (getRelSection(Rel)->sh_type != ELF::SHT_RELA)
    818     return object_error::parse_failed;
    819   return (int64_t)getRela(Rel)->r_addend;
    820 }
    821 
    822 template <class ELFT>
    823 const typename ELFObjectFile<ELFT>::Elf_Rel *
    824 ELFObjectFile<ELFT>::getRel(DataRefImpl Rel) const {
    825   assert(getRelSection(Rel)->sh_type == ELF::SHT_REL);
    826   auto Ret = EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
    827   if (!Ret)
    828     report_fatal_error(errorToErrorCode(Ret.takeError()).message());
    829   return *Ret;
    830 }
    831 
    832 template <class ELFT>
    833 const typename ELFObjectFile<ELFT>::Elf_Rela *
    834 ELFObjectFile<ELFT>::getRela(DataRefImpl Rela) const {
    835   assert(getRelSection(Rela)->sh_type == ELF::SHT_RELA);
    836   auto Ret = EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
    837   if (!Ret)
    838     report_fatal_error(errorToErrorCode(Ret.takeError()).message());
    839   return *Ret;
    840 }
    841 
    842 template <class ELFT>
    843 ELFObjectFile<ELFT>::ELFObjectFile(MemoryBufferRef Object, std::error_code &EC)
    844     : ELFObjectFileBase(
    845           getELFType(ELFT::TargetEndianness == support::little, ELFT::Is64Bits),
    846           Object),
    847       EF(Data.getBuffer()) {
    848   auto SectionsOrErr = EF.sections();
    849   if (!SectionsOrErr) {
    850     EC = errorToErrorCode(SectionsOrErr.takeError());
    851     return;
    852   }
    853   for (const Elf_Shdr &Sec : *SectionsOrErr) {
    854     switch (Sec.sh_type) {
    855     case ELF::SHT_DYNSYM: {
    856       if (DotDynSymSec) {
    857         // More than one .dynsym!
    858         EC = object_error::parse_failed;
    859         return;
    860       }
    861       DotDynSymSec = &Sec;
    862       break;
    863     }
    864     case ELF::SHT_SYMTAB: {
    865       if (DotSymtabSec) {
    866         // More than one .dynsym!
    867         EC = object_error::parse_failed;
    868         return;
    869       }
    870       DotSymtabSec = &Sec;
    871       break;
    872     }
    873     case ELF::SHT_SYMTAB_SHNDX: {
    874       auto TableOrErr = EF.getSHNDXTable(Sec);
    875       if (!TableOrErr) {
    876         EC = errorToErrorCode(TableOrErr.takeError());
    877         return;
    878       }
    879       ShndxTable = *TableOrErr;
    880       break;
    881     }
    882     }
    883   }
    884 }
    885 
    886 template <class ELFT>
    887 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_begin() const {
    888   DataRefImpl Sym = toDRI(DotSymtabSec, 0);
    889   return basic_symbol_iterator(SymbolRef(Sym, this));
    890 }
    891 
    892 template <class ELFT>
    893 basic_symbol_iterator ELFObjectFile<ELFT>::symbol_end() const {
    894   const Elf_Shdr *SymTab = DotSymtabSec;
    895   if (!SymTab)
    896     return symbol_begin();
    897   DataRefImpl Sym = toDRI(SymTab, SymTab->sh_size / sizeof(Elf_Sym));
    898   return basic_symbol_iterator(SymbolRef(Sym, this));
    899 }
    900 
    901 template <class ELFT>
    902 elf_symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_begin() const {
    903   DataRefImpl Sym = toDRI(DotDynSymSec, 0);
    904   return symbol_iterator(SymbolRef(Sym, this));
    905 }
    906 
    907 template <class ELFT>
    908 elf_symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_end() const {
    909   const Elf_Shdr *SymTab = DotDynSymSec;
    910   if (!SymTab)
    911     return dynamic_symbol_begin();
    912   DataRefImpl Sym = toDRI(SymTab, SymTab->sh_size / sizeof(Elf_Sym));
    913   return basic_symbol_iterator(SymbolRef(Sym, this));
    914 }
    915 
    916 template <class ELFT>
    917 section_iterator ELFObjectFile<ELFT>::section_begin() const {
    918   auto SectionsOrErr = EF.sections();
    919   if (!SectionsOrErr)
    920     return section_iterator(SectionRef());
    921   return section_iterator(SectionRef(toDRI((*SectionsOrErr).begin()), this));
    922 }
    923 
    924 template <class ELFT>
    925 section_iterator ELFObjectFile<ELFT>::section_end() const {
    926   auto SectionsOrErr = EF.sections();
    927   if (!SectionsOrErr)
    928     return section_iterator(SectionRef());
    929   return section_iterator(SectionRef(toDRI((*SectionsOrErr).end()), this));
    930 }
    931 
    932 template <class ELFT>
    933 uint8_t ELFObjectFile<ELFT>::getBytesInAddress() const {
    934   return ELFT::Is64Bits ? 8 : 4;
    935 }
    936 
    937 template <class ELFT>
    938 StringRef ELFObjectFile<ELFT>::getFileFormatName() const {
    939   bool IsLittleEndian = ELFT::TargetEndianness == support::little;
    940   switch (EF.getHeader()->e_ident[ELF::EI_CLASS]) {
    941   case ELF::ELFCLASS32:
    942     switch (EF.getHeader()->e_machine) {
    943     case ELF::EM_386:
    944       return "ELF32-i386";
    945     case ELF::EM_IAMCU:
    946       return "ELF32-iamcu";
    947     case ELF::EM_X86_64:
    948       return "ELF32-x86-64";
    949     case ELF::EM_ARM:
    950       return (IsLittleEndian ? "ELF32-arm-little" : "ELF32-arm-big");
    951     case ELF::EM_AVR:
    952       return "ELF32-avr";
    953     case ELF::EM_HEXAGON:
    954       return "ELF32-hexagon";
    955     case ELF::EM_LANAI:
    956       return "ELF32-lanai";
    957     case ELF::EM_MIPS:
    958       return "ELF32-mips";
    959     case ELF::EM_PPC:
    960       return "ELF32-ppc";
    961     case ELF::EM_RISCV:
    962       return "ELF32-riscv";
    963     case ELF::EM_SPARC:
    964     case ELF::EM_SPARC32PLUS:
    965       return "ELF32-sparc";
    966     case ELF::EM_WEBASSEMBLY:
    967       return "ELF32-wasm";
    968     case ELF::EM_AMDGPU:
    969       return "ELF32-amdgpu";
    970     default:
    971       return "ELF32-unknown";
    972     }
    973   case ELF::ELFCLASS64:
    974     switch (EF.getHeader()->e_machine) {
    975     case ELF::EM_386:
    976       return "ELF64-i386";
    977     case ELF::EM_X86_64:
    978       return "ELF64-x86-64";
    979     case ELF::EM_AARCH64:
    980       return (IsLittleEndian ? "ELF64-aarch64-little" : "ELF64-aarch64-big");
    981     case ELF::EM_PPC64:
    982       return "ELF64-ppc64";
    983     case ELF::EM_RISCV:
    984       return "ELF64-riscv";
    985     case ELF::EM_S390:
    986       return "ELF64-s390";
    987     case ELF::EM_SPARCV9:
    988       return "ELF64-sparc";
    989     case ELF::EM_MIPS:
    990       return "ELF64-mips";
    991     case ELF::EM_WEBASSEMBLY:
    992       return "ELF64-wasm";
    993     case ELF::EM_AMDGPU:
    994       return (EF.getHeader()->e_ident[ELF::EI_OSABI] == ELF::ELFOSABI_AMDGPU_HSA
    995               && IsLittleEndian) ?
    996              "ELF64-amdgpu-hsacobj" : "ELF64-amdgpu";
    997     case ELF::EM_BPF:
    998       return "ELF64-BPF";
    999     default:
   1000       return "ELF64-unknown";
   1001     }
   1002   default:
   1003     // FIXME: Proper error handling.
   1004     report_fatal_error("Invalid ELFCLASS!");
   1005   }
   1006 }
   1007 
   1008 template <class ELFT>
   1009 unsigned ELFObjectFile<ELFT>::getArch() const {
   1010   bool IsLittleEndian = ELFT::TargetEndianness == support::little;
   1011   switch (EF.getHeader()->e_machine) {
   1012   case ELF::EM_386:
   1013   case ELF::EM_IAMCU:
   1014     return Triple::x86;
   1015   case ELF::EM_X86_64:
   1016     return Triple::x86_64;
   1017   case ELF::EM_AARCH64:
   1018     return IsLittleEndian ? Triple::aarch64 : Triple::aarch64_be;
   1019   case ELF::EM_ARM:
   1020     return Triple::arm;
   1021   case ELF::EM_AVR:
   1022     return Triple::avr;
   1023   case ELF::EM_HEXAGON:
   1024     return Triple::hexagon;
   1025   case ELF::EM_LANAI:
   1026     return Triple::lanai;
   1027   case ELF::EM_MIPS:
   1028     switch (EF.getHeader()->e_ident[ELF::EI_CLASS]) {
   1029     case ELF::ELFCLASS32:
   1030       return IsLittleEndian ? Triple::mipsel : Triple::mips;
   1031     case ELF::ELFCLASS64:
   1032       return IsLittleEndian ? Triple::mips64el : Triple::mips64;
   1033     default:
   1034       report_fatal_error("Invalid ELFCLASS!");
   1035     }
   1036   case ELF::EM_PPC:
   1037     return Triple::ppc;
   1038   case ELF::EM_PPC64:
   1039     return IsLittleEndian ? Triple::ppc64le : Triple::ppc64;
   1040   case ELF::EM_RISCV:
   1041     switch (EF.getHeader()->e_ident[ELF::EI_CLASS]) {
   1042     case ELF::ELFCLASS32:
   1043       return Triple::riscv32;
   1044     case ELF::ELFCLASS64:
   1045       return Triple::riscv64;
   1046     default:
   1047       report_fatal_error("Invalid ELFCLASS!");
   1048     }
   1049   case ELF::EM_S390:
   1050     return Triple::systemz;
   1051 
   1052   case ELF::EM_SPARC:
   1053   case ELF::EM_SPARC32PLUS:
   1054     return IsLittleEndian ? Triple::sparcel : Triple::sparc;
   1055   case ELF::EM_SPARCV9:
   1056     return Triple::sparcv9;
   1057   case ELF::EM_WEBASSEMBLY:
   1058     switch (EF.getHeader()->e_ident[ELF::EI_CLASS]) {
   1059     case ELF::ELFCLASS32: return Triple::wasm32;
   1060     case ELF::ELFCLASS64: return Triple::wasm64;
   1061     default: return Triple::UnknownArch;
   1062     }
   1063 
   1064   case ELF::EM_AMDGPU:
   1065     return (EF.getHeader()->e_ident[ELF::EI_CLASS] == ELF::ELFCLASS64
   1066          && EF.getHeader()->e_ident[ELF::EI_OSABI] == ELF::ELFOSABI_AMDGPU_HSA
   1067          && IsLittleEndian) ?
   1068       Triple::amdgcn : Triple::UnknownArch;
   1069 
   1070   case ELF::EM_BPF:
   1071     return IsLittleEndian ? Triple::bpfel : Triple::bpfeb;
   1072 
   1073   default:
   1074     return Triple::UnknownArch;
   1075   }
   1076 }
   1077 
   1078 template <class ELFT>
   1079 ELFObjectFileBase::elf_symbol_iterator_range
   1080 ELFObjectFile<ELFT>::getDynamicSymbolIterators() const {
   1081   return make_range(dynamic_symbol_begin(), dynamic_symbol_end());
   1082 }
   1083 
   1084 template <class ELFT> bool ELFObjectFile<ELFT>::isRelocatableObject() const {
   1085   return EF.getHeader()->e_type == ELF::ET_REL;
   1086 }
   1087 
   1088 } // end namespace object
   1089 } // end namespace llvm
   1090 
   1091 #endif // LLVM_OBJECT_ELFOBJECTFILE_H
   1092