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>
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(
249 {Offset << Shift, SymIdx, Type, std::make_signed_t<uint>(Addend)});
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>
289 Expected<const T *> getEntry(uint32_t Section, uint32_t Entry) const;
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;
307 Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section,
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;
312 Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section,
313 Elf_Shdr_Range Sections) const;
314
316
319 SmallVectorImpl<char> &Result) const;
321
322 std::string getDynamicTagAsString(unsigned Arch, uint64_t Type) const;
323 std::string getDynamicTagAsString(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
332 static Expected<ELFFile> create(StringRef Object);
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);
356 return getSectionContentsAsArray<Elf_Sym>(*Sec);
357 }
358
359 Expected<Elf_Rela_Range> relas(const Elf_Shdr &Sec) const {
360 return getSectionContentsAsArray<Elf_Rela>(Sec);
361 }
362
363 Expected<Elf_Rel_Range> rels(const Elf_Shdr &Sec) const {
364 return getSectionContentsAsArray<Elf_Rel>(Sec);
365 }
366
367 Expected<Elf_Relr_Range> relrs(const Elf_Shdr &Sec) const {
368 return getSectionContentsAsArray<Elf_Relr>(Sec);
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
378 Expected<std::vector<Elf_Rela>> android_relas(const Elf_Shdr &Sec) const;
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 Err =
412 createError("invalid offset (0x" + Twine::utohexstr(Phdr.p_offset) +
413 ") or size (0x" + Twine::utohexstr(Phdr.p_filesz) + ")");
414 return Elf_Note_Iterator(Err);
415 }
416 // Allow 4, 8, and (for Linux core dumps) 0.
417 // TODO: Disallow 1 after all tests are fixed.
418 if (Phdr.p_align != 0 && Phdr.p_align != 1 && Phdr.p_align != 4 &&
419 Phdr.p_align != 8) {
420 Err =
421 createError("alignment (" + Twine(Phdr.p_align) + ") is not 4 or 8");
422 return Elf_Note_Iterator(Err);
423 }
424 return Elf_Note_Iterator(base() + Phdr.p_offset, Phdr.p_filesz,
425 std::max<size_t>(Phdr.p_align, 4), Err);
426 }
427
428 /// Get an iterator over notes in a section.
429 ///
430 /// The section must be of type \c SHT_NOTE.
431 ///
432 /// \param Shdr the section to iterate over.
433 /// \param Err [out] an error to support fallible iteration, which should
434 /// be checked after iteration ends.
435 Elf_Note_Iterator notes_begin(const Elf_Shdr &Shdr, Error &Err) const {
436 assert(Shdr.sh_type == ELF::SHT_NOTE && "Shdr is not of type SHT_NOTE");
437 ErrorAsOutParameter ErrAsOutParam(Err);
438 if (Shdr.sh_offset + Shdr.sh_size > getBufSize()) {
439 Err =
440 createError("invalid offset (0x" + Twine::utohexstr(Shdr.sh_offset) +
441 ") or size (0x" + Twine::utohexstr(Shdr.sh_size) + ")");
442 return Elf_Note_Iterator(Err);
443 }
444 // TODO: Allow just 4 and 8 after all tests are fixed.
445 if (Shdr.sh_addralign != 0 && Shdr.sh_addralign != 1 &&
446 Shdr.sh_addralign != 4 && Shdr.sh_addralign != 8) {
447 Err = createError("alignment (" + Twine(Shdr.sh_addralign) +
448 ") is not 4 or 8");
449 return Elf_Note_Iterator(Err);
450 }
451 return Elf_Note_Iterator(base() + Shdr.sh_offset, Shdr.sh_size,
452 std::max<size_t>(Shdr.sh_addralign, 4), Err);
453 }
454
455 /// Get the end iterator for notes.
456 Elf_Note_Iterator notes_end() const {
457 return Elf_Note_Iterator();
458 }
459
460 /// Get an iterator range over notes of a program header.
461 ///
462 /// The program header must be of type \c PT_NOTE.
463 ///
464 /// \param Phdr the program header to iterate over.
465 /// \param Err [out] an error to support fallible iteration, which should
466 /// be checked after iteration ends.
468 Error &Err) const {
469 return make_range(notes_begin(Phdr, Err), notes_end());
470 }
471
472 /// Get an iterator range over notes of a section.
473 ///
474 /// The section must be of type \c SHT_NOTE.
475 ///
476 /// \param Shdr the section to iterate over.
477 /// \param Err [out] an error to support fallible iteration, which should
478 /// be checked after iteration ends.
480 Error &Err) const {
481 return make_range(notes_begin(Shdr, Err), notes_end());
482 }
483
485 Elf_Shdr_Range Sections,
486 WarningHandler WarnHandler = &defaultWarningHandler) const;
487 Expected<uint32_t> getSectionIndex(const Elf_Sym &Sym, Elf_Sym_Range Syms,
488 DataRegion<Elf_Word> ShndxTable) const;
490 const Elf_Shdr *SymTab,
491 DataRegion<Elf_Word> ShndxTable) const;
493 Elf_Sym_Range Symtab,
494 DataRegion<Elf_Word> ShndxTable) const;
496
497 Expected<const Elf_Sym *> getSymbol(const Elf_Shdr *Sec,
498 uint32_t Index) const;
499
501 getSectionName(const Elf_Shdr &Section,
502 WarningHandler WarnHandler = &defaultWarningHandler) const;
503 Expected<StringRef> getSectionName(const Elf_Shdr &Section,
504 StringRef DotShstrtab) const;
505 template <typename T>
506 Expected<ArrayRef<T>> getSectionContentsAsArray(const Elf_Shdr &Sec) const;
507 Expected<ArrayRef<uint8_t>> getSectionContents(const Elf_Shdr &Sec) const;
508 Expected<ArrayRef<uint8_t>> getSegmentContents(const Elf_Phdr &Phdr) const;
509
510 /// Returns a vector of BBAddrMap structs corresponding to each function
511 /// within the text section that the SHT_LLVM_BB_ADDR_MAP section \p Sec
512 /// is associated with. If the current ELFFile is relocatable, a corresponding
513 /// \p RelaSec must be passed in as an argument.
514 /// Optional out variable to collect all PGO Analyses. New elements are only
515 /// added if no error occurs. If not provided, the PGO Analyses are decoded
516 /// then ignored.
518 decodeBBAddrMap(const Elf_Shdr &Sec, const Elf_Shdr *RelaSec = nullptr,
519 std::vector<PGOAnalysisMap> *PGOAnalyses = nullptr) const;
520
521 /// Returns a map from every section matching \p IsMatch to its relocation
522 /// section, or \p nullptr if it has no relocation section. This function
523 /// returns an error if any of the \p IsMatch calls fail or if it fails to
524 /// retrieve the content section of any relocation section.
527 std::function<Expected<bool>(const Elf_Shdr &)> IsMatch) const;
528
529 void createFakeSections();
530};
531
536
537template <class ELFT>
539getSection(typename ELFT::ShdrRange Sections, uint32_t Index) {
540 if (Index >= Sections.size())
541 return createError("invalid section index: " + Twine(Index));
542 return &Sections[Index];
543}
544
545template <class ELFT>
547getExtendedSymbolTableIndex(const typename ELFT::Sym &Sym, unsigned SymIndex,
549 assert(Sym.st_shndx == ELF::SHN_XINDEX);
550 if (!ShndxTable.First)
551 return createError(
552 "found an extended symbol index (" + Twine(SymIndex) +
553 "), but unable to locate the extended symbol index table");
554
555 Expected<typename ELFT::Word> TableOrErr = ShndxTable[SymIndex];
556 if (!TableOrErr)
557 return createError("unable to read an extended symbol table at index " +
558 Twine(SymIndex) + ": " +
559 toString(TableOrErr.takeError()));
560 return *TableOrErr;
561}
562
563template <class ELFT>
565ELFFile<ELFT>::getSectionIndex(const Elf_Sym &Sym, Elf_Sym_Range Syms,
566 DataRegion<Elf_Word> ShndxTable) const {
567 uint32_t Index = Sym.st_shndx;
568 if (Index == ELF::SHN_XINDEX) {
569 Expected<uint32_t> ErrorOrIndex =
570 getExtendedSymbolTableIndex<ELFT>(Sym, &Sym - Syms.begin(), ShndxTable);
571 if (!ErrorOrIndex)
572 return ErrorOrIndex.takeError();
573 return *ErrorOrIndex;
574 }
576 return 0;
577 return Index;
578}
579
580template <class ELFT>
582ELFFile<ELFT>::getSection(const Elf_Sym &Sym, const Elf_Shdr *SymTab,
583 DataRegion<Elf_Word> ShndxTable) const {
584 auto SymsOrErr = symbols(SymTab);
585 if (!SymsOrErr)
586 return SymsOrErr.takeError();
587 return getSection(Sym, *SymsOrErr, ShndxTable);
588}
589
590template <class ELFT>
592ELFFile<ELFT>::getSection(const Elf_Sym &Sym, Elf_Sym_Range Symbols,
593 DataRegion<Elf_Word> ShndxTable) const {
594 auto IndexOrErr = getSectionIndex(Sym, Symbols, ShndxTable);
595 if (!IndexOrErr)
596 return IndexOrErr.takeError();
597 uint32_t Index = *IndexOrErr;
598 if (Index == 0)
599 return nullptr;
600 return getSection(Index);
601}
602
603template <class ELFT>
605ELFFile<ELFT>::getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
606 auto SymsOrErr = symbols(Sec);
607 if (!SymsOrErr)
608 return SymsOrErr.takeError();
609
610 Elf_Sym_Range Symbols = *SymsOrErr;
611 if (Index >= Symbols.size())
612 return createError("unable to get symbol from section " +
613 getSecIndexForError(*this, *Sec) +
614 ": invalid symbol index (" + Twine(Index) + ")");
615 return &Symbols[Index];
616}
617
618template <class ELFT>
619template <typename T>
622 if (Sec.sh_entsize != sizeof(T) && sizeof(T) != 1)
623 return createError("section " + getSecIndexForError(*this, Sec) +
624 " has invalid sh_entsize: expected " + Twine(sizeof(T)) +
625 ", but got " + Twine(Sec.sh_entsize));
626
627 uintX_t Offset = Sec.sh_offset;
628 uintX_t Size = Sec.sh_size;
629
630 if (Size % sizeof(T))
631 return createError("section " + getSecIndexForError(*this, Sec) +
632 " has an invalid sh_size (" + Twine(Size) +
633 ") which is not a multiple of its sh_entsize (" +
634 Twine(Sec.sh_entsize) + ")");
635 if (std::numeric_limits<uintX_t>::max() - Offset < Size)
636 return createError("section " + getSecIndexForError(*this, Sec) +
637 " has a sh_offset (0x" + Twine::utohexstr(Offset) +
638 ") + sh_size (0x" + Twine::utohexstr(Size) +
639 ") that cannot be represented");
640 if (Offset + Size > Buf.size())
641 return createError("section " + getSecIndexForError(*this, Sec) +
642 " has a sh_offset (0x" + Twine::utohexstr(Offset) +
643 ") + sh_size (0x" + Twine::utohexstr(Size) +
644 ") that is greater than the file size (0x" +
645 Twine::utohexstr(Buf.size()) + ")");
646
647 if (Offset % alignof(T))
648 // TODO: this error is untested.
649 return createError("unaligned data");
650
651 const T *Start = reinterpret_cast<const T *>(base() + Offset);
652 return ArrayRef(Start, Size / sizeof(T));
653}
654
655template <class ELFT>
657ELFFile<ELFT>::getSegmentContents(const Elf_Phdr &Phdr) const {
658 uintX_t Offset = Phdr.p_offset;
659 uintX_t Size = Phdr.p_filesz;
660
661 if (std::numeric_limits<uintX_t>::max() - Offset < Size)
662 return createError("program header " + getPhdrIndexForError(*this, Phdr) +
663 " has a p_offset (0x" + Twine::utohexstr(Offset) +
664 ") + p_filesz (0x" + Twine::utohexstr(Size) +
665 ") that cannot be represented");
666 if (Offset + Size > Buf.size())
667 return createError("program header " + getPhdrIndexForError(*this, Phdr) +
668 " has a p_offset (0x" + Twine::utohexstr(Offset) +
669 ") + p_filesz (0x" + Twine::utohexstr(Size) +
670 ") that is greater than the file size (0x" +
671 Twine::utohexstr(Buf.size()) + ")");
672 return ArrayRef(base() + Offset, Size);
673}
674
675template <class ELFT>
677ELFFile<ELFT>::getSectionContents(const Elf_Shdr &Sec) const {
678 return getSectionContentsAsArray<uint8_t>(Sec);
679}
680
681template <class ELFT>
683 return getELFRelocationTypeName(getHeader().e_machine, Type);
684}
685
686template <class ELFT>
688 SmallVectorImpl<char> &Result) const {
689 if (!isMipsELF64()) {
690 StringRef Name = getRelocationTypeName(Type);
691 Result.append(Name.begin(), Name.end());
692 } else {
693 // The Mips N64 ABI allows up to three operations to be specified per
694 // relocation record. Unfortunately there's no easy way to test for the
695 // presence of N64 ELFs as they have no special flag that identifies them
696 // as being N64. We can safely assume at the moment that all Mips
697 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
698 // information to disambiguate between old vs new ABIs.
699 uint8_t Type1 = (Type >> 0) & 0xFF;
700 uint8_t Type2 = (Type >> 8) & 0xFF;
701 uint8_t Type3 = (Type >> 16) & 0xFF;
702
703 // Concat all three relocation type names.
704 StringRef Name = getRelocationTypeName(Type1);
705 Result.append(Name.begin(), Name.end());
706
707 Name = getRelocationTypeName(Type2);
708 Result.append(1, '/');
709 Result.append(Name.begin(), Name.end());
710
711 Name = getRelocationTypeName(Type3);
712 Result.append(1, '/');
713 Result.append(Name.begin(), Name.end());
714 }
715}
716
717template <class ELFT>
719 return getELFRelativeRelocationType(getHeader().e_machine);
720}
721
722template <class ELFT>
724ELFFile<ELFT>::loadVersionMap(const Elf_Shdr *VerNeedSec,
725 const Elf_Shdr *VerDefSec) const {
727
728 // The first two version indexes are reserved.
729 // Index 0 is VER_NDX_LOCAL, index 1 is VER_NDX_GLOBAL.
730 VersionMap.push_back(VersionEntry());
731 VersionMap.push_back(VersionEntry());
732
733 auto InsertEntry = [&](unsigned N, StringRef Version, bool IsVerdef) {
734 if (N >= VersionMap.size())
735 VersionMap.resize(N + 1);
736 VersionMap[N] = {std::string(Version), IsVerdef};
737 };
738
739 if (VerDefSec) {
740 Expected<std::vector<VerDef>> Defs = getVersionDefinitions(*VerDefSec);
741 if (!Defs)
742 return Defs.takeError();
743 for (const VerDef &Def : *Defs)
744 InsertEntry(Def.Ndx & ELF::VERSYM_VERSION, Def.Name, true);
745 }
746
747 if (VerNeedSec) {
748 Expected<std::vector<VerNeed>> Deps = getVersionDependencies(*VerNeedSec);
749 if (!Deps)
750 return Deps.takeError();
751 for (const VerNeed &Dep : *Deps)
752 for (const VernAux &Aux : Dep.AuxV)
753 InsertEntry(Aux.Other & ELF::VERSYM_VERSION, Aux.Name, false);
754 }
755
756 return VersionMap;
757}
758
759template <class ELFT>
762 const Elf_Shdr *SymTab) const {
763 uint32_t Index = Rel.getSymbol(isMips64EL());
764 if (Index == 0)
765 return nullptr;
766 return getEntry<Elf_Sym>(*SymTab, Index);
767}
768
769template <class ELFT>
772 WarningHandler WarnHandler) const {
773 uint32_t Index = getHeader().e_shstrndx;
774 if (Index == ELF::SHN_XINDEX) {
775 // If the section name string table section index is greater than
776 // or equal to SHN_LORESERVE, then the actual index of the section name
777 // string table section is contained in the sh_link field of the section
778 // header at index 0.
779 if (Sections.empty())
780 return createError(
781 "e_shstrndx == SHN_XINDEX, but the section header table is empty");
782
783 Index = Sections[0].sh_link;
784 }
785
786 // There is no section name string table. Return FakeSectionStrings which
787 // is non-empty if we have created fake sections.
788 if (!Index)
789 return FakeSectionStrings;
790
791 if (Index >= Sections.size())
792 return createError("section header string table index " + Twine(Index) +
793 " does not exist");
794 return getStringTable(Sections[Index], WarnHandler);
795}
796
797/// This function finds the number of dynamic symbols using a GNU hash table.
798///
799/// @param Table The GNU hash table for .dynsym.
800template <class ELFT>
802getDynSymtabSizeFromGnuHash(const typename ELFT::GnuHash &Table,
803 const void *BufEnd) {
804 using Elf_Word = typename ELFT::Word;
805 if (Table.nbuckets == 0)
806 return Table.symndx + 1;
807 uint64_t LastSymIdx = 0;
808 // Find the index of the first symbol in the last chain.
809 for (Elf_Word Val : Table.buckets())
810 LastSymIdx = std::max(LastSymIdx, (uint64_t)Val);
811 const Elf_Word *It =
812 reinterpret_cast<const Elf_Word *>(Table.values(LastSymIdx).end());
813 // Locate the end of the chain to find the last symbol index.
814 while (It < BufEnd && (*It & 1) == 0) {
815 ++LastSymIdx;
816 ++It;
817 }
818 if (It >= BufEnd) {
819 return createStringError(
821 "no terminator found for GNU hash section before buffer end");
822 }
823 return LastSymIdx + 1;
824}
825
826/// This function determines the number of dynamic symbols. It reads section
827/// headers first. If section headers are not available, the number of
828/// symbols will be inferred by parsing dynamic hash tables.
829template <class ELFT>
831 // Read .dynsym section header first if available.
832 Expected<Elf_Shdr_Range> SectionsOrError = sections();
833 if (!SectionsOrError)
834 return SectionsOrError.takeError();
835 for (const Elf_Shdr &Sec : *SectionsOrError) {
836 if (Sec.sh_type == ELF::SHT_DYNSYM) {
837 if (Sec.sh_size % Sec.sh_entsize != 0) {
839 "SHT_DYNSYM section has sh_size (" +
840 Twine(Sec.sh_size) + ") % sh_entsize (" +
841 Twine(Sec.sh_entsize) + ") that is not 0");
842 }
843 return Sec.sh_size / Sec.sh_entsize;
844 }
845 }
846
847 if (!SectionsOrError->empty()) {
848 // Section headers are available but .dynsym header is not found.
849 // Return 0 as .dynsym does not exist.
850 return 0;
851 }
852
853 // Section headers do not exist. Falling back to infer
854 // upper bound of .dynsym from .gnu.hash and .hash.
855 Expected<Elf_Dyn_Range> DynTable = dynamicEntries();
856 if (!DynTable)
857 return DynTable.takeError();
858 std::optional<uint64_t> ElfHash;
859 std::optional<uint64_t> ElfGnuHash;
860 for (const Elf_Dyn &Entry : *DynTable) {
861 switch (Entry.d_tag) {
862 case ELF::DT_HASH:
863 ElfHash = Entry.d_un.d_ptr;
864 break;
865 case ELF::DT_GNU_HASH:
866 ElfGnuHash = Entry.d_un.d_ptr;
867 break;
868 }
869 }
870 if (ElfGnuHash) {
871 Expected<const uint8_t *> TablePtr = toMappedAddr(*ElfGnuHash);
872 if (!TablePtr)
873 return TablePtr.takeError();
874 const Elf_GnuHash *Table =
875 reinterpret_cast<const Elf_GnuHash *>(TablePtr.get());
876 return getDynSymtabSizeFromGnuHash<ELFT>(*Table, this->Buf.bytes_end());
877 }
878
879 // Search SYSV hash table to try to find the upper bound of dynsym.
880 if (ElfHash) {
881 Expected<const uint8_t *> TablePtr = toMappedAddr(*ElfHash);
882 if (!TablePtr)
883 return TablePtr.takeError();
884 const Elf_Hash *Table = reinterpret_cast<const Elf_Hash *>(TablePtr.get());
885 return Table->nchain;
886 }
887 return 0;
888}
889
890template <class ELFT> ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {}
891
892template <class ELFT>
894 if (sizeof(Elf_Ehdr) > Object.size())
895 return createError("invalid buffer: the size (" + Twine(Object.size()) +
896 ") is smaller than an ELF header (" +
897 Twine(sizeof(Elf_Ehdr)) + ")");
898 return ELFFile(Object);
899}
900
901/// Used by llvm-objdump -d (which needs sections for disassembly) to
902/// disassemble objects without a section header table (e.g. ET_CORE objects
903/// analyzed by linux perf or ET_EXEC with llvm-strip --strip-sections).
904template <class ELFT> void ELFFile<ELFT>::createFakeSections() {
905 if (!FakeSections.empty())
906 return;
907 auto PhdrsOrErr = program_headers();
908 if (!PhdrsOrErr)
909 return;
910
911 FakeSectionStrings += '\0';
912 for (auto [Idx, Phdr] : llvm::enumerate(*PhdrsOrErr)) {
913 if (Phdr.p_type != ELF::PT_LOAD || !(Phdr.p_flags & ELF::PF_X))
914 continue;
915 Elf_Shdr FakeShdr = {};
916 FakeShdr.sh_type = ELF::SHT_PROGBITS;
917 FakeShdr.sh_flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
918 FakeShdr.sh_addr = Phdr.p_vaddr;
919 FakeShdr.sh_size = Phdr.p_memsz;
920 FakeShdr.sh_offset = Phdr.p_offset;
921 // Create a section name based on the p_type and index.
922 FakeShdr.sh_name = FakeSectionStrings.size();
923 FakeSectionStrings += ("PT_LOAD#" + Twine(Idx)).str();
924 FakeSectionStrings += '\0';
925 FakeSections.push_back(FakeShdr);
926 }
927}
928
929template <class ELFT>
931 const uintX_t SectionTableOffset = getHeader().e_shoff;
932 if (SectionTableOffset == 0) {
933 if (!FakeSections.empty())
934 return ArrayRef(FakeSections);
935 return ArrayRef<Elf_Shdr>();
936 }
937
938 if (getHeader().e_shentsize != sizeof(Elf_Shdr))
939 return createError("invalid e_shentsize in ELF header: " +
940 Twine(getHeader().e_shentsize));
941
942 const uint64_t FileSize = Buf.size();
943 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize ||
944 SectionTableOffset + (uintX_t)sizeof(Elf_Shdr) < SectionTableOffset)
945 return createError(
946 "section header table goes past the end of the file: e_shoff = 0x" +
947 Twine::utohexstr(SectionTableOffset));
948
949 // Invalid address alignment of section headers
950 if (SectionTableOffset & (alignof(Elf_Shdr) - 1))
951 // TODO: this error is untested.
952 return createError("invalid alignment of section headers");
953
954 const Elf_Shdr *First =
955 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
956
957 uintX_t NumSections = getHeader().e_shnum;
958 if (NumSections == 0)
959 NumSections = First->sh_size;
960
961 if (NumSections > UINT64_MAX / sizeof(Elf_Shdr))
962 return createError("invalid number of sections specified in the NULL "
963 "section's sh_size field (" +
964 Twine(NumSections) + ")");
965
966 const uint64_t SectionTableSize = NumSections * sizeof(Elf_Shdr);
967 if (SectionTableOffset + SectionTableSize < SectionTableOffset)
968 return createError(
969 "invalid section header table offset (e_shoff = 0x" +
970 Twine::utohexstr(SectionTableOffset) +
971 ") or invalid number of sections specified in the first section "
972 "header's sh_size field (0x" +
973 Twine::utohexstr(NumSections) + ")");
974
975 // Section table goes past end of file!
976 if (SectionTableOffset + SectionTableSize > FileSize)
977 return createError("section table goes past the end of file");
978 return ArrayRef(First, NumSections);
979}
980
981template <class ELFT>
982template <typename T>
984 uint32_t Entry) const {
985 auto SecOrErr = getSection(Section);
986 if (!SecOrErr)
987 return SecOrErr.takeError();
988 return getEntry<T>(**SecOrErr, Entry);
989}
990
991template <class ELFT>
992template <typename T>
994 uint32_t Entry) const {
995 Expected<ArrayRef<T>> EntriesOrErr = getSectionContentsAsArray<T>(Section);
996 if (!EntriesOrErr)
997 return EntriesOrErr.takeError();
998
999 ArrayRef<T> Arr = *EntriesOrErr;
1000 if (Entry >= Arr.size())
1001 return createError(
1002 "can't read an entry at 0x" +
1003 Twine::utohexstr(Entry * static_cast<uint64_t>(sizeof(T))) +
1004 ": it goes past the end of the section (0x" +
1005 Twine::utohexstr(Section.sh_size) + ")");
1006 return &Arr[Entry];
1007}
1008
1009template <typename ELFT>
1011 uint32_t SymbolVersionIndex, bool &IsDefault,
1012 SmallVector<std::optional<VersionEntry>, 0> &VersionMap,
1013 std::optional<bool> IsSymHidden) const {
1014 size_t VersionIndex = SymbolVersionIndex & llvm::ELF::VERSYM_VERSION;
1015
1016 // Special markers for unversioned symbols.
1017 if (VersionIndex == llvm::ELF::VER_NDX_LOCAL ||
1018 VersionIndex == llvm::ELF::VER_NDX_GLOBAL) {
1019 IsDefault = false;
1020 return "";
1021 }
1022
1023 // Lookup this symbol in the version table.
1024 if (VersionIndex >= VersionMap.size() || !VersionMap[VersionIndex])
1025 return createError("SHT_GNU_versym section refers to a version index " +
1026 Twine(VersionIndex) + " which is missing");
1027
1028 const VersionEntry &Entry = *VersionMap[VersionIndex];
1029 // A default version (@@) is only available for defined symbols.
1030 if (!Entry.IsVerDef || IsSymHidden.value_or(false))
1031 IsDefault = false;
1032 else
1033 IsDefault = !(SymbolVersionIndex & llvm::ELF::VERSYM_HIDDEN);
1034 return Entry.Name.c_str();
1035}
1036
1037template <class ELFT>
1039ELFFile<ELFT>::getVersionDefinitions(const Elf_Shdr &Sec) const {
1040 Expected<StringRef> StrTabOrErr = getLinkAsStrtab(Sec);
1041 if (!StrTabOrErr)
1042 return StrTabOrErr.takeError();
1043
1044 Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec);
1045 if (!ContentsOrErr)
1046 return createError("cannot read content of " + describe(*this, Sec) + ": " +
1047 toString(ContentsOrErr.takeError()));
1048
1049 const uint8_t *Start = ContentsOrErr->data();
1050 const uint8_t *End = Start + ContentsOrErr->size();
1051
1052 auto ExtractNextAux = [&](const uint8_t *&VerdauxBuf,
1053 unsigned VerDefNdx) -> Expected<VerdAux> {
1054 if (VerdauxBuf + sizeof(Elf_Verdaux) > End)
1055 return createError("invalid " + describe(*this, Sec) +
1056 ": version definition " + Twine(VerDefNdx) +
1057 " refers to an auxiliary entry that goes past the end "
1058 "of the section");
1059
1060 auto *Verdaux = reinterpret_cast<const Elf_Verdaux *>(VerdauxBuf);
1061 VerdauxBuf += Verdaux->vda_next;
1062
1063 VerdAux Aux;
1064 Aux.Offset = VerdauxBuf - Start;
1065 if (Verdaux->vda_name < StrTabOrErr->size())
1066 Aux.Name = std::string(StrTabOrErr->drop_front(Verdaux->vda_name).data());
1067 else
1068 Aux.Name = ("<invalid vda_name: " + Twine(Verdaux->vda_name) + ">").str();
1069 return Aux;
1070 };
1071
1072 std::vector<VerDef> Ret;
1073 const uint8_t *VerdefBuf = Start;
1074 for (unsigned I = 1; I <= /*VerDefsNum=*/Sec.sh_info; ++I) {
1075 if (VerdefBuf + sizeof(Elf_Verdef) > End)
1076 return createError("invalid " + describe(*this, Sec) +
1077 ": version definition " + Twine(I) +
1078 " goes past the end of the section");
1079
1080 if (reinterpret_cast<uintptr_t>(VerdefBuf) % sizeof(uint32_t) != 0)
1081 return createError(
1082 "invalid " + describe(*this, Sec) +
1083 ": found a misaligned version definition entry at offset 0x" +
1084 Twine::utohexstr(VerdefBuf - Start));
1085
1086 unsigned Version = *reinterpret_cast<const Elf_Half *>(VerdefBuf);
1087 if (Version != 1)
1088 return createError("unable to dump " + describe(*this, Sec) +
1089 ": version " + Twine(Version) +
1090 " is not yet supported");
1091
1092 const Elf_Verdef *D = reinterpret_cast<const Elf_Verdef *>(VerdefBuf);
1093 VerDef &VD = *Ret.emplace(Ret.end());
1094 VD.Offset = VerdefBuf - Start;
1095 VD.Version = D->vd_version;
1096 VD.Flags = D->vd_flags;
1097 VD.Ndx = D->vd_ndx;
1098 VD.Cnt = D->vd_cnt;
1099 VD.Hash = D->vd_hash;
1100
1101 const uint8_t *VerdauxBuf = VerdefBuf + D->vd_aux;
1102 for (unsigned J = 0; J < D->vd_cnt; ++J) {
1103 if (reinterpret_cast<uintptr_t>(VerdauxBuf) % sizeof(uint32_t) != 0)
1104 return createError("invalid " + describe(*this, Sec) +
1105 ": found a misaligned auxiliary entry at offset 0x" +
1106 Twine::utohexstr(VerdauxBuf - Start));
1107
1108 Expected<VerdAux> AuxOrErr = ExtractNextAux(VerdauxBuf, I);
1109 if (!AuxOrErr)
1110 return AuxOrErr.takeError();
1111
1112 if (J == 0)
1113 VD.Name = AuxOrErr->Name;
1114 else
1115 VD.AuxV.push_back(*AuxOrErr);
1116 }
1117
1118 VerdefBuf += D->vd_next;
1119 }
1120
1121 return Ret;
1122}
1123
1124template <class ELFT>
1127 WarningHandler WarnHandler) const {
1128 StringRef StrTab;
1129 Expected<StringRef> StrTabOrErr = getLinkAsStrtab(Sec);
1130 if (!StrTabOrErr) {
1131 if (Error E = WarnHandler(toString(StrTabOrErr.takeError())))
1132 return std::move(E);
1133 } else {
1134 StrTab = *StrTabOrErr;
1135 }
1136
1137 Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec);
1138 if (!ContentsOrErr)
1139 return createError("cannot read content of " + describe(*this, Sec) + ": " +
1140 toString(ContentsOrErr.takeError()));
1141
1142 const uint8_t *Start = ContentsOrErr->data();
1143 const uint8_t *End = Start + ContentsOrErr->size();
1144 const uint8_t *VerneedBuf = Start;
1145
1146 std::vector<VerNeed> Ret;
1147 for (unsigned I = 1; I <= /*VerneedNum=*/Sec.sh_info; ++I) {
1148 if (VerneedBuf + sizeof(Elf_Verdef) > End)
1149 return createError("invalid " + describe(*this, Sec) +
1150 ": version dependency " + Twine(I) +
1151 " goes past the end of the section");
1152
1153 if (reinterpret_cast<uintptr_t>(VerneedBuf) % sizeof(uint32_t) != 0)
1154 return createError(
1155 "invalid " + describe(*this, Sec) +
1156 ": found a misaligned version dependency entry at offset 0x" +
1157 Twine::utohexstr(VerneedBuf - Start));
1158
1159 unsigned Version = *reinterpret_cast<const Elf_Half *>(VerneedBuf);
1160 if (Version != 1)
1161 return createError("unable to dump " + describe(*this, Sec) +
1162 ": version " + Twine(Version) +
1163 " is not yet supported");
1164
1165 const Elf_Verneed *Verneed =
1166 reinterpret_cast<const Elf_Verneed *>(VerneedBuf);
1167
1168 VerNeed &VN = *Ret.emplace(Ret.end());
1169 VN.Version = Verneed->vn_version;
1170 VN.Cnt = Verneed->vn_cnt;
1171 VN.Offset = VerneedBuf - Start;
1172
1173 if (Verneed->vn_file < StrTab.size())
1174 VN.File = std::string(StrTab.data() + Verneed->vn_file);
1175 else
1176 VN.File = ("<corrupt vn_file: " + Twine(Verneed->vn_file) + ">").str();
1177
1178 const uint8_t *VernauxBuf = VerneedBuf + Verneed->vn_aux;
1179 for (unsigned J = 0; J < Verneed->vn_cnt; ++J) {
1180 if (reinterpret_cast<uintptr_t>(VernauxBuf) % sizeof(uint32_t) != 0)
1181 return createError("invalid " + describe(*this, Sec) +
1182 ": found a misaligned auxiliary entry at offset 0x" +
1183 Twine::utohexstr(VernauxBuf - Start));
1184
1185 if (VernauxBuf + sizeof(Elf_Vernaux) > End)
1186 return createError(
1187 "invalid " + describe(*this, Sec) + ": version dependency " +
1188 Twine(I) +
1189 " refers to an auxiliary entry that goes past the end "
1190 "of the section");
1191
1192 const Elf_Vernaux *Vernaux =
1193 reinterpret_cast<const Elf_Vernaux *>(VernauxBuf);
1194
1195 VernAux &Aux = *VN.AuxV.emplace(VN.AuxV.end());
1196 Aux.Hash = Vernaux->vna_hash;
1197 Aux.Flags = Vernaux->vna_flags;
1198 Aux.Other = Vernaux->vna_other;
1199 Aux.Offset = VernauxBuf - Start;
1200 if (StrTab.size() <= Vernaux->vna_name)
1201 Aux.Name = "<corrupt>";
1202 else
1203 Aux.Name = std::string(StrTab.drop_front(Vernaux->vna_name));
1204
1205 VernauxBuf += Vernaux->vna_next;
1206 }
1207 VerneedBuf += Verneed->vn_next;
1208 }
1209 return Ret;
1210}
1211
1212template <class ELFT>
1215 auto TableOrErr = sections();
1216 if (!TableOrErr)
1217 return TableOrErr.takeError();
1218 return object::getSection<ELFT>(*TableOrErr, Index);
1219}
1220
1221template <class ELFT>
1223ELFFile<ELFT>::getStringTable(const Elf_Shdr &Section,
1224 WarningHandler WarnHandler) const {
1225 if (Section.sh_type != ELF::SHT_STRTAB)
1226 if (Error E = WarnHandler("invalid sh_type for string table section " +
1227 getSecIndexForError(*this, Section) +
1228 ": expected SHT_STRTAB, but got " +
1230 getHeader().e_machine, Section.sh_type)))
1231 return std::move(E);
1232
1233 auto V = getSectionContentsAsArray<char>(Section);
1234 if (!V)
1235 return V.takeError();
1236 ArrayRef<char> Data = *V;
1237 if (Data.empty())
1238 return createError("SHT_STRTAB string table section " +
1239 getSecIndexForError(*this, Section) + " is empty");
1240 if (Data.back() != '\0')
1241 return createError("SHT_STRTAB string table section " +
1242 getSecIndexForError(*this, Section) +
1243 " is non-null terminated");
1244 return StringRef(Data.begin(), Data.size());
1245}
1246
1247template <class ELFT>
1249ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
1250 auto SectionsOrErr = sections();
1251 if (!SectionsOrErr)
1252 return SectionsOrErr.takeError();
1253 return getSHNDXTable(Section, *SectionsOrErr);
1254}
1255
1256template <class ELFT>
1258ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section,
1259 Elf_Shdr_Range Sections) const {
1260 assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX);
1261 auto VOrErr = getSectionContentsAsArray<Elf_Word>(Section);
1262 if (!VOrErr)
1263 return VOrErr.takeError();
1264 ArrayRef<Elf_Word> V = *VOrErr;
1265 auto SymTableOrErr = object::getSection<ELFT>(Sections, Section.sh_link);
1266 if (!SymTableOrErr)
1267 return SymTableOrErr.takeError();
1268 const Elf_Shdr &SymTable = **SymTableOrErr;
1269 if (SymTable.sh_type != ELF::SHT_SYMTAB &&
1270 SymTable.sh_type != ELF::SHT_DYNSYM)
1271 return createError(
1272 "SHT_SYMTAB_SHNDX section is linked with " +
1273 object::getELFSectionTypeName(getHeader().e_machine, SymTable.sh_type) +
1274 " section (expected SHT_SYMTAB/SHT_DYNSYM)");
1275
1276 uint64_t Syms = SymTable.sh_size / sizeof(Elf_Sym);
1277 if (V.size() != Syms)
1278 return createError("SHT_SYMTAB_SHNDX has " + Twine(V.size()) +
1279 " entries, but the symbol table associated has " +
1280 Twine(Syms));
1281
1282 return V;
1283}
1284
1285template <class ELFT>
1287ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
1288 auto SectionsOrErr = sections();
1289 if (!SectionsOrErr)
1290 return SectionsOrErr.takeError();
1291 return getStringTableForSymtab(Sec, *SectionsOrErr);
1292}
1293
1294template <class ELFT>
1297 Elf_Shdr_Range Sections) const {
1298
1299 if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
1300 return createError(
1301 "invalid sh_type for symbol table, expected SHT_SYMTAB or SHT_DYNSYM");
1302 Expected<const Elf_Shdr *> SectionOrErr =
1303 object::getSection<ELFT>(Sections, Sec.sh_link);
1304 if (!SectionOrErr)
1305 return SectionOrErr.takeError();
1306 return getStringTable(**SectionOrErr);
1307}
1308
1309template <class ELFT>
1311ELFFile<ELFT>::getLinkAsStrtab(const typename ELFT::Shdr &Sec) const {
1313 getSection(Sec.sh_link);
1314 if (!StrTabSecOrErr)
1315 return createError("invalid section linked to " + describe(*this, Sec) +
1316 ": " + toString(StrTabSecOrErr.takeError()));
1317
1318 Expected<StringRef> StrTabOrErr = getStringTable(**StrTabSecOrErr);
1319 if (!StrTabOrErr)
1320 return createError("invalid string table linked to " +
1321 describe(*this, Sec) + ": " +
1322 toString(StrTabOrErr.takeError()));
1323 return *StrTabOrErr;
1324}
1325
1326template <class ELFT>
1328ELFFile<ELFT>::getSectionName(const Elf_Shdr &Section,
1329 WarningHandler WarnHandler) const {
1330 auto SectionsOrErr = sections();
1331 if (!SectionsOrErr)
1332 return SectionsOrErr.takeError();
1333 auto Table = getSectionStringTable(*SectionsOrErr, WarnHandler);
1334 if (!Table)
1335 return Table.takeError();
1336 return getSectionName(Section, *Table);
1337}
1338
1339template <class ELFT>
1341 StringRef DotShstrtab) const {
1342 uint32_t Offset = Section.sh_name;
1343 if (Offset == 0)
1344 return StringRef();
1345 if (Offset >= DotShstrtab.size())
1346 return createError("a section " + getSecIndexForError(*this, Section) +
1347 " has an invalid sh_name (0x" +
1349 ") offset which goes past the end of the "
1350 "section name string table");
1351 return StringRef(DotShstrtab.data() + Offset);
1352}
1353
1354/// This function returns the hash value for a symbol in the .dynsym section
1355/// Name of the API remains consistent as specified in the libelf
1356/// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
1357inline uint32_t hashSysV(StringRef SymbolName) {
1358 uint32_t H = 0;
1359 for (uint8_t C : SymbolName) {
1360 H = (H << 4) + C;
1361 H ^= (H >> 24) & 0xf0;
1362 }
1363 return H & 0x0fffffff;
1364}
1365
1366/// This function returns the hash value for a symbol in the .dynsym section
1367/// for the GNU hash table. The implementation is defined in the GNU hash ABI.
1368/// REF : https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=bfd/elf.c#l222
1370 uint32_t H = 5381;
1371 for (uint8_t C : Name)
1372 H = (H << 5) + H + C;
1373 return H;
1374}
1375
1380
1381} // end namespace object
1382} // end namespace llvm
1383
1384#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< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:390
#define LLVM_ABI
Definition: Compiler.h:213
#define LLVM_TEMPLATE_ABI
Definition: Compiler.h:214
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)
T Content
Elf_Shdr Shdr
std::string Name
uint32_t Index
uint64_t Size
#define LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
Definition: ELFTypes.h:107
ELFYAML::ELF_REL Type3
Definition: ELFYAML.cpp:1851
ELFYAML::ELF_REL Type2
Definition: ELFYAML.cpp:1850
bool End
Definition: ELF_riscv.cpp:480
Symbol * Sym
Definition: ELF_riscv.cpp:479
#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.
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...
Definition: DataExtractor.h:55
Error takeError()
Return error contained inside this Cursor, if any.
Definition: DataExtractor.h:79
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
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
void resize(size_type N)
Definition: SmallVector.h:639
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
const unsigned char * bytes_end() const
Definition: StringRef.h:135
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:619
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:154
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:148
const unsigned char * bytes_begin() const
Definition: StringRef.h:132
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:418
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: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:1311
static Expected< ELFFile > create(StringRef Object)
Definition: ELF.h:893
Expected< const Elf_Sym * > getSymbol(const Elf_Shdr *Sec, uint32_t Index) const
Definition: ELF.h:605
Expected< std::vector< VerDef > > getVersionDefinitions(const Elf_Shdr &Sec) const
Definition: ELF.h:1039
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:1249
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:657
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:435
uint32_t getRelativeRelocationType() const
Definition: ELF.h:718
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:467
Expected< StringRef > getSymbolVersionByIndex(uint32_t SymbolVersionIndex, bool &IsDefault, SmallVector< std::optional< VersionEntry >, 0 > &VersionMap, std::optional< bool > IsSymHidden) const
Definition: ELF.h:1010
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:677
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:1287
Expected< std::vector< VerNeed > > getVersionDependencies(const Elf_Shdr &Sec, WarningHandler WarnHandler=&defaultWarningHandler) const
Definition: ELF.h:1126
size_t getBufSize() const
Definition: ELF.h:274
Expected< const T * > getEntry(uint32_t Section, uint32_t Entry) const
Definition: ELF.h:983
Expected< const Elf_Sym * > getRelocationSymbol(const Elf_Rel &Rel, const Elf_Shdr *SymTab) const
Get the symbol for a given relocation.
Definition: ELF.h:761
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:771
Expected< uint64_t > getDynSymtabSize() const
This function determines the number of dynamic symbols.
Definition: ELF.h:830
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:904
ELFFile(const ELFFile &)=default
Expected< Elf_Shdr_Range > sections() const
Definition: ELF.h:930
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:479
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
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:456
Expected< StringRef > getSectionName(const Elf_Shdr &Section, WarningHandler WarnHandler=&defaultWarningHandler) const
Definition: ELF.h:1328
StringRef getRelocationTypeName(uint32_t Type) const
Definition: ELF.h:682
Expected< StringRef > getStringTable(const Elf_Shdr &Section, WarningHandler WarnHandler=&defaultWarningHandler) const
Definition: ELF.h:1223
llvm::function_ref< Error(const Twine &Msg)> WarningHandler
Definition: ELF.h:269
Expected< ArrayRef< T > > getSectionContentsAsArray(const Elf_Shdr &Sec) const
Definition: ELF.h:621
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:724
Expected< Elf_Rel_Range > rels(const Elf_Shdr &Sec) const
Definition: ELF.h:363
std::pair< std::vector< Elf_Rel >, std::vector< Elf_Rela > > RelsOrRelas
Definition: ELF.h:374
Expected< const Elf_Shdr * > getSection(const Elf_Sym &Sym, const Elf_Shdr *SymTab, DataRegion< Elf_Word > ShndxTable) const
Definition: ELF.h:582
std::vector< Elf_Rel > decode_relrs(Elf_Relr_Range relrs) const
Definition: ELF.cpp:338
Expected< uint32_t > getSectionIndex(const Elf_Sym &Sym, Elf_Sym_Range Syms, DataRegion< Elf_Word > ShndxTable) const
Definition: ELF.h:565
#define UINT64_MAX
Definition: DataTypes.h:77
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ ELFCLASS64
Definition: ELF.h:334
@ ELFCLASSNONE
Definition: ELF.h:332
@ EI_DATA
Definition: ELF.h:56
@ EI_NIDENT
Definition: ELF.h:61
@ EI_CLASS
Definition: ELF.h:55
@ EM_MIPS
Definition: ELF.h:146
@ VER_NDX_GLOBAL
Definition: ELF.h:1706
@ VERSYM_VERSION
Definition: ELF.h:1707
@ VER_NDX_LOCAL
Definition: ELF.h:1705
@ VERSYM_HIDDEN
Definition: ELF.h:1708
constexpr unsigned CREL_HDR_ADDEND
Definition: ELF.h:2045
@ SHT_STRTAB
Definition: ELF.h:1142
@ SHT_PROGBITS
Definition: ELF.h:1140
@ SHT_NOBITS
Definition: ELF.h:1147
@ SHT_SYMTAB
Definition: ELF.h:1141
@ SHT_SYMTAB_SHNDX
Definition: ELF.h:1155
@ SHT_NOTE
Definition: ELF.h:1146
@ SHT_DYNSYM
Definition: ELF.h:1150
@ ELFDATANONE
Definition: ELF.h:339
@ ELFDATA2LSB
Definition: ELF.h:340
@ PF_X
Definition: ELF.h:1600
@ SHN_XINDEX
Definition: ELF.h:1133
@ SHN_UNDEF
Definition: ELF.h:1125
@ SHN_LORESERVE
Definition: ELF.h:1126
@ SHF_ALLOC
Definition: ELF.h:1240
@ SHF_TLS
Definition: ELF.h:1265
@ SHF_EXECINSTR
Definition: ELF.h:1243
@ PT_LOAD
Definition: ELF.h:1550
@ PT_TLS
Definition: ELF.h:1556
@ PT_NOTE
Definition: ELF.h:1553
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:547
Expected< const typename ELFT::Shdr * > getSection(typename ELFT::ShdrRange Sections, uint32_t Index)
Definition: ELF.h:539
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:802
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:1369
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
@ BCTR
Definition: ELF.h:95
@ 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
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:1357
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
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ 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:1702
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:2491
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
@ 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:769
const char * toString(DWARFSectionKind Kind)
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
const T * First
Definition: ELF.h:125
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