blob: cab29741cf095c060fc18859fe1b6e16ce6114c1 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- ELF.h - ELF object file implementation -------------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
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);
Andrew Walbran16937d02019-10-22 13:54:20 +010034uint32_t getELFRelativeRelocationType(uint32_t Machine);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010035StringRef 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
Andrew Walbran3d2c1972020-04-07 12:24:26 +010047static inline Error createError(const Twine &Err) {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010048 return make_error<StringError>(Err, object_error::parse_failed);
49}
50
Andrew Walbran3d2c1972020-04-07 12:24:26 +010051template <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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010067template <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;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010079 using Elf_Relr = typename ELFT::Relr;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010080 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;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010095 using Elf_Relr_Range = typename ELFT::RelrRange;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010096 using Elf_Phdr_Range = typename ELFT::PhdrRange;
97
Andrew Walbran3d2c1972020-04-07 12:24:26 +010098 const uint8_t *base() const { return Buf.bytes_begin(); }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010099
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;
Andrew Walbran16937d02019-10-22 13:54:20 +0100129 uint32_t getRelativeRelocationType() const;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100130
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100131 std::string getDynamicTagAsString(unsigned Arch, uint64_t Type) const;
132 std::string getDynamicTagAsString(uint64_t Type) const;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100133
134 /// Get the symbol for a given relocation.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100135 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
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100152 Expected<Elf_Dyn_Range> dynamicEntries() const;
153
154 Expected<const uint8_t *> toMappedAddr(uint64_t VAddr) const;
155
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100156 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
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100170 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100176 Expected<std::vector<Elf_Rela>> android_relas(const Elf_Shdr *Sec) const;
177
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100178 /// Iterate over program header table.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100179 Expected<Elf_Phdr_Range> program_headers() const {
180 if (getHeader()->e_phnum && getHeader()->e_phentsize != sizeof(Elf_Phdr))
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100181 return createError("invalid e_phentsize: " +
182 Twine(getHeader()->e_phentsize));
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100183 if (getHeader()->e_phoff +
184 (getHeader()->e_phnum * getHeader()->e_phentsize) >
185 getBufSize())
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100186 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));
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100191 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 if (Phdr.p_type != ELF::PT_NOTE) {
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100205 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100206 Err = createError("attempt to iterate notes of non-note program header");
207 return Elf_Note_Iterator(Err);
208 }
209 if (Phdr.p_offset + Phdr.p_filesz > getBufSize()) {
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100210 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100211 Err = createError("invalid program header offset/size");
212 return Elf_Note_Iterator(Err);
213 }
214 return Elf_Note_Iterator(base() + Phdr.p_offset, Phdr.p_filesz, Err);
215 }
216
217 /// Get an iterator over notes in a section.
218 ///
219 /// The section must be of type \c SHT_NOTE.
220 ///
221 /// \param Shdr the section to iterate over.
222 /// \param Err [out] an error to support fallible iteration, which should
223 /// be checked after iteration ends.
224 Elf_Note_Iterator notes_begin(const Elf_Shdr &Shdr, Error &Err) const {
225 if (Shdr.sh_type != ELF::SHT_NOTE) {
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100226 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100227 Err = createError("attempt to iterate notes of non-note section");
228 return Elf_Note_Iterator(Err);
229 }
230 if (Shdr.sh_offset + Shdr.sh_size > getBufSize()) {
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100231 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100232 Err = createError("invalid section offset/size");
233 return Elf_Note_Iterator(Err);
234 }
235 return Elf_Note_Iterator(base() + Shdr.sh_offset, Shdr.sh_size, Err);
236 }
237
238 /// Get the end iterator for notes.
239 Elf_Note_Iterator notes_end() const {
240 return Elf_Note_Iterator();
241 }
242
243 /// Get an iterator range over notes of a program header.
244 ///
245 /// The program header must be of type \c PT_NOTE.
246 ///
247 /// \param Phdr the program header to iterate over.
248 /// \param Err [out] an error to support fallible iteration, which should
249 /// be checked after iteration ends.
250 iterator_range<Elf_Note_Iterator> notes(const Elf_Phdr &Phdr,
251 Error &Err) const {
252 return make_range(notes_begin(Phdr, Err), notes_end());
253 }
254
255 /// Get an iterator range over notes of a section.
256 ///
257 /// The section must be of type \c SHT_NOTE.
258 ///
259 /// \param Shdr the section to iterate over.
260 /// \param Err [out] an error to support fallible iteration, which should
261 /// be checked after iteration ends.
262 iterator_range<Elf_Note_Iterator> notes(const Elf_Shdr &Shdr,
263 Error &Err) const {
264 return make_range(notes_begin(Shdr, Err), notes_end());
265 }
266
267 Expected<StringRef> getSectionStringTable(Elf_Shdr_Range Sections) const;
268 Expected<uint32_t> getSectionIndex(const Elf_Sym *Sym, Elf_Sym_Range Syms,
269 ArrayRef<Elf_Word> ShndxTable) const;
270 Expected<const Elf_Shdr *> getSection(const Elf_Sym *Sym,
271 const Elf_Shdr *SymTab,
272 ArrayRef<Elf_Word> ShndxTable) const;
273 Expected<const Elf_Shdr *> getSection(const Elf_Sym *Sym,
274 Elf_Sym_Range Symtab,
275 ArrayRef<Elf_Word> ShndxTable) const;
276 Expected<const Elf_Shdr *> getSection(uint32_t Index) const;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100277 Expected<const Elf_Shdr *> getSection(const StringRef SectionName) const;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100278
279 Expected<const Elf_Sym *> getSymbol(const Elf_Shdr *Sec,
280 uint32_t Index) const;
281
282 Expected<StringRef> getSectionName(const Elf_Shdr *Section) const;
283 Expected<StringRef> getSectionName(const Elf_Shdr *Section,
284 StringRef DotShstrtab) const;
285 template <typename T>
286 Expected<ArrayRef<T>> getSectionContentsAsArray(const Elf_Shdr *Sec) const;
287 Expected<ArrayRef<uint8_t>> getSectionContents(const Elf_Shdr *Sec) const;
288};
289
290using ELF32LEFile = ELFFile<ELF32LE>;
291using ELF64LEFile = ELFFile<ELF64LE>;
292using ELF32BEFile = ELFFile<ELF32BE>;
293using ELF64BEFile = ELFFile<ELF64BE>;
294
295template <class ELFT>
296inline Expected<const typename ELFT::Shdr *>
297getSection(typename ELFT::ShdrRange Sections, uint32_t Index) {
298 if (Index >= Sections.size())
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100299 return createError("invalid section index: " + Twine(Index));
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100300 return &Sections[Index];
301}
302
303template <class ELFT>
304inline Expected<uint32_t>
305getExtendedSymbolTableIndex(const typename ELFT::Sym *Sym,
306 const typename ELFT::Sym *FirstSym,
307 ArrayRef<typename ELFT::Word> ShndxTable) {
308 assert(Sym->st_shndx == ELF::SHN_XINDEX);
309 unsigned Index = Sym - FirstSym;
310 if (Index >= ShndxTable.size())
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100311 return createError(
312 "extended symbol index (" + Twine(Index) +
313 ") is past the end of the SHT_SYMTAB_SHNDX section of size " +
314 Twine(ShndxTable.size()));
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100315
316 // The size of the table was checked in getSHNDXTable.
317 return ShndxTable[Index];
318}
319
320template <class ELFT>
321Expected<uint32_t>
322ELFFile<ELFT>::getSectionIndex(const Elf_Sym *Sym, Elf_Sym_Range Syms,
323 ArrayRef<Elf_Word> ShndxTable) const {
324 uint32_t Index = Sym->st_shndx;
325 if (Index == ELF::SHN_XINDEX) {
326 auto ErrorOrIndex = getExtendedSymbolTableIndex<ELFT>(
327 Sym, Syms.begin(), ShndxTable);
328 if (!ErrorOrIndex)
329 return ErrorOrIndex.takeError();
330 return *ErrorOrIndex;
331 }
332 if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
333 return 0;
334 return Index;
335}
336
337template <class ELFT>
338Expected<const typename ELFT::Shdr *>
339ELFFile<ELFT>::getSection(const Elf_Sym *Sym, const Elf_Shdr *SymTab,
340 ArrayRef<Elf_Word> ShndxTable) const {
341 auto SymsOrErr = symbols(SymTab);
342 if (!SymsOrErr)
343 return SymsOrErr.takeError();
344 return getSection(Sym, *SymsOrErr, ShndxTable);
345}
346
347template <class ELFT>
348Expected<const typename ELFT::Shdr *>
349ELFFile<ELFT>::getSection(const Elf_Sym *Sym, Elf_Sym_Range Symbols,
350 ArrayRef<Elf_Word> ShndxTable) const {
351 auto IndexOrErr = getSectionIndex(Sym, Symbols, ShndxTable);
352 if (!IndexOrErr)
353 return IndexOrErr.takeError();
354 uint32_t Index = *IndexOrErr;
355 if (Index == 0)
356 return nullptr;
357 return getSection(Index);
358}
359
360template <class ELFT>
361inline Expected<const typename ELFT::Sym *>
362getSymbol(typename ELFT::SymRange Symbols, uint32_t Index) {
363 if (Index >= Symbols.size())
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100364 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100365 return createError("invalid symbol index");
366 return &Symbols[Index];
367}
368
369template <class ELFT>
370Expected<const typename ELFT::Sym *>
371ELFFile<ELFT>::getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
372 auto SymtabOrErr = symbols(Sec);
373 if (!SymtabOrErr)
374 return SymtabOrErr.takeError();
375 return object::getSymbol<ELFT>(*SymtabOrErr, Index);
376}
377
378template <class ELFT>
379template <typename T>
380Expected<ArrayRef<T>>
381ELFFile<ELFT>::getSectionContentsAsArray(const Elf_Shdr *Sec) const {
382 if (Sec->sh_entsize != sizeof(T) && sizeof(T) != 1)
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100383 return createError("section " + getSecIndexForError(this, Sec) +
384 " has an invalid sh_entsize: " + Twine(Sec->sh_entsize));
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100385
386 uintX_t Offset = Sec->sh_offset;
387 uintX_t Size = Sec->sh_size;
388
389 if (Size % sizeof(T))
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100390 return createError("section " + getSecIndexForError(this, Sec) +
391 " has an invalid sh_size (" + Twine(Size) +
392 ") which is not a multiple of its sh_entsize (" +
393 Twine(Sec->sh_entsize) + ")");
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100394 if ((std::numeric_limits<uintX_t>::max() - Offset < Size) ||
395 Offset + Size > Buf.size())
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100396 return createError("section " + getSecIndexForError(this, Sec) +
397 " has a sh_offset (0x" + Twine::utohexstr(Offset) +
398 ") + sh_size (0x" + Twine(Size) +
399 ") that cannot be represented");
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100400
401 if (Offset % alignof(T))
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100402 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100403 return createError("unaligned data");
404
405 const T *Start = reinterpret_cast<const T *>(base() + Offset);
406 return makeArrayRef(Start, Size / sizeof(T));
407}
408
409template <class ELFT>
410Expected<ArrayRef<uint8_t>>
411ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
412 return getSectionContentsAsArray<uint8_t>(Sec);
413}
414
415template <class ELFT>
416StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
417 return getELFRelocationTypeName(getHeader()->e_machine, Type);
418}
419
420template <class ELFT>
421void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
422 SmallVectorImpl<char> &Result) const {
423 if (!isMipsELF64()) {
424 StringRef Name = getRelocationTypeName(Type);
425 Result.append(Name.begin(), Name.end());
426 } else {
427 // The Mips N64 ABI allows up to three operations to be specified per
428 // relocation record. Unfortunately there's no easy way to test for the
429 // presence of N64 ELFs as they have no special flag that identifies them
430 // as being N64. We can safely assume at the moment that all Mips
431 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
432 // information to disambiguate between old vs new ABIs.
433 uint8_t Type1 = (Type >> 0) & 0xFF;
434 uint8_t Type2 = (Type >> 8) & 0xFF;
435 uint8_t Type3 = (Type >> 16) & 0xFF;
436
437 // Concat all three relocation type names.
438 StringRef Name = getRelocationTypeName(Type1);
439 Result.append(Name.begin(), Name.end());
440
441 Name = getRelocationTypeName(Type2);
442 Result.append(1, '/');
443 Result.append(Name.begin(), Name.end());
444
445 Name = getRelocationTypeName(Type3);
446 Result.append(1, '/');
447 Result.append(Name.begin(), Name.end());
448 }
449}
450
451template <class ELFT>
Andrew Walbran16937d02019-10-22 13:54:20 +0100452uint32_t ELFFile<ELFT>::getRelativeRelocationType() const {
453 return getELFRelativeRelocationType(getHeader()->e_machine);
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100454}
455
456template <class ELFT>
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100457Expected<const typename ELFT::Sym *>
458ELFFile<ELFT>::getRelocationSymbol(const Elf_Rel *Rel,
459 const Elf_Shdr *SymTab) const {
460 uint32_t Index = Rel->getSymbol(isMips64EL());
461 if (Index == 0)
462 return nullptr;
463 return getEntry<Elf_Sym>(SymTab, Index);
464}
465
466template <class ELFT>
467Expected<StringRef>
468ELFFile<ELFT>::getSectionStringTable(Elf_Shdr_Range Sections) const {
469 uint32_t Index = getHeader()->e_shstrndx;
470 if (Index == ELF::SHN_XINDEX)
471 Index = Sections[0].sh_link;
472
473 if (!Index) // no section string table.
474 return "";
475 if (Index >= Sections.size())
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100476 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100477 return createError("invalid section index");
478 return getStringTable(&Sections[Index]);
479}
480
481template <class ELFT> ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {}
482
483template <class ELFT>
484Expected<ELFFile<ELFT>> ELFFile<ELFT>::create(StringRef Object) {
485 if (sizeof(Elf_Ehdr) > Object.size())
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100486 return createError("invalid buffer: the size (" + Twine(Object.size()) +
487 ") is smaller than an ELF header (" +
488 Twine(sizeof(Elf_Ehdr)) + ")");
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100489 return ELFFile(Object);
490}
491
492template <class ELFT>
493Expected<typename ELFT::ShdrRange> ELFFile<ELFT>::sections() const {
494 const uintX_t SectionTableOffset = getHeader()->e_shoff;
495 if (SectionTableOffset == 0)
496 return ArrayRef<Elf_Shdr>();
497
498 if (getHeader()->e_shentsize != sizeof(Elf_Shdr))
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100499 return createError("invalid e_shentsize in ELF header: " +
500 Twine(getHeader()->e_shentsize));
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100501
502 const uint64_t FileSize = Buf.size();
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100503 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100504 return createError(
505 "section header table goes past the end of the file: e_shoff = 0x" +
506 Twine::utohexstr(SectionTableOffset));
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100507
508 // Invalid address alignment of section headers
509 if (SectionTableOffset & (alignof(Elf_Shdr) - 1))
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100510 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100511 return createError("invalid alignment of section headers");
512
513 const Elf_Shdr *First =
514 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
515
516 uintX_t NumSections = getHeader()->e_shnum;
517 if (NumSections == 0)
518 NumSections = First->sh_size;
519
520 if (NumSections > UINT64_MAX / sizeof(Elf_Shdr))
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100521 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100522 return createError("section table goes past the end of file");
523
524 const uint64_t SectionTableSize = NumSections * sizeof(Elf_Shdr);
525
526 // Section table goes past end of file!
527 if (SectionTableOffset + SectionTableSize > FileSize)
528 return createError("section table goes past the end of file");
529
530 return makeArrayRef(First, NumSections);
531}
532
533template <class ELFT>
534template <typename T>
535Expected<const T *> ELFFile<ELFT>::getEntry(uint32_t Section,
536 uint32_t Entry) const {
537 auto SecOrErr = getSection(Section);
538 if (!SecOrErr)
539 return SecOrErr.takeError();
540 return getEntry<T>(*SecOrErr, Entry);
541}
542
543template <class ELFT>
544template <typename T>
545Expected<const T *> ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
546 uint32_t Entry) const {
547 if (sizeof(T) != Section->sh_entsize)
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100548 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100549 return createError("invalid sh_entsize");
550 size_t Pos = Section->sh_offset + Entry * sizeof(T);
551 if (Pos + sizeof(T) > Buf.size())
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100552 return createError("unable to access section " +
553 getSecIndexForError(this, Section) + " data at 0x" +
554 Twine::utohexstr(Pos) +
555 ": offset goes past the end of file");
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100556 return reinterpret_cast<const T *>(base() + Pos);
557}
558
559template <class ELFT>
560Expected<const typename ELFT::Shdr *>
561ELFFile<ELFT>::getSection(uint32_t Index) const {
562 auto TableOrErr = sections();
563 if (!TableOrErr)
564 return TableOrErr.takeError();
565 return object::getSection<ELFT>(*TableOrErr, Index);
566}
567
568template <class ELFT>
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100569Expected<const typename ELFT::Shdr *>
570ELFFile<ELFT>::getSection(const StringRef SectionName) const {
571 auto TableOrErr = sections();
572 if (!TableOrErr)
573 return TableOrErr.takeError();
574 for (auto &Sec : *TableOrErr) {
575 auto SecNameOrErr = getSectionName(&Sec);
576 if (!SecNameOrErr)
577 return SecNameOrErr.takeError();
578 if (*SecNameOrErr == SectionName)
579 return &Sec;
580 }
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100581 // TODO: this error is untested.
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100582 return createError("invalid section name");
583}
584
585template <class ELFT>
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100586Expected<StringRef>
587ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
588 if (Section->sh_type != ELF::SHT_STRTAB)
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100589 return createError("invalid sh_type for string table section " +
590 getSecIndexForError(this, Section) +
591 ": expected SHT_STRTAB, but got " +
592 object::getELFSectionTypeName(getHeader()->e_machine,
593 Section->sh_type));
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100594 auto V = getSectionContentsAsArray<char>(Section);
595 if (!V)
596 return V.takeError();
597 ArrayRef<char> Data = *V;
598 if (Data.empty())
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100599 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100600 return createError("empty string table");
601 if (Data.back() != '\0')
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100602 return createError(object::getELFSectionTypeName(getHeader()->e_machine,
603 Section->sh_type) +
604 " string table section " +
605 getSecIndexForError(this, Section) +
606 " is non-null terminated");
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100607 return StringRef(Data.begin(), Data.size());
608}
609
610template <class ELFT>
611Expected<ArrayRef<typename ELFT::Word>>
612ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
613 auto SectionsOrErr = sections();
614 if (!SectionsOrErr)
615 return SectionsOrErr.takeError();
616 return getSHNDXTable(Section, *SectionsOrErr);
617}
618
619template <class ELFT>
620Expected<ArrayRef<typename ELFT::Word>>
621ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section,
622 Elf_Shdr_Range Sections) const {
623 assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX);
624 auto VOrErr = getSectionContentsAsArray<Elf_Word>(&Section);
625 if (!VOrErr)
626 return VOrErr.takeError();
627 ArrayRef<Elf_Word> V = *VOrErr;
628 auto SymTableOrErr = object::getSection<ELFT>(Sections, Section.sh_link);
629 if (!SymTableOrErr)
630 return SymTableOrErr.takeError();
631 const Elf_Shdr &SymTable = **SymTableOrErr;
632 if (SymTable.sh_type != ELF::SHT_SYMTAB &&
633 SymTable.sh_type != ELF::SHT_DYNSYM)
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100634 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100635 return createError("invalid sh_type");
636 if (V.size() != (SymTable.sh_size / sizeof(Elf_Sym)))
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100637 return createError("SHT_SYMTAB_SHNDX section has sh_size (" +
638 Twine(SymTable.sh_size) +
639 ") which is not equal to the number of symbols (" +
640 Twine(V.size()) + ")");
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100641 return V;
642}
643
644template <class ELFT>
645Expected<StringRef>
646ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
647 auto SectionsOrErr = sections();
648 if (!SectionsOrErr)
649 return SectionsOrErr.takeError();
650 return getStringTableForSymtab(Sec, *SectionsOrErr);
651}
652
653template <class ELFT>
654Expected<StringRef>
655ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec,
656 Elf_Shdr_Range Sections) const {
657
658 if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100659 // TODO: this error is untested.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100660 return createError(
661 "invalid sh_type for symbol table, expected SHT_SYMTAB or SHT_DYNSYM");
662 auto SectionOrErr = object::getSection<ELFT>(Sections, Sec.sh_link);
663 if (!SectionOrErr)
664 return SectionOrErr.takeError();
665 return getStringTable(*SectionOrErr);
666}
667
668template <class ELFT>
669Expected<StringRef>
670ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
671 auto SectionsOrErr = sections();
672 if (!SectionsOrErr)
673 return SectionsOrErr.takeError();
674 auto Table = getSectionStringTable(*SectionsOrErr);
675 if (!Table)
676 return Table.takeError();
677 return getSectionName(Section, *Table);
678}
679
680template <class ELFT>
681Expected<StringRef> ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section,
682 StringRef DotShstrtab) const {
683 uint32_t Offset = Section->sh_name;
684 if (Offset == 0)
685 return StringRef();
686 if (Offset >= DotShstrtab.size())
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100687 return createError("a section " + getSecIndexForError(this, Section) +
688 " has an invalid sh_name (0x" +
689 Twine::utohexstr(Offset) +
690 ") offset which goes past the end of the "
691 "section name string table");
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100692 return StringRef(DotShstrtab.data() + Offset);
693}
694
695/// This function returns the hash value for a symbol in the .dynsym section
696/// Name of the API remains consistent as specified in the libelf
697/// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
698inline unsigned hashSysV(StringRef SymbolName) {
699 unsigned h = 0, g;
700 for (char C : SymbolName) {
701 h = (h << 4) + C;
702 g = h & 0xf0000000L;
703 if (g != 0)
704 h ^= g >> 24;
705 h &= ~g;
706 }
707 return h;
708}
709
710} // end namespace object
711} // end namespace llvm
712
713#endif // LLVM_OBJECT_ELF_H