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