b4b76e13ed3a6ac97fca6677b4432ce789595b49
[folly.git] / folly / experimental / symbolizer / Elf.cpp
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
18 #include <folly/experimental/symbolizer/Elf.h>
19
20 #include <sys/mman.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <fcntl.h>
24
25 #include <string>
26
27 #include <glog/logging.h>
28
29 #include <folly/Conv.h>
30 #include <folly/Exception.h>
31
32 namespace folly {
33 namespace symbolizer {
34
35 ElfFile::ElfFile() noexcept
36   : fd_(-1),
37     file_(static_cast<char*>(MAP_FAILED)),
38     length_(0),
39     baseAddress_(0) {
40 }
41
42 ElfFile::ElfFile(const char* name, bool readOnly)
43   : fd_(-1),
44     file_(static_cast<char*>(MAP_FAILED)),
45     length_(0),
46     baseAddress_(0) {
47   open(name, readOnly);
48 }
49
50 void ElfFile::open(const char* name, bool readOnly) {
51   const char* msg = "";
52   int r = openNoThrow(name, readOnly, &msg);
53   if (r == kSystemError) {
54     throwSystemError(msg);
55   } else {
56     CHECK_EQ(r, kSuccess) << msg;
57   }
58 }
59
60 int ElfFile::openNoThrow(const char* name, bool readOnly, const char** msg)
61   noexcept {
62   FOLLY_SAFE_CHECK(fd_ == -1, "File already open");
63   fd_ = ::open(name, readOnly ? O_RDONLY : O_RDWR);
64   if (fd_ == -1) {
65     if (msg) *msg = "open";
66     return kSystemError;
67   }
68
69   struct stat st;
70   int r = fstat(fd_, &st);
71   if (r == -1) {
72     if (msg) *msg = "fstat";
73     return kSystemError;
74   }
75
76   length_ = st.st_size;
77   int prot = PROT_READ;
78   if (!readOnly) {
79     prot |= PROT_WRITE;
80   }
81   file_ = static_cast<char*>(mmap(nullptr, length_, prot, MAP_SHARED, fd_, 0));
82   if (file_ == MAP_FAILED) {
83     if (msg) *msg = "mmap";
84     return kSystemError;
85   }
86   if (!init(msg)) {
87     errno = EINVAL;
88     return kInvalidElfFile;
89   }
90
91   return kSuccess;
92 }
93
94 ElfFile::~ElfFile() {
95   destroy();
96 }
97
98 ElfFile::ElfFile(ElfFile&& other) noexcept
99   : fd_(other.fd_),
100     file_(other.file_),
101     length_(other.length_),
102     baseAddress_(other.baseAddress_) {
103   other.fd_ = -1;
104   other.file_ = static_cast<char*>(MAP_FAILED);
105   other.length_ = 0;
106   other.baseAddress_ = 0;
107 }
108
109 ElfFile& ElfFile::operator=(ElfFile&& other) {
110   assert(this != &other);
111   destroy();
112
113   fd_ = other.fd_;
114   file_ = other.file_;
115   length_ = other.length_;
116   baseAddress_ = other.baseAddress_;
117
118   other.fd_ = -1;
119   other.file_ = static_cast<char*>(MAP_FAILED);
120   other.length_ = 0;
121   other.baseAddress_ = 0;
122
123   return *this;
124 }
125
126 void ElfFile::destroy() {
127   if (file_ != MAP_FAILED) {
128     munmap(file_, length_);
129   }
130
131   if (fd_ != -1) {
132     close(fd_);
133   }
134 }
135
136 bool ElfFile::init(const char** msg) {
137   auto& elfHeader = this->elfHeader();
138
139   // Validate ELF magic numbers
140   if (!(elfHeader.e_ident[EI_MAG0] == ELFMAG0 &&
141         elfHeader.e_ident[EI_MAG1] == ELFMAG1 &&
142         elfHeader.e_ident[EI_MAG2] == ELFMAG2 &&
143         elfHeader.e_ident[EI_MAG3] == ELFMAG3)) {
144     if (msg) *msg = "invalid ELF magic";
145     return false;
146   }
147
148   // Validate ELF class (32/64 bits)
149 #define EXPECTED_CLASS P1(ELFCLASS, __ELF_NATIVE_CLASS)
150 #define P1(a, b) P2(a, b)
151 #define P2(a, b) a ## b
152   if (elfHeader.e_ident[EI_CLASS] != EXPECTED_CLASS) {
153     if (msg) *msg = "invalid ELF class";
154     return false;
155   }
156 #undef P1
157 #undef P2
158 #undef EXPECTED_CLASS
159
160   // Validate ELF data encoding (LSB/MSB)
161 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
162 # define EXPECTED_ENCODING ELFDATA2LSB
163 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
164 # define EXPECTED_ENCODING ELFDATA2MSB
165 #else
166 # error Unsupported byte order
167 #endif
168   if (elfHeader.e_ident[EI_DATA] != EXPECTED_ENCODING) {
169     if (msg) *msg = "invalid ELF encoding";
170     return false;
171   }
172 #undef EXPECTED_ENCODING
173
174   // Validate ELF version (1)
175   if (elfHeader.e_ident[EI_VERSION] != EV_CURRENT ||
176       elfHeader.e_version != EV_CURRENT) {
177     if (msg) *msg = "invalid ELF version";
178     return false;
179   }
180
181   // We only support executable and shared object files
182   if (elfHeader.e_type != ET_EXEC && elfHeader.e_type != ET_DYN) {
183     if (msg) *msg = "invalid ELF file type";
184     return false;
185   }
186
187   if (elfHeader.e_phnum == 0) {
188     if (msg) *msg = "no program header!";
189     return false;
190   }
191
192   if (elfHeader.e_phentsize != sizeof(ElfW(Phdr))) {
193     if (msg) *msg = "invalid program header entry size";
194     return false;
195   }
196
197   if (elfHeader.e_shentsize != sizeof(ElfW(Shdr))) {
198     if (msg) *msg = "invalid section header entry size";
199   }
200
201   const ElfW(Phdr)* programHeader = &at<ElfW(Phdr)>(elfHeader.e_phoff);
202   bool foundBase = false;
203   for (size_t i = 0; i < elfHeader.e_phnum; programHeader++, i++) {
204     // Program headers are sorted by load address, so the first PT_LOAD
205     // header gives us the base address.
206     if (programHeader->p_type == PT_LOAD) {
207       baseAddress_ = programHeader->p_vaddr;
208       foundBase = true;
209       break;
210     }
211   }
212
213   if (!foundBase) {
214     if (msg) *msg =  "could not find base address";
215     return false;
216   }
217
218   return true;
219 }
220
221 const ElfW(Shdr)* ElfFile::getSectionByIndex(size_t idx) const {
222   FOLLY_SAFE_CHECK(idx < elfHeader().e_shnum, "invalid section index");
223   return &at<ElfW(Shdr)>(elfHeader().e_shoff + idx * sizeof(ElfW(Shdr)));
224 }
225
226 folly::StringPiece ElfFile::getSectionBody(const ElfW(Shdr)& section) const {
227   return folly::StringPiece(file_ + section.sh_offset, section.sh_size);
228 }
229
230 void ElfFile::validateStringTable(const ElfW(Shdr)& stringTable) const {
231   FOLLY_SAFE_CHECK(stringTable.sh_type == SHT_STRTAB,
232                    "invalid type for string table");
233
234   const char* start = file_ + stringTable.sh_offset;
235   // First and last bytes must be 0
236   FOLLY_SAFE_CHECK(stringTable.sh_size == 0 ||
237                    (start[0] == '\0' && start[stringTable.sh_size - 1] == '\0'),
238                    "invalid string table");
239 }
240
241 const char* ElfFile::getString(const ElfW(Shdr)& stringTable, size_t offset)
242   const {
243   validateStringTable(stringTable);
244   FOLLY_SAFE_CHECK(offset < stringTable.sh_size,
245                    "invalid offset in string table");
246
247   return file_ + stringTable.sh_offset + offset;
248 }
249
250 const char* ElfFile::getSectionName(const ElfW(Shdr)& section) const {
251   if (elfHeader().e_shstrndx == SHN_UNDEF) {
252     return nullptr;  // no section name string table
253   }
254
255   const ElfW(Shdr)& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
256   return getString(sectionNames, section.sh_name);
257 }
258
259 const ElfW(Shdr)* ElfFile::getSectionByName(const char* name) const {
260   if (elfHeader().e_shstrndx == SHN_UNDEF) {
261     return nullptr;  // no section name string table
262   }
263
264   // Find offset in the section name string table of the requested name
265   const ElfW(Shdr)& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
266   const char* foundName = iterateStrings(
267       sectionNames,
268       [&] (const char* s) { return !strcmp(name, s); });
269   if (foundName == nullptr) {
270     return nullptr;
271   }
272
273   size_t offset = foundName - (file_ + sectionNames.sh_offset);
274
275   // Find section with the appropriate sh_name offset
276   const ElfW(Shdr)* foundSection = iterateSections(
277     [&](const ElfW(Shdr)& sh) {
278       if (sh.sh_name == offset) {
279         return true;
280       }
281       return false;
282     });
283   return foundSection;
284 }
285
286 ElfFile::Symbol ElfFile::getDefinitionByAddress(uintptr_t address) const {
287   Symbol foundSymbol {nullptr, nullptr};
288
289   auto findSection = [&](const ElfW(Shdr)& section) {
290     auto findSymbols = [&](const ElfW(Sym)& sym) {
291       if (sym.st_shndx == SHN_UNDEF) {
292         return false;  // not a definition
293       }
294       if (address >= sym.st_value && address < sym.st_value + sym.st_size) {
295         foundSymbol.first = &section;
296         foundSymbol.second = &sym;
297         return true;
298       }
299
300       return false;
301     };
302
303     return iterateSymbolsWithType(section, STT_OBJECT, findSymbols) ||
304       iterateSymbolsWithType(section, STT_FUNC, findSymbols);
305   };
306
307   // Try the .dynsym section first if it exists, it's smaller.
308   (iterateSectionsWithType(SHT_DYNSYM, findSection) ||
309    iterateSectionsWithType(SHT_SYMTAB, findSection));
310
311   return foundSymbol;
312 }
313
314 ElfFile::Symbol ElfFile::getSymbolByName(const char* name) const {
315   Symbol foundSymbol{nullptr, nullptr};
316
317   auto findSection = [&](const ElfW(Shdr)& section) -> bool {
318     // This section has no string table associated w/ its symbols; hence we
319     // can't get names for them
320     if (section.sh_link == SHN_UNDEF) {
321       return false;
322     }
323
324     auto findSymbols = [&](const ElfW(Sym)& sym) -> bool {
325       if (sym.st_shndx == SHN_UNDEF) {
326         return false;  // not a definition
327       }
328       if (sym.st_name == 0) {
329         return false;  // no name for this symbol
330       }
331       const char* sym_name = getString(
332         *getSectionByIndex(section.sh_link), sym.st_name);
333       if (strcmp(sym_name, name) == 0) {
334         foundSymbol.first = &section;
335         foundSymbol.second = &sym;
336         return true;
337       }
338
339       return false;
340     };
341
342     return iterateSymbolsWithType(section, STT_OBJECT, findSymbols) ||
343       iterateSymbolsWithType(section, STT_FUNC, findSymbols);
344   };
345
346   // Try the .dynsym section first if it exists, it's smaller.
347   iterateSectionsWithType(SHT_DYNSYM, findSection) ||
348     iterateSectionsWithType(SHT_SYMTAB, findSection);
349
350   return foundSymbol;
351 }
352
353 const ElfW(Shdr)* ElfFile::getSectionContainingAddress(ElfW(Addr) addr) const {
354   return iterateSections([&](const ElfW(Shdr)& sh) -> bool {
355     return (addr >= sh.sh_addr) && (addr < (sh.sh_addr + sh.sh_size));
356   });
357 }
358
359 const char* ElfFile::getSymbolName(Symbol symbol) const {
360   if (!symbol.first || !symbol.second) {
361     return nullptr;
362   }
363
364   if (symbol.second->st_name == 0) {
365     return nullptr;  // symbol has no name
366   }
367
368   if (symbol.first->sh_link == SHN_UNDEF) {
369     return nullptr;  // symbol table has no strings
370   }
371
372   return getString(*getSectionByIndex(symbol.first->sh_link),
373                    symbol.second->st_name);
374 }
375
376 }  // namespace symbolizer
377 }  // namespace folly
378