477d8798b512f50968a6825081ecfb427748f238
[folly.git] / folly / experimental / symbolizer / Elf.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 // ELF file parser
18
19 #pragma once
20 #define FOLLY_EXPERIMENTAL_SYMBOLIZER_ELF_H_
21
22 #include <elf.h>
23 #include <link.h> // For ElfW()
24
25 #include <cstdio>
26 #include <initializer_list>
27 #include <stdexcept>
28 #include <system_error>
29
30 #include <folly/Conv.h>
31 #include <folly/Likely.h>
32 #include <folly/Range.h>
33 #include <folly/lang/SafeAssert.h>
34
35 namespace folly {
36 namespace symbolizer {
37
38 using ElfAddr = ElfW(Addr);
39 using ElfEhdr = ElfW(Ehdr);
40 using ElfOff = ElfW(Off);
41 using ElfPhdr = ElfW(Phdr);
42 using ElfShdr = ElfW(Shdr);
43 using ElfSym = ElfW(Sym);
44
45 /**
46  * ELF file parser.
47  *
48  * We handle native files only (32-bit files on a 32-bit platform, 64-bit files
49  * on a 64-bit platform), and only executables (ET_EXEC) and shared objects
50  * (ET_DYN).
51  */
52 class ElfFile {
53  public:
54   ElfFile() noexcept;
55
56   // Note: may throw, call openNoThrow() explicitly if you don't want to throw
57   explicit ElfFile(const char* name, bool readOnly = true);
58
59   // Open the ELF file.
60   // Returns 0 on success, kSystemError (guaranteed to be -1) (and sets errno)
61   // on IO error, kInvalidElfFile (and sets errno to EINVAL) for an invalid
62   // Elf file. On error, if msg is not nullptr, sets *msg to a static string
63   // indicating what failed.
64   enum {
65     kSuccess = 0,
66     kSystemError = -1,
67     kInvalidElfFile = -2,
68   };
69   // Open the ELF file. Does not throw on error.
70   int openNoThrow(
71       const char* name,
72       bool readOnly = true,
73       const char** msg = nullptr) noexcept;
74
75   // Like openNoThrow, but follow .gnu_debuglink if present
76   int openAndFollow(
77       const char* name,
78       bool readOnly = true,
79       const char** msg = nullptr) noexcept;
80
81   // Open the ELF file. Throws on error.
82   void open(const char* name, bool readOnly = true);
83
84   ~ElfFile();
85
86   ElfFile(ElfFile&& other) noexcept;
87   ElfFile& operator=(ElfFile&& other);
88
89   /** Retrieve the ELF header */
90   const ElfEhdr& elfHeader() const {
91     return at<ElfEhdr>(0);
92   }
93
94   /**
95    * Get the base address, the address where the file should be loaded if
96    * no relocations happened.
97    */
98   uintptr_t getBaseAddress() const {
99     return baseAddress_;
100   }
101
102   /** Find a section given its name */
103   const ElfShdr* getSectionByName(const char* name) const;
104
105   /** Find a section given its index in the section header table */
106   const ElfShdr* getSectionByIndex(size_t idx) const;
107
108   /** Retrieve the name of a section */
109   const char* getSectionName(const ElfShdr& section) const;
110
111   /** Get the actual section body */
112   folly::StringPiece getSectionBody(const ElfShdr& section) const;
113
114   /** Retrieve a string from a string table section */
115   const char* getString(const ElfShdr& stringTable, size_t offset) const;
116
117   /**
118    * Iterate over all strings in a string table section for as long as
119    * fn(str) returns false.
120    * Returns the current ("found") string when fn returned true, or nullptr
121    * if fn returned false for all strings in the table.
122    */
123   template <class Fn>
124   const char* iterateStrings(const ElfShdr& stringTable, Fn fn) const;
125
126   /**
127    * Iterate over program headers as long as fn(section) returns false.
128    * Returns a pointer to the current ("found") section when fn returned
129    * true, or nullptr if fn returned false for all sections.
130    */
131   template <class Fn>
132   const ElfPhdr* iterateProgramHeaders(Fn fn) const;
133
134   /**
135    * Iterate over all sections for as long as fn(section) returns false.
136    * Returns a pointer to the current ("found") section when fn returned
137    * true, or nullptr if fn returned false for all sections.
138    */
139   template <class Fn>
140   const ElfShdr* iterateSections(Fn fn) const;
141
142   /**
143    * Iterate over all sections with a given type.  Similar to
144    * iterateSections(), but filtered only for sections with the given type.
145    */
146   template <class Fn>
147   const ElfShdr* iterateSectionsWithType(uint32_t type, Fn fn) const;
148
149   /**
150    * Iterate over all symbols witin a given section.
151    *
152    * Returns a pointer to the current ("found") symbol when fn returned true,
153    * or nullptr if fn returned false for all symbols.
154    */
155   template <class Fn>
156   const ElfSym* iterateSymbols(const ElfShdr& section, Fn fn) const;
157   template <class Fn>
158   const ElfSym*
159   iterateSymbolsWithType(const ElfShdr& section, uint32_t type, Fn fn) const;
160   template <class Fn>
161   const ElfSym* iterateSymbolsWithTypes(
162       const ElfShdr& section,
163       std::initializer_list<uint32_t> types,
164       Fn fn) const;
165
166   /**
167    * Find symbol definition by address.
168    * Note that this is the file virtual address, so you need to undo
169    * any relocation that might have happened.
170    *
171    * Returns {nullptr, nullptr} if not found.
172    */
173   typedef std::pair<const ElfShdr*, const ElfSym*> Symbol;
174   Symbol getDefinitionByAddress(uintptr_t address) const;
175
176   /**
177    * Find symbol definition by name.
178    *
179    * If a symbol with this name cannot be found, a <nullptr, nullptr> Symbol
180    * will be returned. This is O(N) in the number of symbols in the file.
181    *
182    * Returns {nullptr, nullptr} if not found.
183    */
184   Symbol getSymbolByName(const char* name) const;
185
186   /**
187    * Get the value of a symbol.
188    */
189   template <class T>
190   const T& getSymbolValue(const ElfSym* symbol) const {
191     const ElfShdr* section = getSectionByIndex(symbol->st_shndx);
192     FOLLY_SAFE_CHECK(section, "Symbol's section index is invalid");
193
194     return valueAt<T>(*section, symbol->st_value);
195   }
196
197   /**
198    * Get the value of the object stored at the given address.
199    *
200    * This is the function that you want to use in conjunction with
201    * getSymbolValue() to follow pointers. For example, to get the value of
202    * a char* symbol, you'd do something like this:
203    *
204    *  auto sym = getSymbolByName("someGlobalValue");
205    *  auto addr = getSymbolValue<ElfAddr>(sym.second);
206    *  const char* str = &getSymbolValue<const char>(addr);
207    */
208   template <class T>
209   const T& getAddressValue(const ElfAddr addr) const {
210     const ElfShdr* section = getSectionContainingAddress(addr);
211     FOLLY_SAFE_CHECK(section, "Address does not refer to existing section");
212
213     return valueAt<T>(*section, addr);
214   }
215
216   /**
217    * Retrieve symbol name.
218    */
219   const char* getSymbolName(Symbol symbol) const;
220
221   /** Find the section containing the given address */
222   const ElfShdr* getSectionContainingAddress(ElfAddr addr) const;
223
224  private:
225   bool init(const char** msg);
226   void reset();
227   ElfFile(const ElfFile&) = delete;
228   ElfFile& operator=(const ElfFile&) = delete;
229
230   void validateStringTable(const ElfShdr& stringTable) const;
231
232   template <class T>
233   const typename std::enable_if<std::is_pod<T>::value, T>::type& at(
234       ElfOff offset) const {
235     FOLLY_SAFE_CHECK(
236         offset + sizeof(T) <= length_,
237         "Offset is not contained within our mmapped file");
238
239     return *reinterpret_cast<T*>(file_ + offset);
240   }
241
242   template <class T>
243   const T& valueAt(const ElfShdr& section, const ElfAddr addr) const {
244     // For exectuables and shared objects, st_value holds a virtual address
245     // that refers to the memory owned by sections. Since we didn't map the
246     // sections into the addresses that they're expecting (sh_addr), but
247     // instead just mmapped the entire file directly, we need to translate
248     // between addresses and offsets into the file.
249     //
250     // TODO: For other file types, st_value holds a file offset directly. Since
251     //       I don't have a use-case for that right now, just assert that
252     //       nobody wants this. We can always add it later.
253     FOLLY_SAFE_CHECK(
254         elfHeader().e_type == ET_EXEC || elfHeader().e_type == ET_DYN,
255         "Only exectuables and shared objects are supported");
256     FOLLY_SAFE_CHECK(
257         addr >= section.sh_addr &&
258             (addr + sizeof(T)) <= (section.sh_addr + section.sh_size),
259         "Address is not contained within the provided segment");
260
261     return at<T>(section.sh_offset + (addr - section.sh_addr));
262   }
263
264   int fd_;
265   char* file_; // mmap() location
266   size_t length_; // mmap() length
267
268   uintptr_t baseAddress_;
269 };
270
271 } // namespace symbolizer
272 } // namespace folly
273
274 #include <folly/experimental/symbolizer/Elf-inl.h>