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