Fix ElfFile crashing when opening short (<64 bytes) files.
[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   if (length_ < 4) {
197     if (msg) {
198       *msg = "not an ELF file (too short)";
199     }
200     return false;
201   }
202
203   // Validate ELF magic numbers
204   if (file_[EI_MAG0] != ELFMAG0 || file_[EI_MAG1] != ELFMAG1 ||
205       file_[EI_MAG2] != ELFMAG2 || file_[EI_MAG3] != ELFMAG3) {
206     if (msg) {
207       *msg = "invalid ELF magic";
208     }
209     return false;
210   }
211
212   auto& elfHeader = this->elfHeader();
213
214 #define EXPECTED_CLASS P1(ELFCLASS, __ELF_NATIVE_CLASS)
215 #define P1(a, b) P2(a, b)
216 #define P2(a, b) a##b
217   // Validate ELF class (32/64 bits)
218   if (elfHeader.e_ident[EI_CLASS] != EXPECTED_CLASS) {
219     if (msg) {
220       *msg = "invalid ELF class";
221     }
222     return false;
223   }
224 #undef P1
225 #undef P2
226 #undef EXPECTED_CLASS
227
228   // Validate ELF data encoding (LSB/MSB)
229   static constexpr auto kExpectedEncoding =
230       kIsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
231   if (elfHeader.e_ident[EI_DATA] != kExpectedEncoding) {
232     if (msg) {
233       *msg = "invalid ELF encoding";
234     }
235     return false;
236   }
237
238   // Validate ELF version (1)
239   if (elfHeader.e_ident[EI_VERSION] != EV_CURRENT ||
240       elfHeader.e_version != EV_CURRENT) {
241     if (msg) {
242       *msg = "invalid ELF version";
243     }
244     return false;
245   }
246
247   // We only support executable and shared object files
248   if (elfHeader.e_type != ET_EXEC && elfHeader.e_type != ET_DYN) {
249     if (msg) {
250       *msg = "invalid ELF file type";
251     }
252     return false;
253   }
254
255   if (elfHeader.e_phnum == 0) {
256     if (msg) {
257       *msg = "no program header!";
258     }
259     return false;
260   }
261
262   if (elfHeader.e_phentsize != sizeof(ElfPhdr)) {
263     if (msg) {
264       *msg = "invalid program header entry size";
265     }
266     return false;
267   }
268
269   if (elfHeader.e_shentsize != sizeof(ElfShdr)) {
270     if (msg) {
271       *msg = "invalid section header entry size";
272     }
273   }
274
275   // Program headers are sorted by load address, so the first PT_LOAD
276   // header gives us the base address.
277   const ElfPhdr* programHeader =
278       iterateProgramHeaders([](auto& h) { return h.p_type == PT_LOAD; });
279
280   if (!programHeader) {
281     if (msg) {
282       *msg = "could not find base address";
283     }
284     return false;
285   }
286   baseAddress_ = programHeader->p_vaddr;
287
288   return true;
289 }
290
291 const ElfShdr* ElfFile::getSectionByIndex(size_t idx) const {
292   FOLLY_SAFE_CHECK(idx < elfHeader().e_shnum, "invalid section index");
293   return &at<ElfShdr>(elfHeader().e_shoff + idx * sizeof(ElfShdr));
294 }
295
296 folly::StringPiece ElfFile::getSectionBody(const ElfShdr& section) const {
297   return folly::StringPiece(file_ + section.sh_offset, section.sh_size);
298 }
299
300 void ElfFile::validateStringTable(const ElfShdr& stringTable) const {
301   FOLLY_SAFE_CHECK(
302       stringTable.sh_type == SHT_STRTAB, "invalid type for string table");
303
304   const char* start = file_ + stringTable.sh_offset;
305   // First and last bytes must be 0
306   FOLLY_SAFE_CHECK(
307       stringTable.sh_size == 0 ||
308           (start[0] == '\0' && start[stringTable.sh_size - 1] == '\0'),
309       "invalid string table");
310 }
311
312 const char* ElfFile::getString(const ElfShdr& stringTable, size_t offset)
313     const {
314   validateStringTable(stringTable);
315   FOLLY_SAFE_CHECK(
316       offset < stringTable.sh_size, "invalid offset in string table");
317
318   return file_ + stringTable.sh_offset + offset;
319 }
320
321 const char* ElfFile::getSectionName(const ElfShdr& section) const {
322   if (elfHeader().e_shstrndx == SHN_UNDEF) {
323     return nullptr; // no section name string table
324   }
325
326   const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
327   return getString(sectionNames, section.sh_name);
328 }
329
330 const ElfShdr* ElfFile::getSectionByName(const char* name) const {
331   if (elfHeader().e_shstrndx == SHN_UNDEF) {
332     return nullptr; // no section name string table
333   }
334
335   // Find offset in the section name string table of the requested name
336   const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
337   const char* foundName = iterateStrings(
338       sectionNames, [&](const char* s) { return !strcmp(name, s); });
339   if (foundName == nullptr) {
340     return nullptr;
341   }
342
343   size_t offset = foundName - (file_ + sectionNames.sh_offset);
344
345   // Find section with the appropriate sh_name offset
346   const ElfShdr* foundSection = iterateSections([&](const ElfShdr& sh) {
347     if (sh.sh_name == offset) {
348       return true;
349     }
350     return false;
351   });
352   return foundSection;
353 }
354
355 ElfFile::Symbol ElfFile::getDefinitionByAddress(uintptr_t address) const {
356   Symbol foundSymbol{nullptr, nullptr};
357
358   auto findSection = [&](const ElfShdr& section) {
359     auto findSymbols = [&](const ElfSym& sym) {
360       if (sym.st_shndx == SHN_UNDEF) {
361         return false; // not a definition
362       }
363       if (address >= sym.st_value && address < sym.st_value + sym.st_size) {
364         foundSymbol.first = &section;
365         foundSymbol.second = &sym;
366         return true;
367       }
368
369       return false;
370     };
371
372     return iterateSymbolsWithTypes(
373         section, {STT_OBJECT, STT_FUNC, STT_GNU_IFUNC}, findSymbols);
374   };
375
376   // Try the .dynsym section first if it exists, it's smaller.
377   (iterateSectionsWithType(SHT_DYNSYM, findSection) ||
378    iterateSectionsWithType(SHT_SYMTAB, findSection));
379
380   return foundSymbol;
381 }
382
383 ElfFile::Symbol ElfFile::getSymbolByName(const char* name) const {
384   Symbol foundSymbol{nullptr, nullptr};
385
386   auto findSection = [&](const ElfShdr& section) -> bool {
387     // This section has no string table associated w/ its symbols; hence we
388     // can't get names for them
389     if (section.sh_link == SHN_UNDEF) {
390       return false;
391     }
392
393     auto findSymbols = [&](const ElfSym& sym) -> bool {
394       if (sym.st_shndx == SHN_UNDEF) {
395         return false; // not a definition
396       }
397       if (sym.st_name == 0) {
398         return false; // no name for this symbol
399       }
400       const char* sym_name =
401           getString(*getSectionByIndex(section.sh_link), sym.st_name);
402       if (strcmp(sym_name, name) == 0) {
403         foundSymbol.first = &section;
404         foundSymbol.second = &sym;
405         return true;
406       }
407
408       return false;
409     };
410
411     return iterateSymbolsWithTypes(
412         section, {STT_OBJECT, STT_FUNC, STT_GNU_IFUNC}, findSymbols);
413   };
414
415   // Try the .dynsym section first if it exists, it's smaller.
416   iterateSectionsWithType(SHT_DYNSYM, findSection) ||
417       iterateSectionsWithType(SHT_SYMTAB, findSection);
418
419   return foundSymbol;
420 }
421
422 const ElfShdr* ElfFile::getSectionContainingAddress(ElfAddr addr) const {
423   return iterateSections([&](const ElfShdr& sh) -> bool {
424     return (addr >= sh.sh_addr) && (addr < (sh.sh_addr + sh.sh_size));
425   });
426 }
427
428 const char* ElfFile::getSymbolName(Symbol symbol) const {
429   if (!symbol.first || !symbol.second) {
430     return nullptr;
431   }
432
433   if (symbol.second->st_name == 0) {
434     return nullptr; // symbol has no name
435   }
436
437   if (symbol.first->sh_link == SHN_UNDEF) {
438     return nullptr; // symbol table has no strings
439   }
440
441   return getString(
442       *getSectionByIndex(symbol.first->sh_link), symbol.second->st_name);
443 }
444
445 } // namespace symbolizer
446 } // namespace folly