1#pragma once
2
3#if defined(__ELF__) && !defined(__FreeBSD__)
4
5#include <IO/MMapReadBufferFromFile.h>
6
7#include <string>
8#include <optional>
9#include <functional>
10
11#include <elf.h>
12#include <link.h>
13
14
15using ElfAddr = ElfW(Addr);
16using ElfEhdr = ElfW(Ehdr);
17using ElfOff = ElfW(Off);
18using ElfPhdr = ElfW(Phdr);
19using ElfShdr = ElfW(Shdr);
20using ElfSym = ElfW(Sym);
21
22
23namespace DB
24{
25
26/** Allow to navigate sections in ELF.
27 */
28class Elf final
29{
30public:
31 struct Section
32 {
33 const ElfShdr & header;
34 const char * name() const;
35
36 const char * begin() const;
37 const char * end() const;
38 size_t size() const;
39
40 Section(const ElfShdr & header_, const Elf & elf_);
41
42 private:
43 const Elf & elf;
44 };
45
46 explicit Elf(const std::string & path);
47
48 bool iterateSections(std::function<bool(const Section & section, size_t idx)> && pred) const;
49 std::optional<Section> findSection(std::function<bool(const Section & section, size_t idx)> && pred) const;
50 std::optional<Section> findSectionByName(const char * name) const;
51
52 const char * begin() const { return mapped; }
53 const char * end() const { return mapped + elf_size; }
54 size_t size() const { return elf_size; }
55
56private:
57 MMapReadBufferFromFile in;
58 size_t elf_size;
59 const char * mapped;
60 const ElfEhdr * header;
61 const ElfShdr * section_headers;
62 const char * section_names = nullptr;
63};
64
65}
66
67#endif
68