2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #define FOLLY_EXPERIMENTAL_SYMBOLIZER_ELF_H_
23 #include <link.h> // For ElfW()
26 #include <initializer_list>
28 #include <system_error>
30 #include <folly/Conv.h>
31 #include <folly/Likely.h>
32 #include <folly/Range.h>
33 #include <folly/lang/SafeAssert.h>
36 namespace symbolizer {
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);
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
56 // Note: may throw, call openNoThrow() explicitly if you don't want to throw
57 explicit ElfFile(const char* name, bool readOnly = true);
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.
69 // Open the ELF file. Does not throw on error.
73 const char** msg = nullptr) noexcept;
75 // Like openNoThrow, but follow .gnu_debuglink if present
79 const char** msg = nullptr) noexcept;
81 // Open the ELF file. Throws on error.
82 void open(const char* name, bool readOnly = true);
86 ElfFile(ElfFile&& other) noexcept;
87 ElfFile& operator=(ElfFile&& other);
89 /** Retrieve the ELF header */
90 const ElfEhdr& elfHeader() const {
91 return at<ElfEhdr>(0);
95 * Get the base address, the address where the file should be loaded if
96 * no relocations happened.
98 uintptr_t getBaseAddress() const {
102 /** Find a section given its name */
103 const ElfShdr* getSectionByName(const char* name) const;
105 /** Find a section given its index in the section header table */
106 const ElfShdr* getSectionByIndex(size_t idx) const;
108 /** Retrieve the name of a section */
109 const char* getSectionName(const ElfShdr& section) const;
111 /** Get the actual section body */
112 folly::StringPiece getSectionBody(const ElfShdr& section) const;
114 /** Retrieve a string from a string table section */
115 const char* getString(const ElfShdr& stringTable, size_t offset) const;
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.
124 const char* iterateStrings(const ElfShdr& stringTable, Fn fn) const;
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.
132 const ElfPhdr* iterateProgramHeaders(Fn fn) const;
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.
140 const ElfShdr* iterateSections(Fn fn) const;
143 * Iterate over all sections with a given type. Similar to
144 * iterateSections(), but filtered only for sections with the given type.
147 const ElfShdr* iterateSectionsWithType(uint32_t type, Fn fn) const;
150 * Iterate over all symbols witin a given section.
152 * Returns a pointer to the current ("found") symbol when fn returned true,
153 * or nullptr if fn returned false for all symbols.
156 const ElfSym* iterateSymbols(const ElfShdr& section, Fn fn) const;
159 iterateSymbolsWithType(const ElfShdr& section, uint32_t type, Fn fn) const;
161 const ElfSym* iterateSymbolsWithTypes(
162 const ElfShdr& section,
163 std::initializer_list<uint32_t> types,
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.
171 * Returns {nullptr, nullptr} if not found.
173 typedef std::pair<const ElfShdr*, const ElfSym*> Symbol;
174 Symbol getDefinitionByAddress(uintptr_t address) const;
177 * Find symbol definition by name.
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.
182 * Returns {nullptr, nullptr} if not found.
184 Symbol getSymbolByName(const char* name) const;
187 * Get the value of a symbol.
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");
194 return valueAt<T>(*section, symbol->st_value);
198 * Get the value of the object stored at the given address.
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:
204 * auto sym = getSymbolByName("someGlobalValue");
205 * auto addr = getSymbolValue<ElfAddr>(sym.second);
206 * const char* str = &getSymbolValue<const char>(addr);
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");
213 return valueAt<T>(*section, addr);
217 * Retrieve symbol name.
219 const char* getSymbolName(Symbol symbol) const;
221 /** Find the section containing the given address */
222 const ElfShdr* getSectionContainingAddress(ElfAddr addr) const;
225 bool init(const char** msg);
227 ElfFile(const ElfFile&) = delete;
228 ElfFile& operator=(const ElfFile&) = delete;
230 void validateStringTable(const ElfShdr& stringTable) const;
233 const typename std::enable_if<std::is_pod<T>::value, T>::type& at(
234 ElfOff offset) const {
236 offset + sizeof(T) <= length_,
237 "Offset is not contained within our mmapped file");
239 return *reinterpret_cast<T*>(file_ + offset);
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.
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.
254 elfHeader().e_type == ET_EXEC || elfHeader().e_type == ET_DYN,
255 "Only exectuables and shared objects are supported");
257 addr >= section.sh_addr &&
258 (addr + sizeof(T)) <= (section.sh_addr + section.sh_size),
259 "Address is not contained within the provided segment");
261 return at<T>(section.sh_offset + (addr - section.sh_addr));
265 char* file_; // mmap() location
266 size_t length_; // mmap() length
268 uintptr_t baseAddress_;
271 } // namespace symbolizer
274 #include <folly/experimental/symbolizer/Elf-inl.h>