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