LLVM 18.0.0git
ELF.h
Go to the documentation of this file.
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/MapVector.h"
20#include "llvm/ADT/StringRef.h"
23#include "llvm/Object/Error.h"
24#include "llvm/Support/Error.h"
25#include <cassert>
26#include <cstddef>
27#include <cstdint>
28#include <limits>
29#include <utility>
30
31namespace llvm {
32namespace object {
33
34struct VerdAux {
35 unsigned Offset;
36 std::string Name;
37};
38
39struct VerDef {
40 unsigned Offset;
41 unsigned Version;
42 unsigned Flags;
43 unsigned Ndx;
44 unsigned Cnt;
45 unsigned Hash;
46 std::string Name;
47 std::vector<VerdAux> AuxV;
48};
49
50struct VernAux {
51 unsigned Hash;
52 unsigned Flags;
53 unsigned Other;
54 unsigned Offset;
55 std::string Name;
56};
57
58struct VerNeed {
59 unsigned Version;
60 unsigned Cnt;
61 unsigned Offset;
62 std::string File;
63 std::vector<VernAux> AuxV;
64};
65
67 std::string Name;
69};
70
74
75// Subclasses of ELFFile may need this for template instantiation
76inline std::pair<unsigned char, unsigned char>
78 if (Object.size() < ELF::EI_NIDENT)
79 return std::make_pair((uint8_t)ELF::ELFCLASSNONE,
80 (uint8_t)ELF::ELFDATANONE);
81 return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
82 (uint8_t)Object[ELF::EI_DATA]);
83}
84
86 PADDI_R12_NO_DISP = 0x0610000039800000,
90 PLD_R12_NO_DISP = 0x04100000E5800000,
91 MTCTR_R12 = 0x7D8903A6,
92 BCTR = 0x4E800420,
93};
94
95template <class ELFT> class ELFFile;
96
97template <class T> struct DataRegion {
98 // This constructor is used when we know the start and the size of a data
99 // region. We assume that Arr does not go past the end of the file.
100 DataRegion(ArrayRef<T> Arr) : First(Arr.data()), Size(Arr.size()) {}
101
102 // Sometimes we only know the start of a data region. We still don't want to
103 // read past the end of the file, so we provide the end of a buffer.
104 DataRegion(const T *Data, const uint8_t *BufferEnd)
105 : First(Data), BufEnd(BufferEnd) {}
106
108 assert(Size || BufEnd);
109 if (Size) {
110 if (N >= *Size)
111 return createError(
112 "the index is greater than or equal to the number of entries (" +
113 Twine(*Size) + ")");
114 } else {
115 const uint8_t *EntryStart = (const uint8_t *)First + N * sizeof(T);
116 if (EntryStart + sizeof(T) > BufEnd)
117 return createError("can't read past the end of the file");
118 }
119 return *(First + N);
120 }
121
122 const T *First;
123 std::optional<uint64_t> Size;
124 const uint8_t *BufEnd = nullptr;
125};
126
127template <class ELFT>
128std::string getSecIndexForError(const ELFFile<ELFT> &Obj,
129 const typename ELFT::Shdr &Sec) {
130 auto TableOrErr = Obj.sections();
131 if (TableOrErr)
132 return "[index " + std::to_string(&Sec - &TableOrErr->front()) + "]";
133 // To make this helper be more convenient for error reporting purposes we
134 // drop the error. But really it should never be triggered. Before this point,
135 // our code should have called 'sections()' and reported a proper error on
136 // failure.
137 llvm::consumeError(TableOrErr.takeError());
138 return "[unknown index]";
139}
140
141template <class ELFT>
142static std::string describe(const ELFFile<ELFT> &Obj,
143 const typename ELFT::Shdr &Sec) {
144 unsigned SecNdx = &Sec - &cantFail(Obj.sections()).front();
145 return (object::getELFSectionTypeName(Obj.getHeader().e_machine,
146 Sec.sh_type) +
147 " section with index " + Twine(SecNdx))
148 .str();
149}
150
151template <class ELFT>
152std::string getPhdrIndexForError(const ELFFile<ELFT> &Obj,
153 const typename ELFT::Phdr &Phdr) {
154 auto Headers = Obj.program_headers();
155 if (Headers)
156 return ("[index " + Twine(&Phdr - &Headers->front()) + "]").str();
157 // See comment in the getSecIndexForError() above.
158 llvm::consumeError(Headers.takeError());
159 return "[unknown index]";
160}
161
162static inline Error defaultWarningHandler(const Twine &Msg) {
163 return createError(Msg);
164}
165
166template <class ELFT>
167bool checkSectionOffsets(const typename ELFT::Phdr &Phdr,
168 const typename ELFT::Shdr &Sec) {
169 // SHT_NOBITS sections don't need to have an offset inside the segment.
170 if (Sec.sh_type == ELF::SHT_NOBITS)
171 return true;
172
173 if (Sec.sh_offset < Phdr.p_offset)
174 return false;
175
176 // Only non-empty sections can be at the end of a segment.
177 if (Sec.sh_size == 0)
178 return (Sec.sh_offset + 1 <= Phdr.p_offset + Phdr.p_filesz);
179 return Sec.sh_offset + Sec.sh_size <= Phdr.p_offset + Phdr.p_filesz;
180}
181
182// Check that an allocatable section belongs to a virtual address
183// space of a segment.
184template <class ELFT>
185bool checkSectionVMA(const typename ELFT::Phdr &Phdr,
186 const typename ELFT::Shdr &Sec) {
187 if (!(Sec.sh_flags & ELF::SHF_ALLOC))
188 return true;
189
190 if (Sec.sh_addr < Phdr.p_vaddr)
191 return false;
192
193 bool IsTbss =
194 (Sec.sh_type == ELF::SHT_NOBITS) && ((Sec.sh_flags & ELF::SHF_TLS) != 0);
195 // .tbss is special, it only has memory in PT_TLS and has NOBITS properties.
196 bool IsTbssInNonTLS = IsTbss && Phdr.p_type != ELF::PT_TLS;
197 // Only non-empty sections can be at the end of a segment.
198 if (Sec.sh_size == 0 || IsTbssInNonTLS)
199 return Sec.sh_addr + 1 <= Phdr.p_vaddr + Phdr.p_memsz;
200 return Sec.sh_addr + Sec.sh_size <= Phdr.p_vaddr + Phdr.p_memsz;
201}
202
203template <class ELFT>
204bool isSectionInSegment(const typename ELFT::Phdr &Phdr,
205 const typename ELFT::Shdr &Sec) {
206 return checkSectionOffsets<ELFT>(Phdr, Sec) &&
207 checkSectionVMA<ELFT>(Phdr, Sec);
208}
209
210template <class ELFT>
211class ELFFile {
212public:
214
215 // This is a callback that can be passed to a number of functions.
216 // It can be used to ignore non-critical errors (warnings), which is
217 // useful for dumpers, like llvm-readobj.
218 // It accepts a warning message string and returns a success
219 // when the warning should be ignored or an error otherwise.
221
222 const uint8_t *base() const { return Buf.bytes_begin(); }
223 const uint8_t *end() const { return base() + getBufSize(); }
224
225 size_t getBufSize() const { return Buf.size(); }
226
227private:
228 StringRef Buf;
229 std::vector<Elf_Shdr> FakeSections;
230 SmallString<0> FakeSectionStrings;
231
232 ELFFile(StringRef Object);
233
234public:
235 const Elf_Ehdr &getHeader() const {
236 return *reinterpret_cast<const Elf_Ehdr *>(base());
237 }
238
239 template <typename T>
240 Expected<const T *> getEntry(uint32_t Section, uint32_t Entry) const;
241 template <typename T>
242 Expected<const T *> getEntry(const Elf_Shdr &Section, uint32_t Entry) const;
243
245 getVersionDefinitions(const Elf_Shdr &Sec) const;
247 const Elf_Shdr &Sec,
248 WarningHandler WarnHandler = &defaultWarningHandler) const;
250 uint32_t SymbolVersionIndex, bool &IsDefault,
251 SmallVector<std::optional<VersionEntry>, 0> &VersionMap,
252 std::optional<bool> IsSymHidden) const;
253
255 getStringTable(const Elf_Shdr &Section,
256 WarningHandler WarnHandler = &defaultWarningHandler) const;
257 Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
258 Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section,
259 Elf_Shdr_Range Sections) const;
260 Expected<StringRef> getLinkAsStrtab(const typename ELFT::Shdr &Sec) const;
261
262 Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section) const;
263 Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section,
264 Elf_Shdr_Range Sections) const;
265
267
270 SmallVectorImpl<char> &Result) const;
272
273 std::string getDynamicTagAsString(unsigned Arch, uint64_t Type) const;
274 std::string getDynamicTagAsString(uint64_t Type) const;
275
276 /// Get the symbol for a given relocation.
278 const Elf_Shdr *SymTab) const;
279
281 loadVersionMap(const Elf_Shdr *VerNeedSec, const Elf_Shdr *VerDefSec) const;
282
283 static Expected<ELFFile> create(StringRef Object);
284
285 bool isLE() const {
286 return getHeader().getDataEncoding() == ELF::ELFDATA2LSB;
287 }
288
289 bool isMipsELF64() const {
290 return getHeader().e_machine == ELF::EM_MIPS &&
291 getHeader().getFileClass() == ELF::ELFCLASS64;
292 }
293
294 bool isMips64EL() const { return isMipsELF64() && isLE(); }
295
297
299
302 WarningHandler WarnHandler = &defaultWarningHandler) const;
303
304 Expected<Elf_Sym_Range> symbols(const Elf_Shdr *Sec) const {
305 if (!Sec)
306 return ArrayRef<Elf_Sym>(nullptr, nullptr);
307 return getSectionContentsAsArray<Elf_Sym>(*Sec);
308 }
309
310 Expected<Elf_Rela_Range> relas(const Elf_Shdr &Sec) const {
311 return getSectionContentsAsArray<Elf_Rela>(Sec);
312 }
313
314 Expected<Elf_Rel_Range> rels(const Elf_Shdr &Sec) const {
315 return getSectionContentsAsArray<Elf_Rel>(Sec);
316 }
317
318 Expected<Elf_Relr_Range> relrs(const Elf_Shdr &Sec) const {
319 return getSectionContentsAsArray<Elf_Relr>(Sec);
320 }
321
322 std::vector<Elf_Rel> decode_relrs(Elf_Relr_Range relrs) const;
323
324 Expected<std::vector<Elf_Rela>> android_relas(const Elf_Shdr &Sec) const;
325
326 /// Iterate over program header table.
328 if (getHeader().e_phnum && getHeader().e_phentsize != sizeof(Elf_Phdr))
329 return createError("invalid e_phentsize: " +
330 Twine(getHeader().e_phentsize));
331
332 uint64_t HeadersSize =
333 (uint64_t)getHeader().e_phnum * getHeader().e_phentsize;
334 uint64_t PhOff = getHeader().e_phoff;
335 if (PhOff + HeadersSize < PhOff || PhOff + HeadersSize > getBufSize())
336 return createError("program headers are longer than binary of size " +
337 Twine(getBufSize()) + ": e_phoff = 0x" +
338 Twine::utohexstr(getHeader().e_phoff) +
339 ", e_phnum = " + Twine(getHeader().e_phnum) +
340 ", e_phentsize = " + Twine(getHeader().e_phentsize));
341
342 auto *Begin = reinterpret_cast<const Elf_Phdr *>(base() + PhOff);
343 return ArrayRef(Begin, Begin + getHeader().e_phnum);
344 }
345
346 /// Get an iterator over notes in a program header.
347 ///
348 /// The program header must be of type \c PT_NOTE.
349 ///
350 /// \param Phdr the program header to iterate over.
351 /// \param Err [out] an error to support fallible iteration, which should
352 /// be checked after iteration ends.
353 Elf_Note_Iterator notes_begin(const Elf_Phdr &Phdr, Error &Err) const {
354 assert(Phdr.p_type == ELF::PT_NOTE && "Phdr is not of type PT_NOTE");
355 ErrorAsOutParameter ErrAsOutParam(&Err);
356 if (Phdr.p_offset + Phdr.p_filesz > getBufSize()) {
357 Err =
358 createError("invalid offset (0x" + Twine::utohexstr(Phdr.p_offset) +
359 ") or size (0x" + Twine::utohexstr(Phdr.p_filesz) + ")");
360 return Elf_Note_Iterator(Err);
361 }
362 // Allow 4, 8, and (for Linux core dumps) 0.
363 // TODO: Disallow 1 after all tests are fixed.
364 if (Phdr.p_align != 0 && Phdr.p_align != 1 && Phdr.p_align != 4 &&
365 Phdr.p_align != 8) {
366 Err =
367 createError("alignment (" + Twine(Phdr.p_align) + ") is not 4 or 8");
368 return Elf_Note_Iterator(Err);
369 }
370 return Elf_Note_Iterator(base() + Phdr.p_offset, Phdr.p_filesz,
371 std::max<size_t>(Phdr.p_align, 4), Err);
372 }
373
374 /// Get an iterator over notes in a section.
375 ///
376 /// The section must be of type \c SHT_NOTE.
377 ///
378 /// \param Shdr the section to iterate over.
379 /// \param Err [out] an error to support fallible iteration, which should
380 /// be checked after iteration ends.
381 Elf_Note_Iterator notes_begin(const Elf_Shdr &Shdr, Error &Err) const {
382 assert(Shdr.sh_type == ELF::SHT_NOTE && "Shdr is not of type SHT_NOTE");
383 ErrorAsOutParameter ErrAsOutParam(&Err);
384 if (Shdr.sh_offset + Shdr.sh_size > getBufSize()) {
385 Err =
386 createError("invalid offset (0x" + Twine::utohexstr(Shdr.sh_offset) +
387 ") or size (0x" + Twine::utohexstr(Shdr.sh_size) + ")");
388 return Elf_Note_Iterator(Err);
389 }
390 // TODO: Allow just 4 and 8 after all tests are fixed.
391 if (Shdr.sh_addralign != 0 && Shdr.sh_addralign != 1 &&
392 Shdr.sh_addralign != 4 && Shdr.sh_addralign != 8) {
393 Err = createError("alignment (" + Twine(Shdr.sh_addralign) +
394 ") is not 4 or 8");
395 return Elf_Note_Iterator(Err);
396 }
397 return Elf_Note_Iterator(base() + Shdr.sh_offset, Shdr.sh_size,
398 std::max<size_t>(Shdr.sh_addralign, 4), Err);
399 }
400
401 /// Get the end iterator for notes.
402 Elf_Note_Iterator notes_end() const {
403 return Elf_Note_Iterator();
404 }
405
406 /// Get an iterator range over notes of a program header.
407 ///
408 /// The program header must be of type \c PT_NOTE.
409 ///
410 /// \param Phdr the program header to iterate over.
411 /// \param Err [out] an error to support fallible iteration, which should
412 /// be checked after iteration ends.
414 Error &Err) const {
415 return make_range(notes_begin(Phdr, Err), notes_end());
416 }
417
418 /// Get an iterator range over notes of a section.
419 ///
420 /// The section must be of type \c SHT_NOTE.
421 ///
422 /// \param Shdr the section to iterate over.
423 /// \param Err [out] an error to support fallible iteration, which should
424 /// be checked after iteration ends.
426 Error &Err) const {
427 return make_range(notes_begin(Shdr, Err), notes_end());
428 }
429
431 Elf_Shdr_Range Sections,
432 WarningHandler WarnHandler = &defaultWarningHandler) const;
433 Expected<uint32_t> getSectionIndex(const Elf_Sym &Sym, Elf_Sym_Range Syms,
434 DataRegion<Elf_Word> ShndxTable) const;
436 const Elf_Shdr *SymTab,
437 DataRegion<Elf_Word> ShndxTable) const;
439 Elf_Sym_Range Symtab,
440 DataRegion<Elf_Word> ShndxTable) const;
442
443 Expected<const Elf_Sym *> getSymbol(const Elf_Shdr *Sec,
444 uint32_t Index) const;
445
447 getSectionName(const Elf_Shdr &Section,
448 WarningHandler WarnHandler = &defaultWarningHandler) const;
449 Expected<StringRef> getSectionName(const Elf_Shdr &Section,
450 StringRef DotShstrtab) const;
451 template <typename T>
452 Expected<ArrayRef<T>> getSectionContentsAsArray(const Elf_Shdr &Sec) const;
453 Expected<ArrayRef<uint8_t>> getSectionContents(const Elf_Shdr &Sec) const;
454 Expected<ArrayRef<uint8_t>> getSegmentContents(const Elf_Phdr &Phdr) const;
455
456 /// Returns a vector of BBAddrMap structs corresponding to each function
457 /// within the text section that the SHT_LLVM_BB_ADDR_MAP section \p Sec
458 /// is associated with. If the current ELFFile is relocatable, a corresponding
459 /// \p RelaSec must be passed in as an argument.
461 decodeBBAddrMap(const Elf_Shdr &Sec, const Elf_Shdr *RelaSec = nullptr) const;
462
463 /// Returns a map from every section matching \p IsMatch to its relocation
464 /// section, or \p nullptr if it has no relocation section. This function
465 /// returns an error if any of the \p IsMatch calls fail or if it fails to
466 /// retrieve the content section of any relocation section.
469 std::function<Expected<bool>(const Elf_Shdr &)> IsMatch) const;
470
471 void createFakeSections();
472};
473
478
479template <class ELFT>
481getSection(typename ELFT::ShdrRange Sections, uint32_t Index) {
482 if (Index >= Sections.size())
483 return createError("invalid section index: " + Twine(Index));
484 return &Sections[Index];
485}
486
487template <class ELFT>
489getExtendedSymbolTableIndex(const typename ELFT::Sym &Sym, unsigned SymIndex,
491 assert(Sym.st_shndx == ELF::SHN_XINDEX);
492 if (!ShndxTable.First)
493 return createError(
494 "found an extended symbol index (" + Twine(SymIndex) +
495 "), but unable to locate the extended symbol index table");
496
497 Expected<typename ELFT::Word> TableOrErr = ShndxTable[SymIndex];
498 if (!TableOrErr)
499 return createError("unable to read an extended symbol table at index " +
500 Twine(SymIndex) + ": " +
501 toString(TableOrErr.takeError()));
502 return *TableOrErr;
503}
504
505template <class ELFT>
507ELFFile<ELFT>::getSectionIndex(const Elf_Sym &Sym, Elf_Sym_Range Syms,
508 DataRegion<Elf_Word> ShndxTable) const {
509 uint32_t Index = Sym.st_shndx;
510 if (Index == ELF::SHN_XINDEX) {
511 Expected<uint32_t> ErrorOrIndex =
512 getExtendedSymbolTableIndex<ELFT>(Sym, &Sym - Syms.begin(), ShndxTable);
513 if (!ErrorOrIndex)
514 return ErrorOrIndex.takeError();
515 return *ErrorOrIndex;
516 }
518 return 0;
519 return Index;
520}
521
522template <class ELFT>
524ELFFile<ELFT>::getSection(const Elf_Sym &Sym, const Elf_Shdr *SymTab,
525 DataRegion<Elf_Word> ShndxTable) const {
526 auto SymsOrErr = symbols(SymTab);
527 if (!SymsOrErr)
528 return SymsOrErr.takeError();
529 return getSection(Sym, *SymsOrErr, ShndxTable);
530}
531
532template <class ELFT>
534ELFFile<ELFT>::getSection(const Elf_Sym &Sym, Elf_Sym_Range Symbols,
535 DataRegion<Elf_Word> ShndxTable) const {
536 auto IndexOrErr = getSectionIndex(Sym, Symbols, ShndxTable);
537 if (!IndexOrErr)
538 return IndexOrErr.takeError();
539 uint32_t Index = *IndexOrErr;
540 if (Index == 0)
541 return nullptr;
542 return getSection(Index);
543}
544
545template <class ELFT>
547ELFFile<ELFT>::getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
548 auto SymsOrErr = symbols(Sec);
549 if (!SymsOrErr)
550 return SymsOrErr.takeError();
551
552 Elf_Sym_Range Symbols = *SymsOrErr;
553 if (Index >= Symbols.size())
554 return createError("unable to get symbol from section " +
555 getSecIndexForError(*this, *Sec) +
556 ": invalid symbol index (" + Twine(Index) + ")");
557 return &Symbols[Index];
558}
559
560template <class ELFT>
561template <typename T>
564 if (Sec.sh_entsize != sizeof(T) && sizeof(T) != 1)
565 return createError("section " + getSecIndexForError(*this, Sec) +
566 " has invalid sh_entsize: expected " + Twine(sizeof(T)) +
567 ", but got " + Twine(Sec.sh_entsize));
568
569 uintX_t Offset = Sec.sh_offset;
570 uintX_t Size = Sec.sh_size;
571
572 if (Size % sizeof(T))
573 return createError("section " + getSecIndexForError(*this, Sec) +
574 " has an invalid sh_size (" + Twine(Size) +
575 ") which is not a multiple of its sh_entsize (" +
576 Twine(Sec.sh_entsize) + ")");
577 if (std::numeric_limits<uintX_t>::max() - Offset < Size)
578 return createError("section " + getSecIndexForError(*this, Sec) +
579 " has a sh_offset (0x" + Twine::utohexstr(Offset) +
580 ") + sh_size (0x" + Twine::utohexstr(Size) +
581 ") that cannot be represented");
582 if (Offset + Size > Buf.size())
583 return createError("section " + getSecIndexForError(*this, Sec) +
584 " has a sh_offset (0x" + Twine::utohexstr(Offset) +
585 ") + sh_size (0x" + Twine::utohexstr(Size) +
586 ") that is greater than the file size (0x" +
587 Twine::utohexstr(Buf.size()) + ")");
588
589 if (Offset % alignof(T))
590 // TODO: this error is untested.
591 return createError("unaligned data");
592
593 const T *Start = reinterpret_cast<const T *>(base() + Offset);
594 return ArrayRef(Start, Size / sizeof(T));
595}
596
597template <class ELFT>
599ELFFile<ELFT>::getSegmentContents(const Elf_Phdr &Phdr) const {
600 uintX_t Offset = Phdr.p_offset;
601 uintX_t Size = Phdr.p_filesz;
602
603 if (std::numeric_limits<uintX_t>::max() - Offset < Size)
604 return createError("program header " + getPhdrIndexForError(*this, Phdr) +
605 " has a p_offset (0x" + Twine::utohexstr(Offset) +
606 ") + p_filesz (0x" + Twine::utohexstr(Size) +
607 ") that cannot be represented");
608 if (Offset + Size > Buf.size())
609 return createError("program header " + getPhdrIndexForError(*this, Phdr) +
610 " has a p_offset (0x" + Twine::utohexstr(Offset) +
611 ") + p_filesz (0x" + Twine::utohexstr(Size) +
612 ") that is greater than the file size (0x" +
613 Twine::utohexstr(Buf.size()) + ")");
614 return ArrayRef(base() + Offset, Size);
615}
616
617template <class ELFT>
619ELFFile<ELFT>::getSectionContents(const Elf_Shdr &Sec) const {
620 return getSectionContentsAsArray<uint8_t>(Sec);
621}
622
623template <class ELFT>
625 return getELFRelocationTypeName(getHeader().e_machine, Type);
626}
627
628template <class ELFT>
630 SmallVectorImpl<char> &Result) const {
631 if (!isMipsELF64()) {
632 StringRef Name = getRelocationTypeName(Type);
633 Result.append(Name.begin(), Name.end());
634 } else {
635 // The Mips N64 ABI allows up to three operations to be specified per
636 // relocation record. Unfortunately there's no easy way to test for the
637 // presence of N64 ELFs as they have no special flag that identifies them
638 // as being N64. We can safely assume at the moment that all Mips
639 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
640 // information to disambiguate between old vs new ABIs.
641 uint8_t Type1 = (Type >> 0) & 0xFF;
642 uint8_t Type2 = (Type >> 8) & 0xFF;
643 uint8_t Type3 = (Type >> 16) & 0xFF;
644
645 // Concat all three relocation type names.
646 StringRef Name = getRelocationTypeName(Type1);
647 Result.append(Name.begin(), Name.end());
648
649 Name = getRelocationTypeName(Type2);
650 Result.append(1, '/');
651 Result.append(Name.begin(), Name.end());
652
653 Name = getRelocationTypeName(Type3);
654 Result.append(1, '/');
655 Result.append(Name.begin(), Name.end());
656 }
657}
658
659template <class ELFT>
661 return getELFRelativeRelocationType(getHeader().e_machine);
662}
663
664template <class ELFT>
666ELFFile<ELFT>::loadVersionMap(const Elf_Shdr *VerNeedSec,
667 const Elf_Shdr *VerDefSec) const {
669
670 // The first two version indexes are reserved.
671 // Index 0 is VER_NDX_LOCAL, index 1 is VER_NDX_GLOBAL.
672 VersionMap.push_back(VersionEntry());
673 VersionMap.push_back(VersionEntry());
674
675 auto InsertEntry = [&](unsigned N, StringRef Version, bool IsVerdef) {
676 if (N >= VersionMap.size())
677 VersionMap.resize(N + 1);
678 VersionMap[N] = {std::string(Version), IsVerdef};
679 };
680
681 if (VerDefSec) {
682 Expected<std::vector<VerDef>> Defs = getVersionDefinitions(*VerDefSec);
683 if (!Defs)
684 return Defs.takeError();
685 for (const VerDef &Def : *Defs)
686 InsertEntry(Def.Ndx & ELF::VERSYM_VERSION, Def.Name, true);
687 }
688
689 if (VerNeedSec) {
690 Expected<std::vector<VerNeed>> Deps = getVersionDependencies(*VerNeedSec);
691 if (!Deps)
692 return Deps.takeError();
693 for (const VerNeed &Dep : *Deps)
694 for (const VernAux &Aux : Dep.AuxV)
695 InsertEntry(Aux.Other & ELF::VERSYM_VERSION, Aux.Name, false);
696 }
697
698 return VersionMap;
699}
700
701template <class ELFT>
704 const Elf_Shdr *SymTab) const {
705 uint32_t Index = Rel.getSymbol(isMips64EL());
706 if (Index == 0)
707 return nullptr;
708 return getEntry<Elf_Sym>(*SymTab, Index);
709}
710
711template <class ELFT>
714 WarningHandler WarnHandler) const {
715 uint32_t Index = getHeader().e_shstrndx;
716 if (Index == ELF::SHN_XINDEX) {
717 // If the section name string table section index is greater than
718 // or equal to SHN_LORESERVE, then the actual index of the section name
719 // string table section is contained in the sh_link field of the section
720 // header at index 0.
721 if (Sections.empty())
722 return createError(
723 "e_shstrndx == SHN_XINDEX, but the section header table is empty");
724
725 Index = Sections[0].sh_link;
726 }
727
728 // There is no section name string table. Return FakeSectionStrings which
729 // is non-empty if we have created fake sections.
730 if (!Index)
731 return FakeSectionStrings;
732
733 if (Index >= Sections.size())
734 return createError("section header string table index " + Twine(Index) +
735 " does not exist");
736 return getStringTable(Sections[Index], WarnHandler);
737}
738
739/// This function finds the number of dynamic symbols using a GNU hash table.
740///
741/// @param Table The GNU hash table for .dynsym.
742template <class ELFT>
744getDynSymtabSizeFromGnuHash(const typename ELFT::GnuHash &Table,
745 const void *BufEnd) {
746 using Elf_Word = typename ELFT::Word;
747 if (Table.nbuckets == 0)
748 return Table.symndx + 1;
749 uint64_t LastSymIdx = 0;
750 // Find the index of the first symbol in the last chain.
751 for (Elf_Word Val : Table.buckets())
752 LastSymIdx = std::max(LastSymIdx, (uint64_t)Val);
753 const Elf_Word *It =
754 reinterpret_cast<const Elf_Word *>(Table.values(LastSymIdx).end());
755 // Locate the end of the chain to find the last symbol index.
756 while (It < BufEnd && (*It & 1) == 0) {
757 ++LastSymIdx;
758 ++It;
759 }
760 if (It >= BufEnd) {
761 return createStringError(
763 "no terminator found for GNU hash section before buffer end");
764 }
765 return LastSymIdx + 1;
766}
767
768/// This function determines the number of dynamic symbols. It reads section
769/// headers first. If section headers are not available, the number of
770/// symbols will be inferred by parsing dynamic hash tables.
771template <class ELFT>
773 // Read .dynsym section header first if available.
774 Expected<Elf_Shdr_Range> SectionsOrError = sections();
775 if (!SectionsOrError)
776 return SectionsOrError.takeError();
777 for (const Elf_Shdr &Sec : *SectionsOrError) {
778 if (Sec.sh_type == ELF::SHT_DYNSYM) {
779 if (Sec.sh_size % Sec.sh_entsize != 0) {
781 "SHT_DYNSYM section has sh_size (" +
782 Twine(Sec.sh_size) + ") % sh_entsize (" +
783 Twine(Sec.sh_entsize) + ") that is not 0");
784 }
785 return Sec.sh_size / Sec.sh_entsize;
786 }
787 }
788
789 if (!SectionsOrError->empty()) {
790 // Section headers are available but .dynsym header is not found.
791 // Return 0 as .dynsym does not exist.
792 return 0;
793 }
794
795 // Section headers do not exist. Falling back to infer
796 // upper bound of .dynsym from .gnu.hash and .hash.
797 Expected<Elf_Dyn_Range> DynTable = dynamicEntries();
798 if (!DynTable)
799 return DynTable.takeError();
800 std::optional<uint64_t> ElfHash;
801 std::optional<uint64_t> ElfGnuHash;
802 for (const Elf_Dyn &Entry : *DynTable) {
803 switch (Entry.d_tag) {
804 case ELF::DT_HASH:
805 ElfHash = Entry.d_un.d_ptr;
806 break;
807 case ELF::DT_GNU_HASH:
808 ElfGnuHash = Entry.d_un.d_ptr;
809 break;
810 }
811 }
812 if (ElfGnuHash) {
813 Expected<const uint8_t *> TablePtr = toMappedAddr(*ElfGnuHash);
814 if (!TablePtr)
815 return TablePtr.takeError();
816 const Elf_GnuHash *Table =
817 reinterpret_cast<const Elf_GnuHash *>(TablePtr.get());
818 return getDynSymtabSizeFromGnuHash<ELFT>(*Table, this->Buf.bytes_end());
819 }
820
821 // Search SYSV hash table to try to find the upper bound of dynsym.
822 if (ElfHash) {
823 Expected<const uint8_t *> TablePtr = toMappedAddr(*ElfHash);
824 if (!TablePtr)
825 return TablePtr.takeError();
826 const Elf_Hash *Table = reinterpret_cast<const Elf_Hash *>(TablePtr.get());
827 return Table->nchain;
828 }
829 return 0;
830}
831
832template <class ELFT> ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {}
833
834template <class ELFT>
836 if (sizeof(Elf_Ehdr) > Object.size())
837 return createError("invalid buffer: the size (" + Twine(Object.size()) +
838 ") is smaller than an ELF header (" +
839 Twine(sizeof(Elf_Ehdr)) + ")");
840 return ELFFile(Object);
841}
842
843/// Used by llvm-objdump -d (which needs sections for disassembly) to
844/// disassemble objects without a section header table (e.g. ET_CORE objects
845/// analyzed by linux perf or ET_EXEC with llvm-strip --strip-sections).
846template <class ELFT> void ELFFile<ELFT>::createFakeSections() {
847 if (!FakeSections.empty())
848 return;
849 auto PhdrsOrErr = program_headers();
850 if (!PhdrsOrErr)
851 return;
852
853 FakeSectionStrings += '\0';
854 for (auto [Idx, Phdr] : llvm::enumerate(*PhdrsOrErr)) {
855 if (Phdr.p_type != ELF::PT_LOAD || !(Phdr.p_flags & ELF::PF_X))
856 continue;
857 Elf_Shdr FakeShdr = {};
858 FakeShdr.sh_type = ELF::SHT_PROGBITS;
859 FakeShdr.sh_flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
860 FakeShdr.sh_addr = Phdr.p_vaddr;
861 FakeShdr.sh_size = Phdr.p_memsz;
862 FakeShdr.sh_offset = Phdr.p_offset;
863 // Create a section name based on the p_type and index.
864 FakeShdr.sh_name = FakeSectionStrings.size();
865 FakeSectionStrings += ("PT_LOAD#" + Twine(Idx)).str();
866 FakeSectionStrings += '\0';
867 FakeSections.push_back(FakeShdr);
868 }
869}
870
871template <class ELFT>
873 const uintX_t SectionTableOffset = getHeader().e_shoff;
874 if (SectionTableOffset == 0) {
875 if (!FakeSections.empty())
876 return ArrayRef(FakeSections.data(), FakeSections.size());
877 return ArrayRef<Elf_Shdr>();
878 }
879
880 if (getHeader().e_shentsize != sizeof(Elf_Shdr))
881 return createError("invalid e_shentsize in ELF header: " +
882 Twine(getHeader().e_shentsize));
883
884 const uint64_t FileSize = Buf.size();
885 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize ||
886 SectionTableOffset + (uintX_t)sizeof(Elf_Shdr) < SectionTableOffset)
887 return createError(
888 "section header table goes past the end of the file: e_shoff = 0x" +
889 Twine::utohexstr(SectionTableOffset));
890
891 // Invalid address alignment of section headers
892 if (SectionTableOffset & (alignof(Elf_Shdr) - 1))
893 // TODO: this error is untested.
894 return createError("invalid alignment of section headers");
895
896 const Elf_Shdr *First =
897 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
898
899 uintX_t NumSections = getHeader().e_shnum;
900 if (NumSections == 0)
901 NumSections = First->sh_size;
902
903 if (NumSections > UINT64_MAX / sizeof(Elf_Shdr))
904 return createError("invalid number of sections specified in the NULL "
905 "section's sh_size field (" +
906 Twine(NumSections) + ")");
907
908 const uint64_t SectionTableSize = NumSections * sizeof(Elf_Shdr);
909 if (SectionTableOffset + SectionTableSize < SectionTableOffset)
910 return createError(
911 "invalid section header table offset (e_shoff = 0x" +
912 Twine::utohexstr(SectionTableOffset) +
913 ") or invalid number of sections specified in the first section "
914 "header's sh_size field (0x" +
915 Twine::utohexstr(NumSections) + ")");
916
917 // Section table goes past end of file!
918 if (SectionTableOffset + SectionTableSize > FileSize)
919 return createError("section table goes past the end of file");
920 return ArrayRef(First, NumSections);
921}
922
923template <class ELFT>
924template <typename T>
926 uint32_t Entry) const {
927 auto SecOrErr = getSection(Section);
928 if (!SecOrErr)
929 return SecOrErr.takeError();
930 return getEntry<T>(**SecOrErr, Entry);
931}
932
933template <class ELFT>
934template <typename T>
936 uint32_t Entry) const {
937 Expected<ArrayRef<T>> EntriesOrErr = getSectionContentsAsArray<T>(Section);
938 if (!EntriesOrErr)
939 return EntriesOrErr.takeError();
940
941 ArrayRef<T> Arr = *EntriesOrErr;
942 if (Entry >= Arr.size())
943 return createError(
944 "can't read an entry at 0x" +
945 Twine::utohexstr(Entry * static_cast<uint64_t>(sizeof(T))) +
946 ": it goes past the end of the section (0x" +
947 Twine::utohexstr(Section.sh_size) + ")");
948 return &Arr[Entry];
949}
950
951template <typename ELFT>
953 uint32_t SymbolVersionIndex, bool &IsDefault,
954 SmallVector<std::optional<VersionEntry>, 0> &VersionMap,
955 std::optional<bool> IsSymHidden) const {
956 size_t VersionIndex = SymbolVersionIndex & llvm::ELF::VERSYM_VERSION;
957
958 // Special markers for unversioned symbols.
959 if (VersionIndex == llvm::ELF::VER_NDX_LOCAL ||
960 VersionIndex == llvm::ELF::VER_NDX_GLOBAL) {
961 IsDefault = false;
962 return "";
963 }
964
965 // Lookup this symbol in the version table.
966 if (VersionIndex >= VersionMap.size() || !VersionMap[VersionIndex])
967 return createError("SHT_GNU_versym section refers to a version index " +
968 Twine(VersionIndex) + " which is missing");
969
970 const VersionEntry &Entry = *VersionMap[VersionIndex];
971 // A default version (@@) is only available for defined symbols.
972 if (!Entry.IsVerDef || IsSymHidden.value_or(false))
973 IsDefault = false;
974 else
975 IsDefault = !(SymbolVersionIndex & llvm::ELF::VERSYM_HIDDEN);
976 return Entry.Name.c_str();
977}
978
979template <class ELFT>
981ELFFile<ELFT>::getVersionDefinitions(const Elf_Shdr &Sec) const {
982 Expected<StringRef> StrTabOrErr = getLinkAsStrtab(Sec);
983 if (!StrTabOrErr)
984 return StrTabOrErr.takeError();
985
986 Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec);
987 if (!ContentsOrErr)
988 return createError("cannot read content of " + describe(*this, Sec) + ": " +
989 toString(ContentsOrErr.takeError()));
990
991 const uint8_t *Start = ContentsOrErr->data();
992 const uint8_t *End = Start + ContentsOrErr->size();
993
994 auto ExtractNextAux = [&](const uint8_t *&VerdauxBuf,
995 unsigned VerDefNdx) -> Expected<VerdAux> {
996 if (VerdauxBuf + sizeof(Elf_Verdaux) > End)
997 return createError("invalid " + describe(*this, Sec) +
998 ": version definition " + Twine(VerDefNdx) +
999 " refers to an auxiliary entry that goes past the end "
1000 "of the section");
1001
1002 auto *Verdaux = reinterpret_cast<const Elf_Verdaux *>(VerdauxBuf);
1003 VerdauxBuf += Verdaux->vda_next;
1004
1005 VerdAux Aux;
1006 Aux.Offset = VerdauxBuf - Start;
1007 if (Verdaux->vda_name <= StrTabOrErr->size())
1008 Aux.Name = std::string(StrTabOrErr->drop_front(Verdaux->vda_name));
1009 else
1010 Aux.Name = ("<invalid vda_name: " + Twine(Verdaux->vda_name) + ">").str();
1011 return Aux;
1012 };
1013
1014 std::vector<VerDef> Ret;
1015 const uint8_t *VerdefBuf = Start;
1016 for (unsigned I = 1; I <= /*VerDefsNum=*/Sec.sh_info; ++I) {
1017 if (VerdefBuf + sizeof(Elf_Verdef) > End)
1018 return createError("invalid " + describe(*this, Sec) +
1019 ": version definition " + Twine(I) +
1020 " goes past the end of the section");
1021
1022 if (reinterpret_cast<uintptr_t>(VerdefBuf) % sizeof(uint32_t) != 0)
1023 return createError(
1024 "invalid " + describe(*this, Sec) +
1025 ": found a misaligned version definition entry at offset 0x" +
1026 Twine::utohexstr(VerdefBuf - Start));
1027
1028 unsigned Version = *reinterpret_cast<const Elf_Half *>(VerdefBuf);
1029 if (Version != 1)
1030 return createError("unable to dump " + describe(*this, Sec) +
1031 ": version " + Twine(Version) +
1032 " is not yet supported");
1033
1034 const Elf_Verdef *D = reinterpret_cast<const Elf_Verdef *>(VerdefBuf);
1035 VerDef &VD = *Ret.emplace(Ret.end());
1036 VD.Offset = VerdefBuf - Start;
1037 VD.Version = D->vd_version;
1038 VD.Flags = D->vd_flags;
1039 VD.Ndx = D->vd_ndx;
1040 VD.Cnt = D->vd_cnt;
1041 VD.Hash = D->vd_hash;
1042
1043 const uint8_t *VerdauxBuf = VerdefBuf + D->vd_aux;
1044 for (unsigned J = 0; J < D->vd_cnt; ++J) {
1045 if (reinterpret_cast<uintptr_t>(VerdauxBuf) % sizeof(uint32_t) != 0)
1046 return createError("invalid " + describe(*this, Sec) +
1047 ": found a misaligned auxiliary entry at offset 0x" +
1048 Twine::utohexstr(VerdauxBuf - Start));
1049
1050 Expected<VerdAux> AuxOrErr = ExtractNextAux(VerdauxBuf, I);
1051 if (!AuxOrErr)
1052 return AuxOrErr.takeError();
1053
1054 if (J == 0)
1055 VD.Name = AuxOrErr->Name;
1056 else
1057 VD.AuxV.push_back(*AuxOrErr);
1058 }
1059
1060 VerdefBuf += D->vd_next;
1061 }
1062
1063 return Ret;
1064}
1065
1066template <class ELFT>
1069 WarningHandler WarnHandler) const {
1070 StringRef StrTab;
1071 Expected<StringRef> StrTabOrErr = getLinkAsStrtab(Sec);
1072 if (!StrTabOrErr) {
1073 if (Error E = WarnHandler(toString(StrTabOrErr.takeError())))
1074 return std::move(E);
1075 } else {
1076 StrTab = *StrTabOrErr;
1077 }
1078
1079 Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec);
1080 if (!ContentsOrErr)
1081 return createError("cannot read content of " + describe(*this, Sec) + ": " +
1082 toString(ContentsOrErr.takeError()));
1083
1084 const uint8_t *Start = ContentsOrErr->data();
1085 const uint8_t *End = Start + ContentsOrErr->size();
1086 const uint8_t *VerneedBuf = Start;
1087
1088 std::vector<VerNeed> Ret;
1089 for (unsigned I = 1; I <= /*VerneedNum=*/Sec.sh_info; ++I) {
1090 if (VerneedBuf + sizeof(Elf_Verdef) > End)
1091 return createError("invalid " + describe(*this, Sec) +
1092 ": version dependency " + Twine(I) +
1093 " goes past the end of the section");
1094
1095 if (reinterpret_cast<uintptr_t>(VerneedBuf) % sizeof(uint32_t) != 0)
1096 return createError(
1097 "invalid " + describe(*this, Sec) +
1098 ": found a misaligned version dependency entry at offset 0x" +
1099 Twine::utohexstr(VerneedBuf - Start));
1100
1101 unsigned Version = *reinterpret_cast<const Elf_Half *>(VerneedBuf);
1102 if (Version != 1)
1103 return createError("unable to dump " + describe(*this, Sec) +
1104 ": version " + Twine(Version) +
1105 " is not yet supported");
1106
1107 const Elf_Verneed *Verneed =
1108 reinterpret_cast<const Elf_Verneed *>(VerneedBuf);
1109
1110 VerNeed &VN = *Ret.emplace(Ret.end());
1111 VN.Version = Verneed->vn_version;
1112 VN.Cnt = Verneed->vn_cnt;
1113 VN.Offset = VerneedBuf - Start;
1114
1115 if (Verneed->vn_file < StrTab.size())
1116 VN.File = std::string(StrTab.data() + Verneed->vn_file);
1117 else
1118 VN.File = ("<corrupt vn_file: " + Twine(Verneed->vn_file) + ">").str();
1119
1120 const uint8_t *VernauxBuf = VerneedBuf + Verneed->vn_aux;
1121 for (unsigned J = 0; J < Verneed->vn_cnt; ++J) {
1122 if (reinterpret_cast<uintptr_t>(VernauxBuf) % sizeof(uint32_t) != 0)
1123 return createError("invalid " + describe(*this, Sec) +
1124 ": found a misaligned auxiliary entry at offset 0x" +
1125 Twine::utohexstr(VernauxBuf - Start));
1126
1127 if (VernauxBuf + sizeof(Elf_Vernaux) > End)
1128 return createError(
1129 "invalid " + describe(*this, Sec) + ": version dependency " +
1130 Twine(I) +
1131 " refers to an auxiliary entry that goes past the end "
1132 "of the section");
1133
1134 const Elf_Vernaux *Vernaux =
1135 reinterpret_cast<const Elf_Vernaux *>(VernauxBuf);
1136
1137 VernAux &Aux = *VN.AuxV.emplace(VN.AuxV.end());
1138 Aux.Hash = Vernaux->vna_hash;
1139 Aux.Flags = Vernaux->vna_flags;
1140 Aux.Other = Vernaux->vna_other;
1141 Aux.Offset = VernauxBuf - Start;
1142 if (StrTab.size() <= Vernaux->vna_name)
1143 Aux.Name = "<corrupt>";
1144 else
1145 Aux.Name = std::string(StrTab.drop_front(Vernaux->vna_name));
1146
1147 VernauxBuf += Vernaux->vna_next;
1148 }
1149 VerneedBuf += Verneed->vn_next;
1150 }
1151 return Ret;
1152}
1153
1154template <class ELFT>
1157 auto TableOrErr = sections();
1158 if (!TableOrErr)
1159 return TableOrErr.takeError();
1160 return object::getSection<ELFT>(*TableOrErr, Index);
1161}
1162
1163template <class ELFT>
1165ELFFile<ELFT>::getStringTable(const Elf_Shdr &Section,
1166 WarningHandler WarnHandler) const {
1167 if (Section.sh_type != ELF::SHT_STRTAB)
1168 if (Error E = WarnHandler("invalid sh_type for string table section " +
1169 getSecIndexForError(*this, Section) +
1170 ": expected SHT_STRTAB, but got " +
1172 getHeader().e_machine, Section.sh_type)))
1173 return std::move(E);
1174
1175 auto V = getSectionContentsAsArray<char>(Section);
1176 if (!V)
1177 return V.takeError();
1178 ArrayRef<char> Data = *V;
1179 if (Data.empty())
1180 return createError("SHT_STRTAB string table section " +
1181 getSecIndexForError(*this, Section) + " is empty");
1182 if (Data.back() != '\0')
1183 return createError("SHT_STRTAB string table section " +
1184 getSecIndexForError(*this, Section) +
1185 " is non-null terminated");
1186 return StringRef(Data.begin(), Data.size());
1187}
1188
1189template <class ELFT>
1191ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
1192 auto SectionsOrErr = sections();
1193 if (!SectionsOrErr)
1194 return SectionsOrErr.takeError();
1195 return getSHNDXTable(Section, *SectionsOrErr);
1196}
1197
1198template <class ELFT>
1200ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section,
1201 Elf_Shdr_Range Sections) const {
1202 assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX);
1203 auto VOrErr = getSectionContentsAsArray<Elf_Word>(Section);
1204 if (!VOrErr)
1205 return VOrErr.takeError();
1206 ArrayRef<Elf_Word> V = *VOrErr;
1207 auto SymTableOrErr = object::getSection<ELFT>(Sections, Section.sh_link);
1208 if (!SymTableOrErr)
1209 return SymTableOrErr.takeError();
1210 const Elf_Shdr &SymTable = **SymTableOrErr;
1211 if (SymTable.sh_type != ELF::SHT_SYMTAB &&
1212 SymTable.sh_type != ELF::SHT_DYNSYM)
1213 return createError(
1214 "SHT_SYMTAB_SHNDX section is linked with " +
1215 object::getELFSectionTypeName(getHeader().e_machine, SymTable.sh_type) +
1216 " section (expected SHT_SYMTAB/SHT_DYNSYM)");
1217
1218 uint64_t Syms = SymTable.sh_size / sizeof(Elf_Sym);
1219 if (V.size() != Syms)
1220 return createError("SHT_SYMTAB_SHNDX has " + Twine(V.size()) +
1221 " entries, but the symbol table associated has " +
1222 Twine(Syms));
1223
1224 return V;
1225}
1226
1227template <class ELFT>
1229ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
1230 auto SectionsOrErr = sections();
1231 if (!SectionsOrErr)
1232 return SectionsOrErr.takeError();
1233 return getStringTableForSymtab(Sec, *SectionsOrErr);
1234}
1235
1236template <class ELFT>
1239 Elf_Shdr_Range Sections) const {
1240
1241 if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
1242 return createError(
1243 "invalid sh_type for symbol table, expected SHT_SYMTAB or SHT_DYNSYM");
1244 Expected<const Elf_Shdr *> SectionOrErr =
1245 object::getSection<ELFT>(Sections, Sec.sh_link);
1246 if (!SectionOrErr)
1247 return SectionOrErr.takeError();
1248 return getStringTable(**SectionOrErr);
1249}
1250
1251template <class ELFT>
1253ELFFile<ELFT>::getLinkAsStrtab(const typename ELFT::Shdr &Sec) const {
1255 getSection(Sec.sh_link);
1256 if (!StrTabSecOrErr)
1257 return createError("invalid section linked to " + describe(*this, Sec) +
1258 ": " + toString(StrTabSecOrErr.takeError()));
1259
1260 Expected<StringRef> StrTabOrErr = getStringTable(**StrTabSecOrErr);
1261 if (!StrTabOrErr)
1262 return createError("invalid string table linked to " +
1263 describe(*this, Sec) + ": " +
1264 toString(StrTabOrErr.takeError()));
1265 return *StrTabOrErr;
1266}
1267
1268template <class ELFT>
1270ELFFile<ELFT>::getSectionName(const Elf_Shdr &Section,
1271 WarningHandler WarnHandler) const {
1272 auto SectionsOrErr = sections();
1273 if (!SectionsOrErr)
1274 return SectionsOrErr.takeError();
1275 auto Table = getSectionStringTable(*SectionsOrErr, WarnHandler);
1276 if (!Table)
1277 return Table.takeError();
1278 return getSectionName(Section, *Table);
1279}
1280
1281template <class ELFT>
1283 StringRef DotShstrtab) const {
1284 uint32_t Offset = Section.sh_name;
1285 if (Offset == 0)
1286 return StringRef();
1287 if (Offset >= DotShstrtab.size())
1288 return createError("a section " + getSecIndexForError(*this, Section) +
1289 " has an invalid sh_name (0x" +
1291 ") offset which goes past the end of the "
1292 "section name string table");
1293 return StringRef(DotShstrtab.data() + Offset);
1294}
1295
1296/// This function returns the hash value for a symbol in the .dynsym section
1297/// Name of the API remains consistent as specified in the libelf
1298/// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
1299inline uint32_t hashSysV(StringRef SymbolName) {
1300 uint32_t H = 0;
1301 for (uint8_t C : SymbolName) {
1302 H = (H << 4) + C;
1303 H ^= (H >> 24) & 0xf0;
1304 }
1305 return H & 0x0fffffff;
1306}
1307
1308/// This function returns the hash value for a symbol in the .dynsym section
1309/// for the GNU hash table. The implementation is defined in the GNU hash ABI.
1310/// REF : https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=bfd/elf.c#l222
1312 uint32_t H = 5381;
1313 for (uint8_t C : Name)
1314 H = (H << 5) + H + C;
1315 return H;
1316}
1317
1318} // end namespace object
1319} // end namespace llvm
1320
1321#endif // LLVM_OBJECT_ELF_H
aarch64 promote const
bbsections Prepares for basic block sections
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static bool isMips64EL(const ELFYAML::Object &Obj)
Elf_Shdr Shdr
std::string Name
uint64_t Size
#define LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
Definition: ELFTypes.h:102
ELFYAML::ELF_REL Type3
Definition: ELFYAML.cpp:1795
ELFYAML::ELF_REL Type2
Definition: ELFYAML.cpp:1794
bool End
Definition: ELF_riscv.cpp:478
Symbol * Sym
Definition: ELF_riscv.cpp:477
#define I(x, y, z)
Definition: MD5.cpp:58
#define H(x, y, z)
Definition: MD5.cpp:57
This file implements a map that provides insertion order iteration.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallString class.
This file defines the SmallVector class.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
Helper for Errors used as out-parameters.
Definition: Error.h:1102
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:474
Error takeError()
Take ownership of the stored error.
Definition: Error.h:601
reference get()
Returns a reference to the stored T value.
Definition: Error.h:571
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
void resize(size_type N)
Definition: SmallVector.h:642
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
const unsigned char * bytes_end() const
Definition: StringRef.h:118
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:613
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
const unsigned char * bytes_begin() const
Definition: StringRef.h:115
const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:416
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
An efficient, type-erasing, non-owning reference to a callable.
A range adaptor for a pair of iterators.
const Elf_Ehdr & getHeader() const
Definition: ELF.h:235
Expected< std::vector< Elf_Rela > > android_relas(const Elf_Shdr &Sec) const
Definition: ELF.cpp:393
Expected< StringRef > getLinkAsStrtab(const typename ELFT::Shdr &Sec) const
Definition: ELF.h:1253
static Expected< ELFFile > create(StringRef Object)
Definition: ELF.h:835
Expected< const Elf_Sym * > getSymbol(const Elf_Shdr *Sec, uint32_t Index) const
Definition: ELF.h:547
Expected< std::vector< VerDef > > getVersionDefinitions(const Elf_Shdr &Sec) const
Definition: ELF.h:981
std::string getDynamicTagAsString(unsigned Arch, uint64_t Type) const
Definition: ELF.cpp:461
Expected< ArrayRef< Elf_Word > > getSHNDXTable(const Elf_Shdr &Section) const
Definition: ELF.h:1191
Expected< Elf_Sym_Range > symbols(const Elf_Shdr *Sec) const
Definition: ELF.h:304
Expected< std::vector< BBAddrMap > > decodeBBAddrMap(const Elf_Shdr &Sec, const Elf_Shdr *RelaSec=nullptr) const
Returns a vector of BBAddrMap structs corresponding to each function within the text section that the...
Definition: ELF.cpp:650
Expected< ArrayRef< uint8_t > > getSegmentContents(const Elf_Phdr &Phdr) const
Definition: ELF.h:599
Elf_Note_Iterator notes_begin(const Elf_Shdr &Shdr, Error &Err) const
Get an iterator over notes in a section.
Definition: ELF.h:381
uint32_t getRelativeRelocationType() const
Definition: ELF.h:660
iterator_range< Elf_Note_Iterator > notes(const Elf_Phdr &Phdr, Error &Err) const
Get an iterator range over notes of a program header.
Definition: ELF.h:413
Expected< StringRef > getSymbolVersionByIndex(uint32_t SymbolVersionIndex, bool &IsDefault, SmallVector< std::optional< VersionEntry >, 0 > &VersionMap, std::optional< bool > IsSymHidden) const
Definition: ELF.h:952
Elf_Note_Iterator notes_begin(const Elf_Phdr &Phdr, Error &Err) const
Get an iterator over notes in a program header.
Definition: ELF.h:353
Expected< ArrayRef< uint8_t > > getSectionContents(const Elf_Shdr &Sec) const
Definition: ELF.h:619
Expected< Elf_Rela_Range > relas(const Elf_Shdr &Sec) const
Definition: ELF.h:310
Expected< Elf_Phdr_Range > program_headers() const
Iterate over program header table.
Definition: ELF.h:327
Expected< StringRef > getStringTableForSymtab(const Elf_Shdr &Section) const
Definition: ELF.h:1229
Expected< std::vector< VerNeed > > getVersionDependencies(const Elf_Shdr &Sec, WarningHandler WarnHandler=&defaultWarningHandler) const
Definition: ELF.h:1068
size_t getBufSize() const
Definition: ELF.h:225
Expected< const T * > getEntry(uint32_t Section, uint32_t Entry) const
Definition: ELF.h:925
Expected< const Elf_Sym * > getRelocationSymbol(const Elf_Rel &Rel, const Elf_Shdr *SymTab) const
Get the symbol for a given relocation.
Definition: ELF.h:703
const uint8_t * end() const
Definition: ELF.h:223
Expected< StringRef > getSectionStringTable(Elf_Shdr_Range Sections, WarningHandler WarnHandler=&defaultWarningHandler) const
Definition: ELF.h:713
Expected< uint64_t > getDynSymtabSize() const
This function determines the number of dynamic symbols.
Definition: ELF.h:772
Expected< Elf_Dyn_Range > dynamicEntries() const
Definition: ELF.cpp:550
void createFakeSections()
Used by llvm-objdump -d (which needs sections for disassembly) to disassemble objects without a secti...
Definition: ELF.h:846
Expected< Elf_Shdr_Range > sections() const
Definition: ELF.h:872
iterator_range< Elf_Note_Iterator > notes(const Elf_Shdr &Shdr, Error &Err) const
Get an iterator range over notes of a section.
Definition: ELF.h:425
const uint8_t * base() const
Definition: ELF.h:222
bool isMipsELF64() const
Definition: ELF.h:289
Expected< const uint8_t * > toMappedAddr(uint64_t VAddr, WarningHandler WarnHandler=&defaultWarningHandler) const
Definition: ELF.cpp:598
Expected< Elf_Relr_Range > relrs(const Elf_Shdr &Sec) const
Definition: ELF.h:318
Expected< MapVector< const Elf_Shdr *, const Elf_Shdr * > > getSectionAndRelocations(std::function< Expected< bool >(const Elf_Shdr &)> IsMatch) const
Returns a map from every section matching IsMatch to its relocation section, or nullptr if it has no ...
Definition: ELF.cpp:761
bool isLE() const
Definition: ELF.h:285
bool isMips64EL() const
Definition: ELF.h:294
Elf_Note_Iterator notes_end() const
Get the end iterator for notes.
Definition: ELF.h:402
Expected< StringRef > getSectionName(const Elf_Shdr &Section, WarningHandler WarnHandler=&defaultWarningHandler) const
Definition: ELF.h:1270
StringRef getRelocationTypeName(uint32_t Type) const
Definition: ELF.h:624
Expected< StringRef > getStringTable(const Elf_Shdr &Section, WarningHandler WarnHandler=&defaultWarningHandler) const
Definition: ELF.h:1165
llvm::function_ref< Error(const Twine &Msg)> WarningHandler
Definition: ELF.h:220
Expected< ArrayRef< T > > getSectionContentsAsArray(const Elf_Shdr &Sec) const
Definition: ELF.h:563
Expected< SmallVector< std::optional< VersionEntry >, 0 > > loadVersionMap(const Elf_Shdr *VerNeedSec, const Elf_Shdr *VerDefSec) const
Definition: ELF.h:666
Expected< Elf_Rel_Range > rels(const Elf_Shdr &Sec) const
Definition: ELF.h:314
Expected< const Elf_Shdr * > getSection(const Elf_Sym &Sym, const Elf_Shdr *SymTab, DataRegion< Elf_Word > ShndxTable) const
Definition: ELF.h:524
std::vector< Elf_Rel > decode_relrs(Elf_Relr_Range relrs) const
Definition: ELF.cpp:329
Expected< uint32_t > getSectionIndex(const Elf_Sym &Sym, Elf_Sym_Range Syms, DataRegion< Elf_Word > ShndxTable) const
Definition: ELF.h:507
#define UINT64_MAX
Definition: DataTypes.h:77
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ EI_DATA
Definition: ELF.h:53
@ EI_NIDENT
Definition: ELF.h:58
@ EI_CLASS
Definition: ELF.h:52
@ PF_X
Definition: ELF.h:1440
@ VER_NDX_GLOBAL
Definition: ELF.h:1546
@ VERSYM_VERSION
Definition: ELF.h:1547
@ VER_NDX_LOCAL
Definition: ELF.h:1545
@ VERSYM_HIDDEN
Definition: ELF.h:1548
@ EM_MIPS
Definition: ELF.h:141
@ ELFDATANONE
Definition: ELF.h:334
@ ELFDATA2LSB
Definition: ELF.h:335
@ SHT_STRTAB
Definition: ELF.h:1006
@ SHT_PROGBITS
Definition: ELF.h:1004
@ SHT_NOBITS
Definition: ELF.h:1011
@ SHT_SYMTAB
Definition: ELF.h:1005
@ SHT_SYMTAB_SHNDX
Definition: ELF.h:1019
@ SHT_NOTE
Definition: ELF.h:1010
@ SHT_DYNSYM
Definition: ELF.h:1014
@ SHN_XINDEX
Definition: ELF.h:997
@ SHN_UNDEF
Definition: ELF.h:989
@ SHN_LORESERVE
Definition: ELF.h:990
@ PT_LOAD
Definition: ELF.h:1392
@ PT_TLS
Definition: ELF.h:1398
@ PT_NOTE
Definition: ELF.h:1395
@ ELFCLASS64
Definition: ELF.h:329
@ ELFCLASSNONE
Definition: ELF.h:327
@ SHF_ALLOC
Definition: ELF.h:1093
@ SHF_TLS
Definition: ELF.h:1118
@ SHF_EXECINSTR
Definition: ELF.h:1096
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
Expected< uint32_t > getExtendedSymbolTableIndex(const typename ELFT::Sym &Sym, unsigned SymIndex, DataRegion< typename ELFT::Word > ShndxTable)
Definition: ELF.h:489
Expected< const typename ELFT::Shdr * > getSection(typename ELFT::ShdrRange Sections, uint32_t Index)
Definition: ELF.h:481
Error createError(const Twine &Err)
Definition: Error.h:84
StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type)
Definition: ELF.cpp:23
static Expected< uint64_t > getDynSymtabSizeFromGnuHash(const typename ELFT::GnuHash &Table, const void *BufEnd)
This function finds the number of dynamic symbols using a GNU hash table.
Definition: ELF.h:744
bool checkSectionOffsets(const typename ELFT::Phdr &Phdr, const typename ELFT::Shdr &Sec)
Definition: ELF.h:167
uint32_t getELFRelativeRelocationType(uint32_t Machine)
Definition: ELF.cpp:192
static std::string describe(const ELFFile< ELFT > &Obj, const typename ELFT::Shdr &Sec)
Definition: ELF.h:142
std::string getPhdrIndexForError(const ELFFile< ELFT > &Obj, const typename ELFT::Phdr &Phdr)
Definition: ELF.h:152
uint32_t hashGnu(StringRef Name)
This function returns the hash value for a symbol in the .dynsym section for the GNU hash table.
Definition: ELF.h:1311
StringRef getELFSectionTypeName(uint32_t Machine, uint32_t Type)
PPCInstrMasks
Definition: ELF.h:85
@ PLD_R12_NO_DISP
Definition: ELF.h:90
@ ADDIS_R12_TO_R2_NO_DISP
Definition: ELF.h:87
@ ADDI_R12_TO_R12_NO_DISP
Definition: ELF.h:89
@ ADDI_R12_TO_R2_NO_DISP
Definition: ELF.h:88
@ PADDI_R12_NO_DISP
Definition: ELF.h:86
@ BCTR
Definition: ELF.h:92
@ MTCTR_R12
Definition: ELF.h:91
std::pair< unsigned char, unsigned char > getElfArchType(StringRef Object)
Definition: ELF.h:77
static Error defaultWarningHandler(const Twine &Msg)
Definition: ELF.h:162
bool isSectionInSegment(const typename ELFT::Phdr &Phdr, const typename ELFT::Shdr &Sec)
Definition: ELF.h:204
bool checkSectionVMA(const typename ELFT::Phdr &Phdr, const typename ELFT::Shdr &Sec)
Definition: ELF.h:185
std::string getSecIndexForError(const ELFFile< ELFT > &Obj, const typename ELFT::Shdr &Sec)
Definition: ELF.h:128
uint32_t hashSysV(StringRef SymbolName)
This function returns the hash value for a symbol in the .dynsym section Name of the API remains cons...
Definition: ELF.h:1299
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:456
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1684
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are are tuples (A,...
Definition: STLExtras.h:2375
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1244
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:749
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1041
#define N
Expected< T > operator[](uint64_t N)
Definition: ELF.h:107
DataRegion(const T *Data, const uint8_t *BufferEnd)
Definition: ELF.h:104
const T * First
Definition: ELF.h:122
DataRegion(ArrayRef< T > Arr)
Definition: ELF.h:100
const uint8_t * BufEnd
Definition: ELF.h:124
std::optional< uint64_t > Size
Definition: ELF.h:123
unsigned Cnt
Definition: ELF.h:44
unsigned Version
Definition: ELF.h:41
unsigned Flags
Definition: ELF.h:42
unsigned Ndx
Definition: ELF.h:43
std::string Name
Definition: ELF.h:46
unsigned Hash
Definition: ELF.h:45
std::vector< VerdAux > AuxV
Definition: ELF.h:47
unsigned Offset
Definition: ELF.h:40
unsigned Cnt
Definition: ELF.h:60
std::string File
Definition: ELF.h:62
std::vector< VernAux > AuxV
Definition: ELF.h:63
unsigned Offset
Definition: ELF.h:61
unsigned Version
Definition: ELF.h:59
unsigned Offset
Definition: ELF.h:35
std::string Name
Definition: ELF.h:36
unsigned Hash
Definition: ELF.h:51
unsigned Offset
Definition: ELF.h:54
unsigned Flags
Definition: ELF.h:52
std::string Name
Definition: ELF.h:55
unsigned Other
Definition: ELF.h:53
std::string Name
Definition: ELF.h:67