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