2 * Copyright 2013 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.
19 #ifndef FOLLY_EXPERIMENTAL_SYMBOLIZER_ELF_H_
20 #define FOLLY_EXPERIMENTAL_SYMBOLIZER_ELF_H_
24 #include <link.h> // For ElfW()
27 #include <system_error>
29 #include "folly/Likely.h"
30 #include "folly/Range.h"
31 #include "folly/Conv.h"
34 namespace symbolizer {
36 template <class... Args>
37 inline void enforce(bool v, Args... args) {
39 throw std::runtime_error(folly::to<std::string>(args...));
46 * We handle native files only (32-bit files on a 32-bit platform, 64-bit files
47 * on a 64-bit platform), and only executables (ET_EXEC) and shared objects
53 explicit ElfFile(const char* name, bool readOnly=true);
56 ElfFile(ElfFile&& other);
57 ElfFile& operator=(ElfFile&& other);
59 /** Retrieve the ELF header */
60 const ElfW(Ehdr)& elfHeader() const {
61 return at<ElfW(Ehdr)>(0);
65 * Get the base address, the address where the file should be loaded if
66 * no relocations happened.
68 uintptr_t getBaseAddress() const {
72 /** Find a section given its name */
73 const ElfW(Shdr)* getSectionByName(const char* name) const;
75 /** Find a section given its index in the section header table */
76 const ElfW(Shdr)* getSectionByIndex(size_t idx) const;
78 /** Retrieve the name of a section */
79 const char* getSectionName(const ElfW(Shdr)& section) const;
81 /** Get the actual section body */
82 folly::StringPiece getSectionBody(const ElfW(Shdr)& section) const;
84 /** Retrieve a string from a string table section */
85 const char* getString(const ElfW(Shdr)& stringTable, size_t offset) const;
88 * Iterate over all strings in a string table section for as long as
89 * fn(str) returns false.
90 * Returns the current ("found") string when fn returned true, or nullptr
91 * if fn returned false for all strings in the table.
94 const char* iterateStrings(const ElfW(Shdr)& stringTable, Fn fn) const;
97 * Iterate over all sections for as long as fn(section) returns false.
98 * Returns a pointer to the current ("found") section when fn returned
99 * true, or nullptr if fn returned false for all sections.
102 const ElfW(Shdr)* iterateSections(Fn fn) const;
105 * Iterate over all sections with a given type. Similar to
106 * iterateSections(), but filtered only for sections with the given type.
109 const ElfW(Shdr)* iterateSectionsWithType(uint32_t type, Fn fn) const;
112 * Iterate over all symbols witin a given section.
114 * Returns a pointer to the current ("found") symbol when fn returned true,
115 * or nullptr if fn returned false for all symbols.
118 const ElfW(Sym)* iterateSymbols(const ElfW(Shdr)& section, Fn fn) const;
120 const ElfW(Sym)* iterateSymbolsWithType(const ElfW(Shdr)& section,
121 uint32_t type, Fn fn) const;
124 * Find symbol definition by address.
125 * Note that this is the file virtual address, so you need to undo
126 * any relocation that might have happened.
128 typedef std::pair<const ElfW(Shdr)*, const ElfW(Sym)*> Symbol;
129 Symbol getDefinitionByAddress(uintptr_t address) const;
132 * Find symbol definition by name.
134 * If a symbol with this name cannot be found, a <nullptr, nullptr> Symbol
135 * will be returned. This is O(N) in the number of symbols in the file.
137 Symbol getSymbolByName(const char* name) const;
140 * Get the value of a symbol.
143 const T& getSymbolValue(const ElfW(Sym)* symbol) const {
144 const ElfW(Shdr)* section = getSectionByIndex(symbol->st_shndx);
145 enforce(section, "Symbol's section index is invalid");
147 return valueAt<T>(*section, symbol->st_value);
151 * Get the value of the object stored at the given address.
153 * This is the function that you want to use in conjunction with
154 * getSymbolValue() to follow pointers. For example, to get the value of
155 * a char* symbol, you'd do something like this:
157 * auto sym = getSymbolByName("someGlobalValue");
158 * auto addr = getSymbolValue<ElfW(Addr)>(sym.second);
159 * const char* str = &getSymbolValue<const char>(addr);
162 const T& getAddressValue(const ElfW(Addr) addr) const {
163 const ElfW(Shdr)* section = getSectionContainingAddress(addr);
164 enforce(section, "Address does not refer to existing section");
166 return valueAt<T>(*section, addr);
170 * Retrieve symbol name.
172 const char* getSymbolName(Symbol symbol) const;
174 /** Find the section containing the given address */
175 const ElfW(Shdr)* getSectionContainingAddress(ElfW(Addr) addr) const;
180 ElfFile(const ElfFile&) = delete;
181 ElfFile& operator=(const ElfFile&) = delete;
183 void validateStringTable(const ElfW(Shdr)& stringTable) const;
186 const typename std::enable_if<std::is_pod<T>::value, T>::type&
187 at(ElfW(Off) offset) const {
188 enforce(offset + sizeof(T) <= length_,
189 "Offset is not contained within our mmapped file");
191 return *reinterpret_cast<T*>(file_ + offset);
195 const T& valueAt(const ElfW(Shdr)& section, const ElfW(Addr) addr) const {
196 // For exectuables and shared objects, st_value holds a virtual address
197 // that refers to the memory owned by sections. Since we didn't map the
198 // sections into the addresses that they're expecting (sh_addr), but
199 // instead just mmapped the entire file directly, we need to translate
200 // between addresses and offsets into the file.
202 // TODO: For other file types, st_value holds a file offset directly. Since
203 // I don't have a use-case for that right now, just assert that
204 // nobody wants this. We can always add it later.
205 enforce(elfHeader().e_type == ET_EXEC || elfHeader().e_type == ET_DYN,
206 "Only exectuables and shared objects are supported");
207 enforce(addr >= section.sh_addr &&
208 (addr + sizeof(T)) <= (section.sh_addr + section.sh_size),
209 "Address is not contained within the provided segment");
211 return at<T>(section.sh_offset + (addr - section.sh_addr));
215 char* file_; // mmap() location
216 size_t length_; // mmap() length
218 uintptr_t baseAddress_;
221 } // namespace symbolizer
224 #include "folly/experimental/symbolizer/Elf-inl.h"
226 #endif /* FOLLY_EXPERIMENTAL_SYMBOLIZER_ELF_H_ */