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