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