2 * Copyright 2015 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/Conv.h>
30 #include <folly/Likely.h>
31 #include <folly/Range.h>
32 #include <folly/SafeAssert.h>
35 namespace symbolizer {
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
48 // Note: may throw, call openNoThrow() explicitly if you don't want to throw
49 explicit ElfFile(const char* name, bool readOnly=true);
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.
61 int openNoThrow(const char* name, bool readOnly=true,
62 const char** msg=nullptr) noexcept;
64 // Open the ELF file. Throws on error.
65 void open(const char* name, bool readOnly=true);
69 ElfFile(ElfFile&& other) noexcept;
70 ElfFile& operator=(ElfFile&& other);
72 /** Retrieve the ELF header */
73 const ElfW(Ehdr)& elfHeader() const {
74 return at<ElfW(Ehdr)>(0);
78 * Get the base address, the address where the file should be loaded if
79 * no relocations happened.
81 uintptr_t getBaseAddress() const {
85 /** Find a section given its name */
86 const ElfW(Shdr)* getSectionByName(const char* name) const;
88 /** Find a section given its index in the section header table */
89 const ElfW(Shdr)* getSectionByIndex(size_t idx) const;
91 /** Retrieve the name of a section */
92 const char* getSectionName(const ElfW(Shdr)& section) const;
94 /** Get the actual section body */
95 folly::StringPiece getSectionBody(const ElfW(Shdr)& section) const;
97 /** Retrieve a string from a string table section */
98 const char* getString(const ElfW(Shdr)& stringTable, size_t offset) const;
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.
107 const char* iterateStrings(const ElfW(Shdr)& stringTable, Fn fn) const;
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.
115 const ElfW(Shdr)* iterateSections(Fn fn) const;
118 * Iterate over all sections with a given type. Similar to
119 * iterateSections(), but filtered only for sections with the given type.
122 const ElfW(Shdr)* iterateSectionsWithType(uint32_t type, Fn fn) const;
125 * Iterate over all symbols witin a given section.
127 * Returns a pointer to the current ("found") symbol when fn returned true,
128 * or nullptr if fn returned false for all symbols.
131 const ElfW(Sym)* iterateSymbols(const ElfW(Shdr)& section, Fn fn) const;
133 const ElfW(Sym)* iterateSymbolsWithType(const ElfW(Shdr)& section,
134 uint32_t type, Fn fn) const;
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.
141 * Returns {nullptr, nullptr} if not found.
143 typedef std::pair<const ElfW(Shdr)*, const ElfW(Sym)*> Symbol;
144 Symbol getDefinitionByAddress(uintptr_t address) const;
147 * Find symbol definition by name.
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.
152 * Returns {nullptr, nullptr} if not found.
154 Symbol getSymbolByName(const char* name) const;
157 * Get the value of a symbol.
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");
164 return valueAt<T>(*section, symbol->st_value);
168 * Get the value of the object stored at the given address.
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:
174 * auto sym = getSymbolByName("someGlobalValue");
175 * auto addr = getSymbolValue<ElfW(Addr)>(sym.second);
176 * const char* str = &getSymbolValue<const char>(addr);
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");
183 return valueAt<T>(*section, addr);
187 * Retrieve symbol name.
189 const char* getSymbolName(Symbol symbol) const;
191 /** Find the section containing the given address */
192 const ElfW(Shdr)* getSectionContainingAddress(ElfW(Addr) addr) const;
195 bool init(const char** msg);
197 ElfFile(const ElfFile&) = delete;
198 ElfFile& operator=(const ElfFile&) = delete;
200 void validateStringTable(const ElfW(Shdr)& stringTable) const;
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");
208 return *reinterpret_cast<T*>(file_ + offset);
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.
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.
223 elfHeader().e_type == ET_EXEC || elfHeader().e_type == ET_DYN,
224 "Only exectuables and shared objects are supported");
226 addr >= section.sh_addr &&
227 (addr + sizeof(T)) <= (section.sh_addr + section.sh_size),
228 "Address is not contained within the provided segment");
230 return at<T>(section.sh_offset + (addr - section.sh_addr));
234 char* file_; // mmap() location
235 size_t length_; // mmap() length
237 uintptr_t baseAddress_;
240 } // namespace symbolizer
243 #include <folly/experimental/symbolizer/Elf-inl.h>
245 #endif /* FOLLY_EXPERIMENTAL_SYMBOLIZER_ELF_H_ */