Home | History | Annotate | Line # | Download | only in Object
      1 //===- ELF.h - ELF object file implementation -------------------*- C++ -*-===//
      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 // This file declares the ELFFile template class.
     10 //
     11 //===----------------------------------------------------------------------===//
     12 
     13 #ifndef LLVM_OBJECT_ELF_H
     14 #define LLVM_OBJECT_ELF_H
     15 
     16 #include "llvm/ADT/ArrayRef.h"
     17 #include "llvm/ADT/SmallVector.h"
     18 #include "llvm/ADT/StringRef.h"
     19 #include "llvm/BinaryFormat/ELF.h"
     20 #include "llvm/Object/ELFTypes.h"
     21 #include "llvm/Object/Error.h"
     22 #include "llvm/Support/Endian.h"
     23 #include "llvm/Support/Error.h"
     24 #include <cassert>
     25 #include <cstddef>
     26 #include <cstdint>
     27 #include <limits>
     28 #include <utility>
     29 
     30 namespace llvm {
     31 namespace object {
     32 
     33 struct VerdAux {
     34   unsigned Offset;
     35   std::string Name;
     36 };
     37 
     38 struct VerDef {
     39   unsigned Offset;
     40   unsigned Version;
     41   unsigned Flags;
     42   unsigned Ndx;
     43   unsigned Cnt;
     44   unsigned Hash;
     45   std::string Name;
     46   std::vector<VerdAux> AuxV;
     47 };
     48 
     49 struct VernAux {
     50   unsigned Hash;
     51   unsigned Flags;
     52   unsigned Other;
     53   unsigned Offset;
     54   std::string Name;
     55 };
     56 
     57 struct VerNeed {
     58   unsigned Version;
     59   unsigned Cnt;
     60   unsigned Offset;
     61   std::string File;
     62   std::vector<VernAux> AuxV;
     63 };
     64 
     65 struct VersionEntry {
     66   std::string Name;
     67   bool IsVerDef;
     68 };
     69 
     70 StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
     71 uint32_t getELFRelativeRelocationType(uint32_t Machine);
     72 StringRef getELFSectionTypeName(uint32_t Machine, uint32_t Type);
     73 
     74 // Subclasses of ELFFile may need this for template instantiation
     75 inline std::pair<unsigned char, unsigned char>
     76 getElfArchType(StringRef Object) {
     77   if (Object.size() < ELF::EI_NIDENT)
     78     return std::make_pair((uint8_t)ELF::ELFCLASSNONE,
     79                           (uint8_t)ELF::ELFDATANONE);
     80   return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
     81                         (uint8_t)Object[ELF::EI_DATA]);
     82 }
     83 
     84 static inline Error createError(const Twine &Err) {
     85   return make_error<StringError>(Err, object_error::parse_failed);
     86 }
     87 
     88 enum PPCInstrMasks : uint64_t {
     89   PADDI_R12_NO_DISP = 0x0610000039800000,
     90   ADDIS_R12_TO_R2_NO_DISP = 0x3D820000,
     91   ADDI_R12_TO_R2_NO_DISP = 0x39820000,
     92   ADDI_R12_TO_R12_NO_DISP = 0x398C0000,
     93   PLD_R12_NO_DISP = 0x04100000E5800000,
     94   MTCTR_R12 = 0x7D8903A6,
     95   BCTR = 0x4E800420,
     96 };
     97 
     98 template <class ELFT> class ELFFile;
     99 
    100 template <class T> struct DataRegion {
    101   // This constructor is used when we know the start and the size of a data
    102   // region. We assume that Arr does not go past the end of the file.
    103   DataRegion(ArrayRef<T> Arr) : First(Arr.data()), Size(Arr.size()) {}
    104 
    105   // Sometimes we only know the start of a data region. We still don't want to
    106   // read past the end of the file, so we provide the end of a buffer.
    107   DataRegion(const T *Data, const uint8_t *BufferEnd)
    108       : First(Data), BufEnd(BufferEnd) {}
    109 
    110   Expected<T> operator[](uint64_t N) {
    111     assert(Size || BufEnd);
    112     if (Size) {
    113       if (N >= *Size)
    114         return createError(
    115             "the index is greater than or equal to the number of entries (" +
    116             Twine(*Size) + ")");
    117     } else {
    118       const uint8_t *EntryStart = (const uint8_t *)First + N * sizeof(T);
    119       if (EntryStart + sizeof(T) > BufEnd)
    120         return createError("can't read past the end of the file");
    121     }
    122     return *(First + N);
    123   }
    124 
    125   const T *First;
    126   Optional<uint64_t> Size = None;
    127   const uint8_t *BufEnd = nullptr;
    128 };
    129 
    130 template <class ELFT>
    131 std::string getSecIndexForError(const ELFFile<ELFT> &Obj,
    132                                 const typename ELFT::Shdr &Sec) {
    133   auto TableOrErr = Obj.sections();
    134   if (TableOrErr)
    135     return "[index " + std::to_string(&Sec - &TableOrErr->front()) + "]";
    136   // To make this helper be more convenient for error reporting purposes we
    137   // drop the error. But really it should never be triggered. Before this point,
    138   // our code should have called 'sections()' and reported a proper error on
    139   // failure.
    140   llvm::consumeError(TableOrErr.takeError());
    141   return "[unknown index]";
    142 }
    143 
    144 template <class ELFT>
    145 static std::string describe(const ELFFile<ELFT> &Obj,
    146                             const typename ELFT::Shdr &Sec) {
    147   unsigned SecNdx = &Sec - &cantFail(Obj.sections()).front();
    148   return (object::getELFSectionTypeName(Obj.getHeader().e_machine,
    149                                         Sec.sh_type) +
    150           " section with index " + Twine(SecNdx))
    151       .str();
    152 }
    153 
    154 template <class ELFT>
    155 std::string getPhdrIndexForError(const ELFFile<ELFT> &Obj,
    156                                  const typename ELFT::Phdr &Phdr) {
    157   auto Headers = Obj.program_headers();
    158   if (Headers)
    159     return ("[index " + Twine(&Phdr - &Headers->front()) + "]").str();
    160   // See comment in the getSecIndexForError() above.
    161   llvm::consumeError(Headers.takeError());
    162   return "[unknown index]";
    163 }
    164 
    165 static inline Error defaultWarningHandler(const Twine &Msg) {
    166   return createError(Msg);
    167 }
    168 
    169 template <class ELFT>
    170 class ELFFile {
    171 public:
    172   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
    173 
    174   // This is a callback that can be passed to a number of functions.
    175   // It can be used to ignore non-critical errors (warnings), which is
    176   // useful for dumpers, like llvm-readobj.
    177   // It accepts a warning message string and returns a success
    178   // when the warning should be ignored or an error otherwise.
    179   using WarningHandler = llvm::function_ref<Error(const Twine &Msg)>;
    180 
    181   const uint8_t *base() const { return Buf.bytes_begin(); }
    182   const uint8_t *end() const { return base() + getBufSize(); }
    183 
    184   size_t getBufSize() const { return Buf.size(); }
    185 
    186 private:
    187   StringRef Buf;
    188 
    189   ELFFile(StringRef Object);
    190 
    191 public:
    192   const Elf_Ehdr &getHeader() const {
    193     return *reinterpret_cast<const Elf_Ehdr *>(base());
    194   }
    195 
    196   template <typename T>
    197   Expected<const T *> getEntry(uint32_t Section, uint32_t Entry) const;
    198   template <typename T>
    199   Expected<const T *> getEntry(const Elf_Shdr &Section, uint32_t Entry) const;
    200 
    201   Expected<std::vector<VerDef>>
    202   getVersionDefinitions(const Elf_Shdr &Sec) const;
    203   Expected<std::vector<VerNeed>> getVersionDependencies(
    204       const Elf_Shdr &Sec,
    205       WarningHandler WarnHandler = &defaultWarningHandler) const;
    206   Expected<StringRef>
    207   getSymbolVersionByIndex(uint32_t SymbolVersionIndex, bool &IsDefault,
    208                           SmallVector<Optional<VersionEntry>, 0> &VersionMap,
    209                           Optional<bool> IsSymHidden) const;
    210 
    211   Expected<StringRef>
    212   getStringTable(const Elf_Shdr &Section,
    213                  WarningHandler WarnHandler = &defaultWarningHandler) const;
    214   Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
    215   Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section,
    216                                               Elf_Shdr_Range Sections) const;
    217   Expected<StringRef> getLinkAsStrtab(const typename ELFT::Shdr &Sec) const;
    218 
    219   Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section) const;
    220   Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section,
    221                                              Elf_Shdr_Range Sections) const;
    222 
    223   Expected<uint64_t> getDynSymtabSize() const;
    224 
    225   StringRef getRelocationTypeName(uint32_t Type) const;
    226   void getRelocationTypeName(uint32_t Type,
    227                              SmallVectorImpl<char> &Result) const;
    228   uint32_t getRelativeRelocationType() const;
    229 
    230   std::string getDynamicTagAsString(unsigned Arch, uint64_t Type) const;
    231   std::string getDynamicTagAsString(uint64_t Type) const;
    232 
    233   /// Get the symbol for a given relocation.
    234   Expected<const Elf_Sym *> getRelocationSymbol(const Elf_Rel &Rel,
    235                                                 const Elf_Shdr *SymTab) const;
    236 
    237   Expected<SmallVector<Optional<VersionEntry>, 0>>
    238   loadVersionMap(const Elf_Shdr *VerNeedSec, const Elf_Shdr *VerDefSec) const;
    239 
    240   static Expected<ELFFile> create(StringRef Object);
    241 
    242   bool isLE() const {
    243     return getHeader().getDataEncoding() == ELF::ELFDATA2LSB;
    244   }
    245 
    246   bool isMipsELF64() const {
    247     return getHeader().e_machine == ELF::EM_MIPS &&
    248            getHeader().getFileClass() == ELF::ELFCLASS64;
    249   }
    250 
    251   bool isMips64EL() const { return isMipsELF64() && isLE(); }
    252 
    253   Expected<Elf_Shdr_Range> sections() const;
    254 
    255   Expected<Elf_Dyn_Range> dynamicEntries() const;
    256 
    257   Expected<const uint8_t *>
    258   toMappedAddr(uint64_t VAddr,
    259                WarningHandler WarnHandler = &defaultWarningHandler) const;
    260 
    261   Expected<Elf_Sym_Range> symbols(const Elf_Shdr *Sec) const {
    262     if (!Sec)
    263       return makeArrayRef<Elf_Sym>(nullptr, nullptr);
    264     return getSectionContentsAsArray<Elf_Sym>(*Sec);
    265   }
    266 
    267   Expected<Elf_Rela_Range> relas(const Elf_Shdr &Sec) const {
    268     return getSectionContentsAsArray<Elf_Rela>(Sec);
    269   }
    270 
    271   Expected<Elf_Rel_Range> rels(const Elf_Shdr &Sec) const {
    272     return getSectionContentsAsArray<Elf_Rel>(Sec);
    273   }
    274 
    275   Expected<Elf_Relr_Range> relrs(const Elf_Shdr &Sec) const {
    276     return getSectionContentsAsArray<Elf_Relr>(Sec);
    277   }
    278 
    279   std::vector<Elf_Rel> decode_relrs(Elf_Relr_Range relrs) const;
    280 
    281   Expected<std::vector<Elf_Rela>> android_relas(const Elf_Shdr &Sec) const;
    282 
    283   /// Iterate over program header table.
    284   Expected<Elf_Phdr_Range> program_headers() const {
    285     if (getHeader().e_phnum && getHeader().e_phentsize != sizeof(Elf_Phdr))
    286       return createError("invalid e_phentsize: " +
    287                          Twine(getHeader().e_phentsize));
    288 
    289     uint64_t HeadersSize =
    290         (uint64_t)getHeader().e_phnum * getHeader().e_phentsize;
    291     uint64_t PhOff = getHeader().e_phoff;
    292     if (PhOff + HeadersSize < PhOff || PhOff + HeadersSize > getBufSize())
    293       return createError("program headers are longer than binary of size " +
    294                          Twine(getBufSize()) + ": e_phoff = 0x" +
    295                          Twine::utohexstr(getHeader().e_phoff) +
    296                          ", e_phnum = " + Twine(getHeader().e_phnum) +
    297                          ", e_phentsize = " + Twine(getHeader().e_phentsize));
    298 
    299     auto *Begin = reinterpret_cast<const Elf_Phdr *>(base() + PhOff);
    300     return makeArrayRef(Begin, Begin + getHeader().e_phnum);
    301   }
    302 
    303   /// Get an iterator over notes in a program header.
    304   ///
    305   /// The program header must be of type \c PT_NOTE.
    306   ///
    307   /// \param Phdr the program header to iterate over.
    308   /// \param Err [out] an error to support fallible iteration, which should
    309   ///  be checked after iteration ends.
    310   Elf_Note_Iterator notes_begin(const Elf_Phdr &Phdr, Error &Err) const {
    311     assert(Phdr.p_type == ELF::PT_NOTE && "Phdr is not of type PT_NOTE");
    312     ErrorAsOutParameter ErrAsOutParam(&Err);
    313     if (Phdr.p_offset + Phdr.p_filesz > getBufSize()) {
    314       Err =
    315           createError("invalid offset (0x" + Twine::utohexstr(Phdr.p_offset) +
    316                       ") or size (0x" + Twine::utohexstr(Phdr.p_filesz) + ")");
    317       return Elf_Note_Iterator(Err);
    318     }
    319     return Elf_Note_Iterator(base() + Phdr.p_offset, Phdr.p_filesz, Err);
    320   }
    321 
    322   /// Get an iterator over notes in a section.
    323   ///
    324   /// The section must be of type \c SHT_NOTE.
    325   ///
    326   /// \param Shdr the section to iterate over.
    327   /// \param Err [out] an error to support fallible iteration, which should
    328   ///  be checked after iteration ends.
    329   Elf_Note_Iterator notes_begin(const Elf_Shdr &Shdr, Error &Err) const {
    330     assert(Shdr.sh_type == ELF::SHT_NOTE && "Shdr is not of type SHT_NOTE");
    331     ErrorAsOutParameter ErrAsOutParam(&Err);
    332     if (Shdr.sh_offset + Shdr.sh_size > getBufSize()) {
    333       Err =
    334           createError("invalid offset (0x" + Twine::utohexstr(Shdr.sh_offset) +
    335                       ") or size (0x" + Twine::utohexstr(Shdr.sh_size) + ")");
    336       return Elf_Note_Iterator(Err);
    337     }
    338     return Elf_Note_Iterator(base() + Shdr.sh_offset, Shdr.sh_size, Err);
    339   }
    340 
    341   /// Get the end iterator for notes.
    342   Elf_Note_Iterator notes_end() const {
    343     return Elf_Note_Iterator();
    344   }
    345 
    346   /// Get an iterator range over notes of a program header.
    347   ///
    348   /// The program header must be of type \c PT_NOTE.
    349   ///
    350   /// \param Phdr the program header to iterate over.
    351   /// \param Err [out] an error to support fallible iteration, which should
    352   ///  be checked after iteration ends.
    353   iterator_range<Elf_Note_Iterator> notes(const Elf_Phdr &Phdr,
    354                                           Error &Err) const {
    355     return make_range(notes_begin(Phdr, Err), notes_end());
    356   }
    357 
    358   /// Get an iterator range over notes of a section.
    359   ///
    360   /// The section must be of type \c SHT_NOTE.
    361   ///
    362   /// \param Shdr the section to iterate over.
    363   /// \param Err [out] an error to support fallible iteration, which should
    364   ///  be checked after iteration ends.
    365   iterator_range<Elf_Note_Iterator> notes(const Elf_Shdr &Shdr,
    366                                           Error &Err) const {
    367     return make_range(notes_begin(Shdr, Err), notes_end());
    368   }
    369 
    370   Expected<StringRef> getSectionStringTable(
    371       Elf_Shdr_Range Sections,
    372       WarningHandler WarnHandler = &defaultWarningHandler) const;
    373   Expected<uint32_t> getSectionIndex(const Elf_Sym &Sym, Elf_Sym_Range Syms,
    374                                      DataRegion<Elf_Word> ShndxTable) const;
    375   Expected<const Elf_Shdr *> getSection(const Elf_Sym &Sym,
    376                                         const Elf_Shdr *SymTab,
    377                                         DataRegion<Elf_Word> ShndxTable) const;
    378   Expected<const Elf_Shdr *> getSection(const Elf_Sym &Sym,
    379                                         Elf_Sym_Range Symtab,
    380                                         DataRegion<Elf_Word> ShndxTable) const;
    381   Expected<const Elf_Shdr *> getSection(uint32_t Index) const;
    382 
    383   Expected<const Elf_Sym *> getSymbol(const Elf_Shdr *Sec,
    384                                       uint32_t Index) const;
    385 
    386   Expected<StringRef>
    387   getSectionName(const Elf_Shdr &Section,
    388                  WarningHandler WarnHandler = &defaultWarningHandler) const;
    389   Expected<StringRef> getSectionName(const Elf_Shdr &Section,
    390                                      StringRef DotShstrtab) const;
    391   template <typename T>
    392   Expected<ArrayRef<T>> getSectionContentsAsArray(const Elf_Shdr &Sec) const;
    393   Expected<ArrayRef<uint8_t>> getSectionContents(const Elf_Shdr &Sec) const;
    394   Expected<ArrayRef<uint8_t>> getSegmentContents(const Elf_Phdr &Phdr) const;
    395   Expected<std::vector<Elf_BBAddrMap>>
    396   decodeBBAddrMap(const Elf_Shdr &Sec) const;
    397 };
    398 
    399 using ELF32LEFile = ELFFile<ELF32LE>;
    400 using ELF64LEFile = ELFFile<ELF64LE>;
    401 using ELF32BEFile = ELFFile<ELF32BE>;
    402 using ELF64BEFile = ELFFile<ELF64BE>;
    403 
    404 template <class ELFT>
    405 inline Expected<const typename ELFT::Shdr *>
    406 getSection(typename ELFT::ShdrRange Sections, uint32_t Index) {
    407   if (Index >= Sections.size())
    408     return createError("invalid section index: " + Twine(Index));
    409   return &Sections[Index];
    410 }
    411 
    412 template <class ELFT>
    413 inline Expected<uint32_t>
    414 getExtendedSymbolTableIndex(const typename ELFT::Sym &Sym, unsigned SymIndex,
    415                             DataRegion<typename ELFT::Word> ShndxTable) {
    416   assert(Sym.st_shndx == ELF::SHN_XINDEX);
    417   if (!ShndxTable.First)
    418     return createError(
    419         "found an extended symbol index (" + Twine(SymIndex) +
    420         "), but unable to locate the extended symbol index table");
    421 
    422   Expected<typename ELFT::Word> TableOrErr = ShndxTable[SymIndex];
    423   if (!TableOrErr)
    424     return createError("unable to read an extended symbol table at index " +
    425                        Twine(SymIndex) + ": " +
    426                        toString(TableOrErr.takeError()));
    427   return *TableOrErr;
    428 }
    429 
    430 template <class ELFT>
    431 Expected<uint32_t>
    432 ELFFile<ELFT>::getSectionIndex(const Elf_Sym &Sym, Elf_Sym_Range Syms,
    433                                DataRegion<Elf_Word> ShndxTable) const {
    434   uint32_t Index = Sym.st_shndx;
    435   if (Index == ELF::SHN_XINDEX) {
    436     Expected<uint32_t> ErrorOrIndex =
    437         getExtendedSymbolTableIndex<ELFT>(Sym, &Sym - Syms.begin(), ShndxTable);
    438     if (!ErrorOrIndex)
    439       return ErrorOrIndex.takeError();
    440     return *ErrorOrIndex;
    441   }
    442   if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
    443     return 0;
    444   return Index;
    445 }
    446 
    447 template <class ELFT>
    448 Expected<const typename ELFT::Shdr *>
    449 ELFFile<ELFT>::getSection(const Elf_Sym &Sym, const Elf_Shdr *SymTab,
    450                           DataRegion<Elf_Word> ShndxTable) const {
    451   auto SymsOrErr = symbols(SymTab);
    452   if (!SymsOrErr)
    453     return SymsOrErr.takeError();
    454   return getSection(Sym, *SymsOrErr, ShndxTable);
    455 }
    456 
    457 template <class ELFT>
    458 Expected<const typename ELFT::Shdr *>
    459 ELFFile<ELFT>::getSection(const Elf_Sym &Sym, Elf_Sym_Range Symbols,
    460                           DataRegion<Elf_Word> ShndxTable) const {
    461   auto IndexOrErr = getSectionIndex(Sym, Symbols, ShndxTable);
    462   if (!IndexOrErr)
    463     return IndexOrErr.takeError();
    464   uint32_t Index = *IndexOrErr;
    465   if (Index == 0)
    466     return nullptr;
    467   return getSection(Index);
    468 }
    469 
    470 template <class ELFT>
    471 Expected<const typename ELFT::Sym *>
    472 ELFFile<ELFT>::getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
    473   auto SymsOrErr = symbols(Sec);
    474   if (!SymsOrErr)
    475     return SymsOrErr.takeError();
    476 
    477   Elf_Sym_Range Symbols = *SymsOrErr;
    478   if (Index >= Symbols.size())
    479     return createError("unable to get symbol from section " +
    480                        getSecIndexForError(*this, *Sec) +
    481                        ": invalid symbol index (" + Twine(Index) + ")");
    482   return &Symbols[Index];
    483 }
    484 
    485 template <class ELFT>
    486 template <typename T>
    487 Expected<ArrayRef<T>>
    488 ELFFile<ELFT>::getSectionContentsAsArray(const Elf_Shdr &Sec) const {
    489   if (Sec.sh_entsize != sizeof(T) && sizeof(T) != 1)
    490     return createError("section " + getSecIndexForError(*this, Sec) +
    491                        " has invalid sh_entsize: expected " + Twine(sizeof(T)) +
    492                        ", but got " + Twine(Sec.sh_entsize));
    493 
    494   uintX_t Offset = Sec.sh_offset;
    495   uintX_t Size = Sec.sh_size;
    496 
    497   if (Size % sizeof(T))
    498     return createError("section " + getSecIndexForError(*this, Sec) +
    499                        " has an invalid sh_size (" + Twine(Size) +
    500                        ") which is not a multiple of its sh_entsize (" +
    501                        Twine(Sec.sh_entsize) + ")");
    502   if (std::numeric_limits<uintX_t>::max() - Offset < Size)
    503     return createError("section " + getSecIndexForError(*this, Sec) +
    504                        " has a sh_offset (0x" + Twine::utohexstr(Offset) +
    505                        ") + sh_size (0x" + Twine::utohexstr(Size) +
    506                        ") that cannot be represented");
    507   if (Offset + Size > Buf.size())
    508     return createError("section " + getSecIndexForError(*this, Sec) +
    509                        " has a sh_offset (0x" + Twine::utohexstr(Offset) +
    510                        ") + sh_size (0x" + Twine::utohexstr(Size) +
    511                        ") that is greater than the file size (0x" +
    512                        Twine::utohexstr(Buf.size()) + ")");
    513 
    514   if (Offset % alignof(T))
    515     // TODO: this error is untested.
    516     return createError("unaligned data");
    517 
    518   const T *Start = reinterpret_cast<const T *>(base() + Offset);
    519   return makeArrayRef(Start, Size / sizeof(T));
    520 }
    521 
    522 template <class ELFT>
    523 Expected<ArrayRef<uint8_t>>
    524 ELFFile<ELFT>::getSegmentContents(const Elf_Phdr &Phdr) const {
    525   uintX_t Offset = Phdr.p_offset;
    526   uintX_t Size = Phdr.p_filesz;
    527 
    528   if (std::numeric_limits<uintX_t>::max() - Offset < Size)
    529     return createError("program header " + getPhdrIndexForError(*this, Phdr) +
    530                        " has a p_offset (0x" + Twine::utohexstr(Offset) +
    531                        ") + p_filesz (0x" + Twine::utohexstr(Size) +
    532                        ") that cannot be represented");
    533   if (Offset + Size > Buf.size())
    534     return createError("program header  " + getPhdrIndexForError(*this, Phdr) +
    535                        " has a p_offset (0x" + Twine::utohexstr(Offset) +
    536                        ") + p_filesz (0x" + Twine::utohexstr(Size) +
    537                        ") that is greater than the file size (0x" +
    538                        Twine::utohexstr(Buf.size()) + ")");
    539   return makeArrayRef(base() + Offset, Size);
    540 }
    541 
    542 template <class ELFT>
    543 Expected<ArrayRef<uint8_t>>
    544 ELFFile<ELFT>::getSectionContents(const Elf_Shdr &Sec) const {
    545   return getSectionContentsAsArray<uint8_t>(Sec);
    546 }
    547 
    548 template <class ELFT>
    549 StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
    550   return getELFRelocationTypeName(getHeader().e_machine, Type);
    551 }
    552 
    553 template <class ELFT>
    554 void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
    555                                           SmallVectorImpl<char> &Result) const {
    556   if (!isMipsELF64()) {
    557     StringRef Name = getRelocationTypeName(Type);
    558     Result.append(Name.begin(), Name.end());
    559   } else {
    560     // The Mips N64 ABI allows up to three operations to be specified per
    561     // relocation record. Unfortunately there's no easy way to test for the
    562     // presence of N64 ELFs as they have no special flag that identifies them
    563     // as being N64. We can safely assume at the moment that all Mips
    564     // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
    565     // information to disambiguate between old vs new ABIs.
    566     uint8_t Type1 = (Type >> 0) & 0xFF;
    567     uint8_t Type2 = (Type >> 8) & 0xFF;
    568     uint8_t Type3 = (Type >> 16) & 0xFF;
    569 
    570     // Concat all three relocation type names.
    571     StringRef Name = getRelocationTypeName(Type1);
    572     Result.append(Name.begin(), Name.end());
    573 
    574     Name = getRelocationTypeName(Type2);
    575     Result.append(1, '/');
    576     Result.append(Name.begin(), Name.end());
    577 
    578     Name = getRelocationTypeName(Type3);
    579     Result.append(1, '/');
    580     Result.append(Name.begin(), Name.end());
    581   }
    582 }
    583 
    584 template <class ELFT>
    585 uint32_t ELFFile<ELFT>::getRelativeRelocationType() const {
    586   return getELFRelativeRelocationType(getHeader().e_machine);
    587 }
    588 
    589 template <class ELFT>
    590 Expected<SmallVector<Optional<VersionEntry>, 0>>
    591 ELFFile<ELFT>::loadVersionMap(const Elf_Shdr *VerNeedSec,
    592                               const Elf_Shdr *VerDefSec) const {
    593   SmallVector<Optional<VersionEntry>, 0> VersionMap;
    594 
    595   // The first two version indexes are reserved.
    596   // Index 0 is VER_NDX_LOCAL, index 1 is VER_NDX_GLOBAL.
    597   VersionMap.push_back(VersionEntry());
    598   VersionMap.push_back(VersionEntry());
    599 
    600   auto InsertEntry = [&](unsigned N, StringRef Version, bool IsVerdef) {
    601     if (N >= VersionMap.size())
    602       VersionMap.resize(N + 1);
    603     VersionMap[N] = {std::string(Version), IsVerdef};
    604   };
    605 
    606   if (VerDefSec) {
    607     Expected<std::vector<VerDef>> Defs = getVersionDefinitions(*VerDefSec);
    608     if (!Defs)
    609       return Defs.takeError();
    610     for (const VerDef &Def : *Defs)
    611       InsertEntry(Def.Ndx & ELF::VERSYM_VERSION, Def.Name, true);
    612   }
    613 
    614   if (VerNeedSec) {
    615     Expected<std::vector<VerNeed>> Deps = getVersionDependencies(*VerNeedSec);
    616     if (!Deps)
    617       return Deps.takeError();
    618     for (const VerNeed &Dep : *Deps)
    619       for (const VernAux &Aux : Dep.AuxV)
    620         InsertEntry(Aux.Other & ELF::VERSYM_VERSION, Aux.Name, false);
    621   }
    622 
    623   return VersionMap;
    624 }
    625 
    626 template <class ELFT>
    627 Expected<const typename ELFT::Sym *>
    628 ELFFile<ELFT>::getRelocationSymbol(const Elf_Rel &Rel,
    629                                    const Elf_Shdr *SymTab) const {
    630   uint32_t Index = Rel.getSymbol(isMips64EL());
    631   if (Index == 0)
    632     return nullptr;
    633   return getEntry<Elf_Sym>(*SymTab, Index);
    634 }
    635 
    636 template <class ELFT>
    637 Expected<StringRef>
    638 ELFFile<ELFT>::getSectionStringTable(Elf_Shdr_Range Sections,
    639                                      WarningHandler WarnHandler) const {
    640   uint32_t Index = getHeader().e_shstrndx;
    641   if (Index == ELF::SHN_XINDEX) {
    642     // If the section name string table section index is greater than
    643     // or equal to SHN_LORESERVE, then the actual index of the section name
    644     // string table section is contained in the sh_link field of the section
    645     // header at index 0.
    646     if (Sections.empty())
    647       return createError(
    648           "e_shstrndx == SHN_XINDEX, but the section header table is empty");
    649 
    650     Index = Sections[0].sh_link;
    651   }
    652 
    653   if (!Index) // no section string table.
    654     return "";
    655   if (Index >= Sections.size())
    656     return createError("section header string table index " + Twine(Index) +
    657                        " does not exist");
    658   return getStringTable(Sections[Index], WarnHandler);
    659 }
    660 
    661 /// This function finds the number of dynamic symbols using a GNU hash table.
    662 ///
    663 /// @param Table The GNU hash table for .dynsym.
    664 template <class ELFT>
    665 static Expected<uint64_t>
    666 getDynSymtabSizeFromGnuHash(const typename ELFT::GnuHash &Table,
    667                             const void *BufEnd) {
    668   using Elf_Word = typename ELFT::Word;
    669   if (Table.nbuckets == 0)
    670     return Table.symndx + 1;
    671   uint64_t LastSymIdx = 0;
    672   // Find the index of the first symbol in the last chain.
    673   for (Elf_Word Val : Table.buckets())
    674     LastSymIdx = std::max(LastSymIdx, (uint64_t)Val);
    675   const Elf_Word *It =
    676       reinterpret_cast<const Elf_Word *>(Table.values(LastSymIdx).end());
    677   // Locate the end of the chain to find the last symbol index.
    678   while (It < BufEnd && (*It & 1) == 0) {
    679     ++LastSymIdx;
    680     ++It;
    681   }
    682   if (It >= BufEnd) {
    683     return createStringError(
    684         object_error::parse_failed,
    685         "no terminator found for GNU hash section before buffer end");
    686   }
    687   return LastSymIdx + 1;
    688 }
    689 
    690 /// This function determines the number of dynamic symbols. It reads section
    691 /// headers first. If section headers are not available, the number of
    692 /// symbols will be inferred by parsing dynamic hash tables.
    693 template <class ELFT>
    694 Expected<uint64_t> ELFFile<ELFT>::getDynSymtabSize() const {
    695   // Read .dynsym section header first if available.
    696   Expected<Elf_Shdr_Range> SectionsOrError = sections();
    697   if (!SectionsOrError)
    698     return SectionsOrError.takeError();
    699   for (const Elf_Shdr &Sec : *SectionsOrError) {
    700     if (Sec.sh_type == ELF::SHT_DYNSYM) {
    701       if (Sec.sh_size % Sec.sh_entsize != 0) {
    702         return createStringError(object_error::parse_failed,
    703                                  "SHT_DYNSYM section has sh_size (" +
    704                                      Twine(Sec.sh_size) + ") % sh_entsize (" +
    705                                      Twine(Sec.sh_entsize) + ") that is not 0");
    706       }
    707       return Sec.sh_size / Sec.sh_entsize;
    708     }
    709   }
    710 
    711   if (!SectionsOrError->empty()) {
    712     // Section headers are available but .dynsym header is not found.
    713     // Return 0 as .dynsym does not exist.
    714     return 0;
    715   }
    716 
    717   // Section headers do not exist. Falling back to infer
    718   // upper bound of .dynsym from .gnu.hash and .hash.
    719   Expected<Elf_Dyn_Range> DynTable = dynamicEntries();
    720   if (!DynTable)
    721     return DynTable.takeError();
    722   llvm::Optional<uint64_t> ElfHash;
    723   llvm::Optional<uint64_t> ElfGnuHash;
    724   for (const Elf_Dyn &Entry : *DynTable) {
    725     switch (Entry.d_tag) {
    726     case ELF::DT_HASH:
    727       ElfHash = Entry.d_un.d_ptr;
    728       break;
    729     case ELF::DT_GNU_HASH:
    730       ElfGnuHash = Entry.d_un.d_ptr;
    731       break;
    732     }
    733   }
    734   if (ElfGnuHash) {
    735     Expected<const uint8_t *> TablePtr = toMappedAddr(*ElfGnuHash);
    736     if (!TablePtr)
    737       return TablePtr.takeError();
    738     const Elf_GnuHash *Table =
    739         reinterpret_cast<const Elf_GnuHash *>(TablePtr.get());
    740     return getDynSymtabSizeFromGnuHash<ELFT>(*Table, this->Buf.bytes_end());
    741   }
    742 
    743   // Search SYSV hash table to try to find the upper bound of dynsym.
    744   if (ElfHash) {
    745     Expected<const uint8_t *> TablePtr = toMappedAddr(*ElfHash);
    746     if (!TablePtr)
    747       return TablePtr.takeError();
    748     const Elf_Hash *Table = reinterpret_cast<const Elf_Hash *>(TablePtr.get());
    749     return Table->nchain;
    750   }
    751   return 0;
    752 }
    753 
    754 template <class ELFT> ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {}
    755 
    756 template <class ELFT>
    757 Expected<ELFFile<ELFT>> ELFFile<ELFT>::create(StringRef Object) {
    758   if (sizeof(Elf_Ehdr) > Object.size())
    759     return createError("invalid buffer: the size (" + Twine(Object.size()) +
    760                        ") is smaller than an ELF header (" +
    761                        Twine(sizeof(Elf_Ehdr)) + ")");
    762   return ELFFile(Object);
    763 }
    764 
    765 template <class ELFT>
    766 Expected<typename ELFT::ShdrRange> ELFFile<ELFT>::sections() const {
    767   const uintX_t SectionTableOffset = getHeader().e_shoff;
    768   if (SectionTableOffset == 0)
    769     return ArrayRef<Elf_Shdr>();
    770 
    771   if (getHeader().e_shentsize != sizeof(Elf_Shdr))
    772     return createError("invalid e_shentsize in ELF header: " +
    773                        Twine(getHeader().e_shentsize));
    774 
    775   const uint64_t FileSize = Buf.size();
    776   if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize ||
    777       SectionTableOffset + (uintX_t)sizeof(Elf_Shdr) < SectionTableOffset)
    778     return createError(
    779         "section header table goes past the end of the file: e_shoff = 0x" +
    780         Twine::utohexstr(SectionTableOffset));
    781 
    782   // Invalid address alignment of section headers
    783   if (SectionTableOffset & (alignof(Elf_Shdr) - 1))
    784     // TODO: this error is untested.
    785     return createError("invalid alignment of section headers");
    786 
    787   const Elf_Shdr *First =
    788       reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
    789 
    790   uintX_t NumSections = getHeader().e_shnum;
    791   if (NumSections == 0)
    792     NumSections = First->sh_size;
    793 
    794   if (NumSections > UINT64_MAX / sizeof(Elf_Shdr))
    795     return createError("invalid number of sections specified in the NULL "
    796                        "section's sh_size field (" +
    797                        Twine(NumSections) + ")");
    798 
    799   const uint64_t SectionTableSize = NumSections * sizeof(Elf_Shdr);
    800   if (SectionTableOffset + SectionTableSize < SectionTableOffset)
    801     return createError(
    802         "invalid section header table offset (e_shoff = 0x" +
    803         Twine::utohexstr(SectionTableOffset) +
    804         ") or invalid number of sections specified in the first section "
    805         "header's sh_size field (0x" +
    806         Twine::utohexstr(NumSections) + ")");
    807 
    808   // Section table goes past end of file!
    809   if (SectionTableOffset + SectionTableSize > FileSize)
    810     return createError("section table goes past the end of file");
    811   return makeArrayRef(First, NumSections);
    812 }
    813 
    814 template <class ELFT>
    815 template <typename T>
    816 Expected<const T *> ELFFile<ELFT>::getEntry(uint32_t Section,
    817                                             uint32_t Entry) const {
    818   auto SecOrErr = getSection(Section);
    819   if (!SecOrErr)
    820     return SecOrErr.takeError();
    821   return getEntry<T>(**SecOrErr, Entry);
    822 }
    823 
    824 template <class ELFT>
    825 template <typename T>
    826 Expected<const T *> ELFFile<ELFT>::getEntry(const Elf_Shdr &Section,
    827                                             uint32_t Entry) const {
    828   Expected<ArrayRef<T>> EntriesOrErr = getSectionContentsAsArray<T>(Section);
    829   if (!EntriesOrErr)
    830     return EntriesOrErr.takeError();
    831 
    832   ArrayRef<T> Arr = *EntriesOrErr;
    833   if (Entry >= Arr.size())
    834     return createError(
    835         "can't read an entry at 0x" +
    836         Twine::utohexstr(Entry * static_cast<uint64_t>(sizeof(T))) +
    837         ": it goes past the end of the section (0x" +
    838         Twine::utohexstr(Section.sh_size) + ")");
    839   return &Arr[Entry];
    840 }
    841 
    842 template <typename ELFT>
    843 Expected<StringRef> ELFFile<ELFT>::getSymbolVersionByIndex(
    844     uint32_t SymbolVersionIndex, bool &IsDefault,
    845     SmallVector<Optional<VersionEntry>, 0> &VersionMap,
    846     Optional<bool> IsSymHidden) const {
    847   size_t VersionIndex = SymbolVersionIndex & llvm::ELF::VERSYM_VERSION;
    848 
    849   // Special markers for unversioned symbols.
    850   if (VersionIndex == llvm::ELF::VER_NDX_LOCAL ||
    851       VersionIndex == llvm::ELF::VER_NDX_GLOBAL) {
    852     IsDefault = false;
    853     return "";
    854   }
    855 
    856   // Lookup this symbol in the version table.
    857   if (VersionIndex >= VersionMap.size() || !VersionMap[VersionIndex])
    858     return createError("SHT_GNU_versym section refers to a version index " +
    859                        Twine(VersionIndex) + " which is missing");
    860 
    861   const VersionEntry &Entry = *VersionMap[VersionIndex];
    862   // A default version (@@) is only available for defined symbols.
    863   if (!Entry.IsVerDef || IsSymHidden.getValueOr(false))
    864     IsDefault = false;
    865   else
    866     IsDefault = !(SymbolVersionIndex & llvm::ELF::VERSYM_HIDDEN);
    867   return Entry.Name.c_str();
    868 }
    869 
    870 template <class ELFT>
    871 Expected<std::vector<VerDef>>
    872 ELFFile<ELFT>::getVersionDefinitions(const Elf_Shdr &Sec) const {
    873   Expected<StringRef> StrTabOrErr = getLinkAsStrtab(Sec);
    874   if (!StrTabOrErr)
    875     return StrTabOrErr.takeError();
    876 
    877   Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec);
    878   if (!ContentsOrErr)
    879     return createError("cannot read content of " + describe(*this, Sec) + ": " +
    880                        toString(ContentsOrErr.takeError()));
    881 
    882   const uint8_t *Start = ContentsOrErr->data();
    883   const uint8_t *End = Start + ContentsOrErr->size();
    884 
    885   auto ExtractNextAux = [&](const uint8_t *&VerdauxBuf,
    886                             unsigned VerDefNdx) -> Expected<VerdAux> {
    887     if (VerdauxBuf + sizeof(Elf_Verdaux) > End)
    888       return createError("invalid " + describe(*this, Sec) +
    889                          ": version definition " + Twine(VerDefNdx) +
    890                          " refers to an auxiliary entry that goes past the end "
    891                          "of the section");
    892 
    893     auto *Verdaux = reinterpret_cast<const Elf_Verdaux *>(VerdauxBuf);
    894     VerdauxBuf += Verdaux->vda_next;
    895 
    896     VerdAux Aux;
    897     Aux.Offset = VerdauxBuf - Start;
    898     if (Verdaux->vda_name <= StrTabOrErr->size())
    899       Aux.Name = std::string(StrTabOrErr->drop_front(Verdaux->vda_name));
    900     else
    901       Aux.Name = ("<invalid vda_name: " + Twine(Verdaux->vda_name) + ">").str();
    902     return Aux;
    903   };
    904 
    905   std::vector<VerDef> Ret;
    906   const uint8_t *VerdefBuf = Start;
    907   for (unsigned I = 1; I <= /*VerDefsNum=*/Sec.sh_info; ++I) {
    908     if (VerdefBuf + sizeof(Elf_Verdef) > End)
    909       return createError("invalid " + describe(*this, Sec) +
    910                          ": version definition " + Twine(I) +
    911                          " goes past the end of the section");
    912 
    913     if (reinterpret_cast<uintptr_t>(VerdefBuf) % sizeof(uint32_t) != 0)
    914       return createError(
    915           "invalid " + describe(*this, Sec) +
    916           ": found a misaligned version definition entry at offset 0x" +
    917           Twine::utohexstr(VerdefBuf - Start));
    918 
    919     unsigned Version = *reinterpret_cast<const Elf_Half *>(VerdefBuf);
    920     if (Version != 1)
    921       return createError("unable to dump " + describe(*this, Sec) +
    922                          ": version " + Twine(Version) +
    923                          " is not yet supported");
    924 
    925     const Elf_Verdef *D = reinterpret_cast<const Elf_Verdef *>(VerdefBuf);
    926     VerDef &VD = *Ret.emplace(Ret.end());
    927     VD.Offset = VerdefBuf - Start;
    928     VD.Version = D->vd_version;
    929     VD.Flags = D->vd_flags;
    930     VD.Ndx = D->vd_ndx;
    931     VD.Cnt = D->vd_cnt;
    932     VD.Hash = D->vd_hash;
    933 
    934     const uint8_t *VerdauxBuf = VerdefBuf + D->vd_aux;
    935     for (unsigned J = 0; J < D->vd_cnt; ++J) {
    936       if (reinterpret_cast<uintptr_t>(VerdauxBuf) % sizeof(uint32_t) != 0)
    937         return createError("invalid " + describe(*this, Sec) +
    938                            ": found a misaligned auxiliary entry at offset 0x" +
    939                            Twine::utohexstr(VerdauxBuf - Start));
    940 
    941       Expected<VerdAux> AuxOrErr = ExtractNextAux(VerdauxBuf, I);
    942       if (!AuxOrErr)
    943         return AuxOrErr.takeError();
    944 
    945       if (J == 0)
    946         VD.Name = AuxOrErr->Name;
    947       else
    948         VD.AuxV.push_back(*AuxOrErr);
    949     }
    950 
    951     VerdefBuf += D->vd_next;
    952   }
    953 
    954   return Ret;
    955 }
    956 
    957 template <class ELFT>
    958 Expected<std::vector<VerNeed>>
    959 ELFFile<ELFT>::getVersionDependencies(const Elf_Shdr &Sec,
    960                                       WarningHandler WarnHandler) const {
    961   StringRef StrTab;
    962   Expected<StringRef> StrTabOrErr = getLinkAsStrtab(Sec);
    963   if (!StrTabOrErr) {
    964     if (Error E = WarnHandler(toString(StrTabOrErr.takeError())))
    965       return std::move(E);
    966   } else {
    967     StrTab = *StrTabOrErr;
    968   }
    969 
    970   Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec);
    971   if (!ContentsOrErr)
    972     return createError("cannot read content of " + describe(*this, Sec) + ": " +
    973                        toString(ContentsOrErr.takeError()));
    974 
    975   const uint8_t *Start = ContentsOrErr->data();
    976   const uint8_t *End = Start + ContentsOrErr->size();
    977   const uint8_t *VerneedBuf = Start;
    978 
    979   std::vector<VerNeed> Ret;
    980   for (unsigned I = 1; I <= /*VerneedNum=*/Sec.sh_info; ++I) {
    981     if (VerneedBuf + sizeof(Elf_Verdef) > End)
    982       return createError("invalid " + describe(*this, Sec) +
    983                          ": version dependency " + Twine(I) +
    984                          " goes past the end of the section");
    985 
    986     if (reinterpret_cast<uintptr_t>(VerneedBuf) % sizeof(uint32_t) != 0)
    987       return createError(
    988           "invalid " + describe(*this, Sec) +
    989           ": found a misaligned version dependency entry at offset 0x" +
    990           Twine::utohexstr(VerneedBuf - Start));
    991 
    992     unsigned Version = *reinterpret_cast<const Elf_Half *>(VerneedBuf);
    993     if (Version != 1)
    994       return createError("unable to dump " + describe(*this, Sec) +
    995                          ": version " + Twine(Version) +
    996                          " is not yet supported");
    997 
    998     const Elf_Verneed *Verneed =
    999         reinterpret_cast<const Elf_Verneed *>(VerneedBuf);
   1000 
   1001     VerNeed &VN = *Ret.emplace(Ret.end());
   1002     VN.Version = Verneed->vn_version;
   1003     VN.Cnt = Verneed->vn_cnt;
   1004     VN.Offset = VerneedBuf - Start;
   1005 
   1006     if (Verneed->vn_file < StrTab.size())
   1007       VN.File = std::string(StrTab.drop_front(Verneed->vn_file));
   1008     else
   1009       VN.File = ("<corrupt vn_file: " + Twine(Verneed->vn_file) + ">").str();
   1010 
   1011     const uint8_t *VernauxBuf = VerneedBuf + Verneed->vn_aux;
   1012     for (unsigned J = 0; J < Verneed->vn_cnt; ++J) {
   1013       if (reinterpret_cast<uintptr_t>(VernauxBuf) % sizeof(uint32_t) != 0)
   1014         return createError("invalid " + describe(*this, Sec) +
   1015                            ": found a misaligned auxiliary entry at offset 0x" +
   1016                            Twine::utohexstr(VernauxBuf - Start));
   1017 
   1018       if (VernauxBuf + sizeof(Elf_Vernaux) > End)
   1019         return createError(
   1020             "invalid " + describe(*this, Sec) + ": version dependency " +
   1021             Twine(I) +
   1022             " refers to an auxiliary entry that goes past the end "
   1023             "of the section");
   1024 
   1025       const Elf_Vernaux *Vernaux =
   1026           reinterpret_cast<const Elf_Vernaux *>(VernauxBuf);
   1027 
   1028       VernAux &Aux = *VN.AuxV.emplace(VN.AuxV.end());
   1029       Aux.Hash = Vernaux->vna_hash;
   1030       Aux.Flags = Vernaux->vna_flags;
   1031       Aux.Other = Vernaux->vna_other;
   1032       Aux.Offset = VernauxBuf - Start;
   1033       if (StrTab.size() <= Vernaux->vna_name)
   1034         Aux.Name = "<corrupt>";
   1035       else
   1036         Aux.Name = std::string(StrTab.drop_front(Vernaux->vna_name));
   1037 
   1038       VernauxBuf += Vernaux->vna_next;
   1039     }
   1040     VerneedBuf += Verneed->vn_next;
   1041   }
   1042   return Ret;
   1043 }
   1044 
   1045 template <class ELFT>
   1046 Expected<const typename ELFT::Shdr *>
   1047 ELFFile<ELFT>::getSection(uint32_t Index) const {
   1048   auto TableOrErr = sections();
   1049   if (!TableOrErr)
   1050     return TableOrErr.takeError();
   1051   return object::getSection<ELFT>(*TableOrErr, Index);
   1052 }
   1053 
   1054 template <class ELFT>
   1055 Expected<StringRef>
   1056 ELFFile<ELFT>::getStringTable(const Elf_Shdr &Section,
   1057                               WarningHandler WarnHandler) const {
   1058   if (Section.sh_type != ELF::SHT_STRTAB)
   1059     if (Error E = WarnHandler("invalid sh_type for string table section " +
   1060                               getSecIndexForError(*this, Section) +
   1061                               ": expected SHT_STRTAB, but got " +
   1062                               object::getELFSectionTypeName(
   1063                                   getHeader().e_machine, Section.sh_type)))
   1064       return std::move(E);
   1065 
   1066   auto V = getSectionContentsAsArray<char>(Section);
   1067   if (!V)
   1068     return V.takeError();
   1069   ArrayRef<char> Data = *V;
   1070   if (Data.empty())
   1071     return createError("SHT_STRTAB string table section " +
   1072                        getSecIndexForError(*this, Section) + " is empty");
   1073   if (Data.back() != '\0')
   1074     return createError("SHT_STRTAB string table section " +
   1075                        getSecIndexForError(*this, Section) +
   1076                        " is non-null terminated");
   1077   return StringRef(Data.begin(), Data.size());
   1078 }
   1079 
   1080 template <class ELFT>
   1081 Expected<ArrayRef<typename ELFT::Word>>
   1082 ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
   1083   auto SectionsOrErr = sections();
   1084   if (!SectionsOrErr)
   1085     return SectionsOrErr.takeError();
   1086   return getSHNDXTable(Section, *SectionsOrErr);
   1087 }
   1088 
   1089 template <class ELFT>
   1090 Expected<ArrayRef<typename ELFT::Word>>
   1091 ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section,
   1092                              Elf_Shdr_Range Sections) const {
   1093   assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX);
   1094   auto VOrErr = getSectionContentsAsArray<Elf_Word>(Section);
   1095   if (!VOrErr)
   1096     return VOrErr.takeError();
   1097   ArrayRef<Elf_Word> V = *VOrErr;
   1098   auto SymTableOrErr = object::getSection<ELFT>(Sections, Section.sh_link);
   1099   if (!SymTableOrErr)
   1100     return SymTableOrErr.takeError();
   1101   const Elf_Shdr &SymTable = **SymTableOrErr;
   1102   if (SymTable.sh_type != ELF::SHT_SYMTAB &&
   1103       SymTable.sh_type != ELF::SHT_DYNSYM)
   1104     return createError(
   1105         "SHT_SYMTAB_SHNDX section is linked with " +
   1106         object::getELFSectionTypeName(getHeader().e_machine, SymTable.sh_type) +
   1107         " section (expected SHT_SYMTAB/SHT_DYNSYM)");
   1108 
   1109   uint64_t Syms = SymTable.sh_size / sizeof(Elf_Sym);
   1110   if (V.size() != Syms)
   1111     return createError("SHT_SYMTAB_SHNDX has " + Twine(V.size()) +
   1112                        " entries, but the symbol table associated has " +
   1113                        Twine(Syms));
   1114 
   1115   return V;
   1116 }
   1117 
   1118 template <class ELFT>
   1119 Expected<StringRef>
   1120 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
   1121   auto SectionsOrErr = sections();
   1122   if (!SectionsOrErr)
   1123     return SectionsOrErr.takeError();
   1124   return getStringTableForSymtab(Sec, *SectionsOrErr);
   1125 }
   1126 
   1127 template <class ELFT>
   1128 Expected<StringRef>
   1129 ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec,
   1130                                        Elf_Shdr_Range Sections) const {
   1131 
   1132   if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
   1133     return createError(
   1134         "invalid sh_type for symbol table, expected SHT_SYMTAB or SHT_DYNSYM");
   1135   Expected<const Elf_Shdr *> SectionOrErr =
   1136       object::getSection<ELFT>(Sections, Sec.sh_link);
   1137   if (!SectionOrErr)
   1138     return SectionOrErr.takeError();
   1139   return getStringTable(**SectionOrErr);
   1140 }
   1141 
   1142 template <class ELFT>
   1143 Expected<StringRef>
   1144 ELFFile<ELFT>::getLinkAsStrtab(const typename ELFT::Shdr &Sec) const {
   1145   Expected<const typename ELFT::Shdr *> StrTabSecOrErr =
   1146       getSection(Sec.sh_link);
   1147   if (!StrTabSecOrErr)
   1148     return createError("invalid section linked to " + describe(*this, Sec) +
   1149                        ": " + toString(StrTabSecOrErr.takeError()));
   1150 
   1151   Expected<StringRef> StrTabOrErr = getStringTable(**StrTabSecOrErr);
   1152   if (!StrTabOrErr)
   1153     return createError("invalid string table linked to " +
   1154                        describe(*this, Sec) + ": " +
   1155                        toString(StrTabOrErr.takeError()));
   1156   return *StrTabOrErr;
   1157 }
   1158 
   1159 template <class ELFT>
   1160 Expected<StringRef>
   1161 ELFFile<ELFT>::getSectionName(const Elf_Shdr &Section,
   1162                               WarningHandler WarnHandler) const {
   1163   auto SectionsOrErr = sections();
   1164   if (!SectionsOrErr)
   1165     return SectionsOrErr.takeError();
   1166   auto Table = getSectionStringTable(*SectionsOrErr, WarnHandler);
   1167   if (!Table)
   1168     return Table.takeError();
   1169   return getSectionName(Section, *Table);
   1170 }
   1171 
   1172 template <class ELFT>
   1173 Expected<StringRef> ELFFile<ELFT>::getSectionName(const Elf_Shdr &Section,
   1174                                                   StringRef DotShstrtab) const {
   1175   uint32_t Offset = Section.sh_name;
   1176   if (Offset == 0)
   1177     return StringRef();
   1178   if (Offset >= DotShstrtab.size())
   1179     return createError("a section " + getSecIndexForError(*this, Section) +
   1180                        " has an invalid sh_name (0x" +
   1181                        Twine::utohexstr(Offset) +
   1182                        ") offset which goes past the end of the "
   1183                        "section name string table");
   1184   return StringRef(DotShstrtab.data() + Offset);
   1185 }
   1186 
   1187 /// This function returns the hash value for a symbol in the .dynsym section
   1188 /// Name of the API remains consistent as specified in the libelf
   1189 /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
   1190 inline unsigned hashSysV(StringRef SymbolName) {
   1191   unsigned h = 0, g;
   1192   for (char C : SymbolName) {
   1193     h = (h << 4) + C;
   1194     g = h & 0xf0000000L;
   1195     if (g != 0)
   1196       h ^= g >> 24;
   1197     h &= ~g;
   1198   }
   1199   return h;
   1200 }
   1201 
   1202 } // end namespace object
   1203 } // end namespace llvm
   1204 
   1205 #endif // LLVM_OBJECT_ELF_H
   1206