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