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