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