ELF.h revision d111c7844ec26448764ced627e153f406d730c5f
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
30namespace llvm {
31namespace object {
32
33StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
34uint32_t getELFRelativeRelocationType(uint32_t Machine);
35StringRef getELFSectionTypeName(uint32_t Machine, uint32_t Type);
36
37// Subclasses of ELFFile may need this for template instantiation
38inline std::pair<unsigned char, unsigned char>
39getElfArchType(StringRef Object) {
40  if (Object.size() < ELF::EI_NIDENT)
41    return std::make_pair((uint8_t)ELF::ELFCLASSNONE,
42                          (uint8_t)ELF::ELFDATANONE);
43  return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
44                        (uint8_t)Object[ELF::EI_DATA]);
45}
46
47static inline Error createError(const Twine &Err) {
48  return make_error<StringError>(Err, object_error::parse_failed);
49}
50
51template <class ELFT> class ELFFile;
52
53template <class ELFT>
54std::string getSecIndexForError(const ELFFile<ELFT> *Obj,
55                                const typename ELFT::Shdr *Sec) {
56  auto TableOrErr = Obj->sections();
57  if (TableOrErr)
58    return "[index " + std::to_string(Sec - &TableOrErr->front()) + "]";
59  // To make this helper be more convenient for error reporting purposes we
60  // drop the error. But really it should never be triggered. Before this point,
61  // our code should have called 'sections()' and reported a proper error on
62  // failure.
63  llvm::consumeError(TableOrErr.takeError());
64  return "[unknown index]";
65}
66
67template <class ELFT>
68class ELFFile {
69public:
70  LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
71  using uintX_t = typename ELFT::uint;
72  using Elf_Ehdr = typename ELFT::Ehdr;
73  using Elf_Shdr = typename ELFT::Shdr;
74  using Elf_Sym = typename ELFT::Sym;
75  using Elf_Dyn = typename ELFT::Dyn;
76  using Elf_Phdr = typename ELFT::Phdr;
77  using Elf_Rel = typename ELFT::Rel;
78  using Elf_Rela = typename ELFT::Rela;
79  using Elf_Relr = typename ELFT::Relr;
80  using Elf_Verdef = typename ELFT::Verdef;
81  using Elf_Verdaux = typename ELFT::Verdaux;
82  using Elf_Verneed = typename ELFT::Verneed;
83  using Elf_Vernaux = typename ELFT::Vernaux;
84  using Elf_Versym = typename ELFT::Versym;
85  using Elf_Hash = typename ELFT::Hash;
86  using Elf_GnuHash = typename ELFT::GnuHash;
87  using Elf_Nhdr = typename ELFT::Nhdr;
88  using Elf_Note = typename ELFT::Note;
89  using Elf_Note_Iterator = typename ELFT::NoteIterator;
90  using Elf_Dyn_Range = typename ELFT::DynRange;
91  using Elf_Shdr_Range = typename ELFT::ShdrRange;
92  using Elf_Sym_Range = typename ELFT::SymRange;
93  using Elf_Rel_Range = typename ELFT::RelRange;
94  using Elf_Rela_Range = typename ELFT::RelaRange;
95  using Elf_Relr_Range = typename ELFT::RelrRange;
96  using Elf_Phdr_Range = typename ELFT::PhdrRange;
97
98  const uint8_t *base() const { return Buf.bytes_begin(); }
99
100  size_t getBufSize() const { return Buf.size(); }
101
102private:
103  StringRef Buf;
104
105  ELFFile(StringRef Object);
106
107public:
108  const Elf_Ehdr *getHeader() const {
109    return reinterpret_cast<const Elf_Ehdr *>(base());
110  }
111
112  template <typename T>
113  Expected<const T *> getEntry(uint32_t Section, uint32_t Entry) const;
114  template <typename T>
115  Expected<const T *> getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
116
117  Expected<StringRef> getStringTable(const Elf_Shdr *Section) const;
118  Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
119  Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section,
120                                              Elf_Shdr_Range Sections) const;
121
122  Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section) const;
123  Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section,
124                                             Elf_Shdr_Range Sections) const;
125
126  StringRef getRelocationTypeName(uint32_t Type) const;
127  void getRelocationTypeName(uint32_t Type,
128                             SmallVectorImpl<char> &Result) const;
129  uint32_t getRelativeRelocationType() const;
130
131  std::string getDynamicTagAsString(unsigned Arch, uint64_t Type) const;
132  std::string getDynamicTagAsString(uint64_t Type) const;
133
134  /// Get the symbol for a given relocation.
135  Expected<const Elf_Sym *> getRelocationSymbol(const Elf_Rel *Rel,
136                                                const Elf_Shdr *SymTab) const;
137
138  static Expected<ELFFile> create(StringRef Object);
139
140  bool isMipsELF64() const {
141    return getHeader()->e_machine == ELF::EM_MIPS &&
142           getHeader()->getFileClass() == ELF::ELFCLASS64;
143  }
144
145  bool isMips64EL() const {
146    return isMipsELF64() &&
147           getHeader()->getDataEncoding() == ELF::ELFDATA2LSB;
148  }
149
150  Expected<Elf_Shdr_Range> sections() const;
151
152  Expected<Elf_Dyn_Range> dynamicEntries() const;
153
154  Expected<const uint8_t *> toMappedAddr(uint64_t VAddr) const;
155
156  Expected<Elf_Sym_Range> symbols(const Elf_Shdr *Sec) const {
157    if (!Sec)
158      return makeArrayRef<Elf_Sym>(nullptr, nullptr);
159    return getSectionContentsAsArray<Elf_Sym>(Sec);
160  }
161
162  Expected<Elf_Rela_Range> relas(const Elf_Shdr *Sec) const {
163    return getSectionContentsAsArray<Elf_Rela>(Sec);
164  }
165
166  Expected<Elf_Rel_Range> rels(const Elf_Shdr *Sec) const {
167    return getSectionContentsAsArray<Elf_Rel>(Sec);
168  }
169
170  Expected<Elf_Relr_Range> relrs(const Elf_Shdr *Sec) const {
171    return getSectionContentsAsArray<Elf_Relr>(Sec);
172  }
173
174  Expected<std::vector<Elf_Rela>> decode_relrs(Elf_Relr_Range relrs) const;
175
176  Expected<std::vector<Elf_Rela>> android_relas(const Elf_Shdr *Sec) const;
177
178  /// Iterate over program header table.
179  Expected<Elf_Phdr_Range> program_headers() const {
180    if (getHeader()->e_phnum && getHeader()->e_phentsize != sizeof(Elf_Phdr))
181      return createError("invalid e_phentsize: " +
182                         Twine(getHeader()->e_phentsize));
183    if (getHeader()->e_phoff +
184            (getHeader()->e_phnum * getHeader()->e_phentsize) >
185        getBufSize())
186      return createError("program headers are longer than binary of size " +
187                         Twine(getBufSize()) + ": e_phoff = 0x" +
188                         Twine::utohexstr(getHeader()->e_phoff) +
189                         ", e_phnum = " + Twine(getHeader()->e_phnum) +
190                         ", e_phentsize = " + Twine(getHeader()->e_phentsize));
191    auto *Begin =
192        reinterpret_cast<const Elf_Phdr *>(base() + getHeader()->e_phoff);
193    return makeArrayRef(Begin, Begin + getHeader()->e_phnum);
194  }
195
196  /// Get an iterator over notes in a program header.
197  ///
198  /// The program header must be of type \c PT_NOTE.
199  ///
200  /// \param Phdr the program header to iterate over.
201  /// \param Err [out] an error to support fallible iteration, which should
202  ///  be checked after iteration ends.
203  Elf_Note_Iterator notes_begin(const Elf_Phdr &Phdr, Error &Err) const {
204    assert(Phdr.p_type == ELF::PT_NOTE && "Phdr is not of type PT_NOTE");
205    ErrorAsOutParameter ErrAsOutParam(&Err);
206    if (Phdr.p_offset + Phdr.p_filesz > getBufSize()) {
207      Err = createError("PT_NOTE header has invalid offset (0x" +
208                        Twine::utohexstr(Phdr.p_offset) + ") or size (0x" +
209                        Twine::utohexstr(Phdr.p_filesz) + ")");
210      return Elf_Note_Iterator(Err);
211    }
212    return Elf_Note_Iterator(base() + Phdr.p_offset, Phdr.p_filesz, Err);
213  }
214
215  /// Get an iterator over notes in a section.
216  ///
217  /// The section must be of type \c SHT_NOTE.
218  ///
219  /// \param Shdr the section to iterate over.
220  /// \param Err [out] an error to support fallible iteration, which should
221  ///  be checked after iteration ends.
222  Elf_Note_Iterator notes_begin(const Elf_Shdr &Shdr, Error &Err) const {
223    assert(Shdr.sh_type == ELF::SHT_NOTE && "Shdr is not of type SHT_NOTE");
224    ErrorAsOutParameter ErrAsOutParam(&Err);
225    if (Shdr.sh_offset + Shdr.sh_size > getBufSize()) {
226      Err = createError("SHT_NOTE section " + getSecIndexForError(this, &Shdr) +
227                        " has invalid offset (0x" +
228                        Twine::utohexstr(Shdr.sh_offset) + ") or size (0x" +
229                        Twine::utohexstr(Shdr.sh_size) + ")");
230      return Elf_Note_Iterator(Err);
231    }
232    return Elf_Note_Iterator(base() + Shdr.sh_offset, Shdr.sh_size, Err);
233  }
234
235  /// Get the end iterator for notes.
236  Elf_Note_Iterator notes_end() const {
237    return Elf_Note_Iterator();
238  }
239
240  /// Get an iterator range over notes of a program header.
241  ///
242  /// The program header must be of type \c PT_NOTE.
243  ///
244  /// \param Phdr the program header to iterate over.
245  /// \param Err [out] an error to support fallible iteration, which should
246  ///  be checked after iteration ends.
247  iterator_range<Elf_Note_Iterator> notes(const Elf_Phdr &Phdr,
248                                          Error &Err) const {
249    return make_range(notes_begin(Phdr, Err), notes_end());
250  }
251
252  /// Get an iterator range over notes of a section.
253  ///
254  /// The section must be of type \c SHT_NOTE.
255  ///
256  /// \param Shdr the section to iterate over.
257  /// \param Err [out] an error to support fallible iteration, which should
258  ///  be checked after iteration ends.
259  iterator_range<Elf_Note_Iterator> notes(const Elf_Shdr &Shdr,
260                                          Error &Err) const {
261    return make_range(notes_begin(Shdr, Err), notes_end());
262  }
263
264  Expected<StringRef> getSectionStringTable(Elf_Shdr_Range Sections) const;
265  Expected<uint32_t> getSectionIndex(const Elf_Sym *Sym, Elf_Sym_Range Syms,
266                                     ArrayRef<Elf_Word> ShndxTable) const;
267  Expected<const Elf_Shdr *> getSection(const Elf_Sym *Sym,
268                                        const Elf_Shdr *SymTab,
269                                        ArrayRef<Elf_Word> ShndxTable) const;
270  Expected<const Elf_Shdr *> getSection(const Elf_Sym *Sym,
271                                        Elf_Sym_Range Symtab,
272                                        ArrayRef<Elf_Word> ShndxTable) const;
273  Expected<const Elf_Shdr *> getSection(uint32_t Index) const;
274  Expected<const Elf_Shdr *> getSection(const StringRef SectionName) const;
275
276  Expected<const Elf_Sym *> getSymbol(const Elf_Shdr *Sec,
277                                      uint32_t Index) const;
278
279  Expected<StringRef> getSectionName(const Elf_Shdr *Section) const;
280  Expected<StringRef> getSectionName(const Elf_Shdr *Section,
281                                     StringRef DotShstrtab) const;
282  template <typename T>
283  Expected<ArrayRef<T>> getSectionContentsAsArray(const Elf_Shdr *Sec) const;
284  Expected<ArrayRef<uint8_t>> getSectionContents(const Elf_Shdr *Sec) const;
285};
286
287using ELF32LEFile = ELFFile<ELF32LE>;
288using ELF64LEFile = ELFFile<ELF64LE>;
289using ELF32BEFile = ELFFile<ELF32BE>;
290using ELF64BEFile = ELFFile<ELF64BE>;
291
292template <class ELFT>
293inline Expected<const typename ELFT::Shdr *>
294getSection(typename ELFT::ShdrRange Sections, uint32_t Index) {
295  if (Index >= Sections.size())
296    return createError("invalid section index: " + Twine(Index));
297  return &Sections[Index];
298}
299
300template <class ELFT>
301inline Expected<uint32_t>
302getExtendedSymbolTableIndex(const typename ELFT::Sym *Sym,
303                            const typename ELFT::Sym *FirstSym,
304                            ArrayRef<typename ELFT::Word> ShndxTable) {
305  assert(Sym->st_shndx == ELF::SHN_XINDEX);
306  unsigned Index = Sym - FirstSym;
307  if (Index >= ShndxTable.size())
308    return createError(
309        "extended symbol index (" + Twine(Index) +
310        ") is past the end of the SHT_SYMTAB_SHNDX section of size " +
311        Twine(ShndxTable.size()));
312
313  // The size of the table was checked in getSHNDXTable.
314  return ShndxTable[Index];
315}
316
317template <class ELFT>
318Expected<uint32_t>
319ELFFile<ELFT>::getSectionIndex(const Elf_Sym *Sym, Elf_Sym_Range Syms,
320                               ArrayRef<Elf_Word> ShndxTable) const {
321  uint32_t Index = Sym->st_shndx;
322  if (Index == ELF::SHN_XINDEX) {
323    auto ErrorOrIndex = getExtendedSymbolTableIndex<ELFT>(
324        Sym, Syms.begin(), ShndxTable);
325    if (!ErrorOrIndex)
326      return ErrorOrIndex.takeError();
327    return *ErrorOrIndex;
328  }
329  if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
330    return 0;
331  return Index;
332}
333
334template <class ELFT>
335Expected<const typename ELFT::Shdr *>
336ELFFile<ELFT>::getSection(const Elf_Sym *Sym, const Elf_Shdr *SymTab,
337                          ArrayRef<Elf_Word> ShndxTable) const {
338  auto SymsOrErr = symbols(SymTab);
339  if (!SymsOrErr)
340    return SymsOrErr.takeError();
341  return getSection(Sym, *SymsOrErr, ShndxTable);
342}
343
344template <class ELFT>
345Expected<const typename ELFT::Shdr *>
346ELFFile<ELFT>::getSection(const Elf_Sym *Sym, Elf_Sym_Range Symbols,
347                          ArrayRef<Elf_Word> ShndxTable) const {
348  auto IndexOrErr = getSectionIndex(Sym, Symbols, ShndxTable);
349  if (!IndexOrErr)
350    return IndexOrErr.takeError();
351  uint32_t Index = *IndexOrErr;
352  if (Index == 0)
353    return nullptr;
354  return getSection(Index);
355}
356
357template <class ELFT>
358Expected<const typename ELFT::Sym *>
359ELFFile<ELFT>::getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
360  auto SymsOrErr = symbols(Sec);
361  if (!SymsOrErr)
362    return SymsOrErr.takeError();
363
364  Elf_Sym_Range Symbols = *SymsOrErr;
365  if (Index >= Symbols.size())
366    return createError("unable to get symbol from section " +
367                       getSecIndexForError(this, Sec) +
368                       ": invalid symbol index (" + Twine(Index) + ")");
369  return &Symbols[Index];
370}
371
372template <class ELFT>
373template <typename T>
374Expected<ArrayRef<T>>
375ELFFile<ELFT>::getSectionContentsAsArray(const Elf_Shdr *Sec) const {
376  if (Sec->sh_entsize != sizeof(T) && sizeof(T) != 1)
377    return createError("section " + getSecIndexForError(this, Sec) +
378                       " has an invalid sh_entsize: " + Twine(Sec->sh_entsize));
379
380  uintX_t Offset = Sec->sh_offset;
381  uintX_t Size = Sec->sh_size;
382
383  if (Size % sizeof(T))
384    return createError("section " + getSecIndexForError(this, Sec) +
385                       " has an invalid sh_size (" + Twine(Size) +
386                       ") which is not a multiple of its sh_entsize (" +
387                       Twine(Sec->sh_entsize) + ")");
388  if ((std::numeric_limits<uintX_t>::max() - Offset < Size) ||
389      Offset + Size > Buf.size())
390    return createError("section " + getSecIndexForError(this, Sec) +
391                       " has a sh_offset (0x" + Twine::utohexstr(Offset) +
392                       ") + sh_size (0x" + Twine(Size) +
393                       ") that cannot be represented");
394
395  if (Offset % alignof(T))
396    // TODO: this error is untested.
397    return createError("unaligned data");
398
399  const T *Start = reinterpret_cast<const T *>(base() + Offset);
400  return makeArrayRef(Start, Size / sizeof(T));
401}
402
403template <class ELFT>
404Expected<ArrayRef<uint8_t>>
405ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
406  return getSectionContentsAsArray<uint8_t>(Sec);
407}
408
409template <class ELFT>
410StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
411  return getELFRelocationTypeName(getHeader()->e_machine, Type);
412}
413
414template <class ELFT>
415void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
416                                          SmallVectorImpl<char> &Result) const {
417  if (!isMipsELF64()) {
418    StringRef Name = getRelocationTypeName(Type);
419    Result.append(Name.begin(), Name.end());
420  } else {
421    // The Mips N64 ABI allows up to three operations to be specified per
422    // relocation record. Unfortunately there's no easy way to test for the
423    // presence of N64 ELFs as they have no special flag that identifies them
424    // as being N64. We can safely assume at the moment that all Mips
425    // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
426    // information to disambiguate between old vs new ABIs.
427    uint8_t Type1 = (Type >> 0) & 0xFF;
428    uint8_t Type2 = (Type >> 8) & 0xFF;
429    uint8_t Type3 = (Type >> 16) & 0xFF;
430
431    // Concat all three relocation type names.
432    StringRef Name = getRelocationTypeName(Type1);
433    Result.append(Name.begin(), Name.end());
434
435    Name = getRelocationTypeName(Type2);
436    Result.append(1, '/');
437    Result.append(Name.begin(), Name.end());
438
439    Name = getRelocationTypeName(Type3);
440    Result.append(1, '/');
441    Result.append(Name.begin(), Name.end());
442  }
443}
444
445template <class ELFT>
446uint32_t ELFFile<ELFT>::getRelativeRelocationType() const {
447  return getELFRelativeRelocationType(getHeader()->e_machine);
448}
449
450template <class ELFT>
451Expected<const typename ELFT::Sym *>
452ELFFile<ELFT>::getRelocationSymbol(const Elf_Rel *Rel,
453                                   const Elf_Shdr *SymTab) const {
454  uint32_t Index = Rel->getSymbol(isMips64EL());
455  if (Index == 0)
456    return nullptr;
457  return getEntry<Elf_Sym>(SymTab, Index);
458}
459
460template <class ELFT>
461Expected<StringRef>
462ELFFile<ELFT>::getSectionStringTable(Elf_Shdr_Range Sections) const {
463  uint32_t Index = getHeader()->e_shstrndx;
464  if (Index == ELF::SHN_XINDEX)
465    Index = Sections[0].sh_link;
466
467  if (!Index) // no section string table.
468    return "";
469  // TODO: Test a case when the sh_link of the section with index 0 is broken.
470  if (Index >= Sections.size())
471    return createError("section header string table index " + Twine(Index) +
472                       " does not exist");
473  return getStringTable(&Sections[Index]);
474}
475
476template <class ELFT> ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {}
477
478template <class ELFT>
479Expected<ELFFile<ELFT>> ELFFile<ELFT>::create(StringRef Object) {
480  if (sizeof(Elf_Ehdr) > Object.size())
481    return createError("invalid buffer: the size (" + Twine(Object.size()) +
482                       ") is smaller than an ELF header (" +
483                       Twine(sizeof(Elf_Ehdr)) + ")");
484  return ELFFile(Object);
485}
486
487template <class ELFT>
488Expected<typename ELFT::ShdrRange> ELFFile<ELFT>::sections() const {
489  const uintX_t SectionTableOffset = getHeader()->e_shoff;
490  if (SectionTableOffset == 0)
491    return ArrayRef<Elf_Shdr>();
492
493  if (getHeader()->e_shentsize != sizeof(Elf_Shdr))
494    return createError("invalid e_shentsize in ELF header: " +
495                       Twine(getHeader()->e_shentsize));
496
497  const uint64_t FileSize = Buf.size();
498  if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
499    return createError(
500        "section header table goes past the end of the file: e_shoff = 0x" +
501        Twine::utohexstr(SectionTableOffset));
502
503  // Invalid address alignment of section headers
504  if (SectionTableOffset & (alignof(Elf_Shdr) - 1))
505    // TODO: this error is untested.
506    return createError("invalid alignment of section headers");
507
508  const Elf_Shdr *First =
509      reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
510
511  uintX_t NumSections = getHeader()->e_shnum;
512  if (NumSections == 0)
513    NumSections = First->sh_size;
514
515  if (NumSections > UINT64_MAX / sizeof(Elf_Shdr))
516    // TODO: this error is untested.
517    return createError("section table goes past the end of file");
518
519  const uint64_t SectionTableSize = NumSections * sizeof(Elf_Shdr);
520
521  // Section table goes past end of file!
522  if (SectionTableOffset + SectionTableSize > FileSize)
523    return createError("section table goes past the end of file");
524
525  return makeArrayRef(First, NumSections);
526}
527
528template <class ELFT>
529template <typename T>
530Expected<const T *> ELFFile<ELFT>::getEntry(uint32_t Section,
531                                            uint32_t Entry) const {
532  auto SecOrErr = getSection(Section);
533  if (!SecOrErr)
534    return SecOrErr.takeError();
535  return getEntry<T>(*SecOrErr, Entry);
536}
537
538template <class ELFT>
539template <typename T>
540Expected<const T *> ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
541                                            uint32_t Entry) const {
542  if (sizeof(T) != Section->sh_entsize)
543    // TODO: this error is untested.
544    return createError("invalid sh_entsize");
545  size_t Pos = Section->sh_offset + Entry * sizeof(T);
546  if (Pos + sizeof(T) > Buf.size())
547    return createError("unable to access section " +
548                       getSecIndexForError(this, Section) + " data at 0x" +
549                       Twine::utohexstr(Pos) +
550                       ": offset goes past the end of file");
551  return reinterpret_cast<const T *>(base() + Pos);
552}
553
554template <class ELFT>
555Expected<const typename ELFT::Shdr *>
556ELFFile<ELFT>::getSection(uint32_t Index) const {
557  auto TableOrErr = sections();
558  if (!TableOrErr)
559    return TableOrErr.takeError();
560  return object::getSection<ELFT>(*TableOrErr, Index);
561}
562
563template <class ELFT>
564Expected<const typename ELFT::Shdr *>
565ELFFile<ELFT>::getSection(const StringRef SectionName) const {
566  auto TableOrErr = sections();
567  if (!TableOrErr)
568    return TableOrErr.takeError();
569  for (auto &Sec : *TableOrErr) {
570    auto SecNameOrErr = getSectionName(&Sec);
571    if (!SecNameOrErr)
572      return SecNameOrErr.takeError();
573    if (*SecNameOrErr == SectionName)
574      return &Sec;
575  }
576  // TODO: this error is untested.
577  return createError("invalid section name");
578}
579
580template <class ELFT>
581Expected<StringRef>
582ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
583  if (Section->sh_type != ELF::SHT_STRTAB)
584    return createError("invalid sh_type for string table section " +
585                       getSecIndexForError(this, Section) +
586                       ": expected SHT_STRTAB, but got " +
587                       object::getELFSectionTypeName(getHeader()->e_machine,
588                                                     Section->sh_type));
589  auto V = getSectionContentsAsArray<char>(Section);
590  if (!V)
591    return V.takeError();
592  ArrayRef<char> Data = *V;
593  if (Data.empty())
594    // TODO: this error is untested.
595    return createError("empty string table");
596  if (Data.back() != '\0')
597    return createError(object::getELFSectionTypeName(getHeader()->e_machine,
598                                                     Section->sh_type) +
599                       " string table section " +
600                       getSecIndexForError(this, Section) +
601                       " is non-null terminated");
602  return StringRef(Data.begin(), Data.size());
603}
604
605template <class ELFT>
606Expected<ArrayRef<typename ELFT::Word>>
607ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
608  auto SectionsOrErr = sections();
609  if (!SectionsOrErr)
610    return SectionsOrErr.takeError();
611  return getSHNDXTable(Section, *SectionsOrErr);
612}
613
614template <class ELFT>
615Expected<ArrayRef<typename ELFT::Word>>
616ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section,
617                             Elf_Shdr_Range Sections) const {
618  assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX);
619  auto VOrErr = getSectionContentsAsArray<Elf_Word>(&Section);
620  if (!VOrErr)
621    return VOrErr.takeError();
622  ArrayRef<Elf_Word> V = *VOrErr;
623  auto SymTableOrErr = object::getSection<ELFT>(Sections, Section.sh_link);
624  if (!SymTableOrErr)
625    return SymTableOrErr.takeError();
626  const Elf_Shdr &SymTable = **SymTableOrErr;
627  if (SymTable.sh_type != ELF::SHT_SYMTAB &&
628      SymTable.sh_type != ELF::SHT_DYNSYM)
629    // TODO: this error is untested.
630    return createError("invalid sh_type");
631  if (V.size() != (SymTable.sh_size / sizeof(Elf_Sym)))
632    return createError("SHT_SYMTAB_SHNDX section has sh_size (" +
633                       Twine(SymTable.sh_size) +
634                       ") which is not equal to the number of symbols (" +
635                       Twine(V.size()) + ")");
636  return V;
637}
638
639template <class ELFT>
640Expected<StringRef>
641ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
642  auto SectionsOrErr = sections();
643  if (!SectionsOrErr)
644    return SectionsOrErr.takeError();
645  return getStringTableForSymtab(Sec, *SectionsOrErr);
646}
647
648template <class ELFT>
649Expected<StringRef>
650ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec,
651                                       Elf_Shdr_Range Sections) const {
652
653  if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
654    // TODO: this error is untested.
655    return createError(
656        "invalid sh_type for symbol table, expected SHT_SYMTAB or SHT_DYNSYM");
657  auto SectionOrErr = object::getSection<ELFT>(Sections, Sec.sh_link);
658  if (!SectionOrErr)
659    return SectionOrErr.takeError();
660  return getStringTable(*SectionOrErr);
661}
662
663template <class ELFT>
664Expected<StringRef>
665ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
666  auto SectionsOrErr = sections();
667  if (!SectionsOrErr)
668    return SectionsOrErr.takeError();
669  auto Table = getSectionStringTable(*SectionsOrErr);
670  if (!Table)
671    return Table.takeError();
672  return getSectionName(Section, *Table);
673}
674
675template <class ELFT>
676Expected<StringRef> ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section,
677                                                  StringRef DotShstrtab) const {
678  uint32_t Offset = Section->sh_name;
679  if (Offset == 0)
680    return StringRef();
681  if (Offset >= DotShstrtab.size())
682    return createError("a section " + getSecIndexForError(this, Section) +
683                       " has an invalid sh_name (0x" +
684                       Twine::utohexstr(Offset) +
685                       ") offset which goes past the end of the "
686                       "section name string table");
687  return StringRef(DotShstrtab.data() + Offset);
688}
689
690/// This function returns the hash value for a symbol in the .dynsym section
691/// Name of the API remains consistent as specified in the libelf
692/// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
693inline unsigned hashSysV(StringRef SymbolName) {
694  unsigned h = 0, g;
695  for (char C : SymbolName) {
696    h = (h << 4) + C;
697    g = h & 0xf0000000L;
698    if (g != 0)
699      h ^= g >> 24;
700    h &= ~g;
701  }
702  return h;
703}
704
705} // end namespace object
706} // end namespace llvm
707
708#endif // LLVM_OBJECT_ELF_H
709