Consistency in namespace-closing comments
[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   const ElfPhdr* programHeader = &at<ElfPhdr>(elfHeader.e_phoff);
267   bool foundBase = false;
268   for (size_t i = 0; i < elfHeader.e_phnum; programHeader++, i++) {
269     // Program headers are sorted by load address, so the first PT_LOAD
270     // header gives us the base address.
271     if (programHeader->p_type == PT_LOAD) {
272       baseAddress_ = programHeader->p_vaddr;
273       foundBase = true;
274       break;
275     }
276   }
277
278   if (!foundBase) {
279     if (msg) {
280       *msg = "could not find base address";
281     }
282     return false;
283   }
284
285   return true;
286 }
287
288 const ElfShdr* ElfFile::getSectionByIndex(size_t idx) const {
289   FOLLY_SAFE_CHECK(idx < elfHeader().e_shnum, "invalid section index");
290   return &at<ElfShdr>(elfHeader().e_shoff + idx * sizeof(ElfShdr));
291 }
292
293 folly::StringPiece ElfFile::getSectionBody(const ElfShdr& section) const {
294   return folly::StringPiece(file_ + section.sh_offset, section.sh_size);
295 }
296
297 void ElfFile::validateStringTable(const ElfShdr& stringTable) const {
298   FOLLY_SAFE_CHECK(
299       stringTable.sh_type == SHT_STRTAB, "invalid type for string table");
300
301   const char* start = file_ + stringTable.sh_offset;
302   // First and last bytes must be 0
303   FOLLY_SAFE_CHECK(
304       stringTable.sh_size == 0 ||
305           (start[0] == '\0' && start[stringTable.sh_size - 1] == '\0'),
306       "invalid string table");
307 }
308
309 const char* ElfFile::getString(const ElfShdr& stringTable, size_t offset)
310     const {
311   validateStringTable(stringTable);
312   FOLLY_SAFE_CHECK(
313       offset < stringTable.sh_size, "invalid offset in string table");
314
315   return file_ + stringTable.sh_offset + offset;
316 }
317
318 const char* ElfFile::getSectionName(const ElfShdr& section) const {
319   if (elfHeader().e_shstrndx == SHN_UNDEF) {
320     return nullptr; // no section name string table
321   }
322
323   const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
324   return getString(sectionNames, section.sh_name);
325 }
326
327 const ElfShdr* ElfFile::getSectionByName(const char* name) const {
328   if (elfHeader().e_shstrndx == SHN_UNDEF) {
329     return nullptr; // no section name string table
330   }
331
332   // Find offset in the section name string table of the requested name
333   const ElfShdr& sectionNames = *getSectionByIndex(elfHeader().e_shstrndx);
334   const char* foundName = iterateStrings(
335       sectionNames, [&](const char* s) { return !strcmp(name, s); });
336   if (foundName == nullptr) {
337     return nullptr;
338   }
339
340   size_t offset = foundName - (file_ + sectionNames.sh_offset);
341
342   // Find section with the appropriate sh_name offset
343   const ElfShdr* foundSection = iterateSections([&](const ElfShdr& sh) {
344     if (sh.sh_name == offset) {
345       return true;
346     }
347     return false;
348   });
349   return foundSection;
350 }
351
352 ElfFile::Symbol ElfFile::getDefinitionByAddress(uintptr_t address) const {
353   Symbol foundSymbol{nullptr, nullptr};
354
355   auto findSection = [&](const ElfShdr& section) {
356     auto findSymbols = [&](const ElfSym& sym) {
357       if (sym.st_shndx == SHN_UNDEF) {
358         return false; // not a definition
359       }
360       if (address >= sym.st_value && address < sym.st_value + sym.st_size) {
361         foundSymbol.first = &section;
362         foundSymbol.second = &sym;
363         return true;
364       }
365
366       return false;
367     };
368
369     return iterateSymbolsWithType(section, STT_OBJECT, findSymbols) ||
370         iterateSymbolsWithType(section, STT_FUNC, findSymbols);
371   };
372
373   // Try the .dynsym section first if it exists, it's smaller.
374   (iterateSectionsWithType(SHT_DYNSYM, findSection) ||
375    iterateSectionsWithType(SHT_SYMTAB, findSection));
376
377   return foundSymbol;
378 }
379
380 ElfFile::Symbol ElfFile::getSymbolByName(const char* name) const {
381   Symbol foundSymbol{nullptr, nullptr};
382
383   auto findSection = [&](const ElfShdr& section) -> bool {
384     // This section has no string table associated w/ its symbols; hence we
385     // can't get names for them
386     if (section.sh_link == SHN_UNDEF) {
387       return false;
388     }
389
390     auto findSymbols = [&](const ElfSym& sym) -> bool {
391       if (sym.st_shndx == SHN_UNDEF) {
392         return false; // not a definition
393       }
394       if (sym.st_name == 0) {
395         return false; // no name for this symbol
396       }
397       const char* sym_name =
398           getString(*getSectionByIndex(section.sh_link), sym.st_name);
399       if (strcmp(sym_name, name) == 0) {
400         foundSymbol.first = &section;
401         foundSymbol.second = &sym;
402         return true;
403       }
404
405       return false;
406     };
407
408     return iterateSymbolsWithType(section, STT_OBJECT, findSymbols) ||
409         iterateSymbolsWithType(section, STT_FUNC, findSymbols);
410   };
411
412   // Try the .dynsym section first if it exists, it's smaller.
413   iterateSectionsWithType(SHT_DYNSYM, findSection) ||
414       iterateSectionsWithType(SHT_SYMTAB, findSection);
415
416   return foundSymbol;
417 }
418
419 const ElfShdr* ElfFile::getSectionContainingAddress(ElfAddr addr) const {
420   return iterateSections([&](const ElfShdr& sh) -> bool {
421     return (addr >= sh.sh_addr) && (addr < (sh.sh_addr + sh.sh_size));
422   });
423 }
424
425 const char* ElfFile::getSymbolName(Symbol symbol) const {
426   if (!symbol.first || !symbol.second) {
427     return nullptr;
428   }
429
430   if (symbol.second->st_name == 0) {
431     return nullptr; // symbol has no name
432   }
433
434   if (symbol.first->sh_link == SHN_UNDEF) {
435     return nullptr; // symbol table has no strings
436   }
437
438   return getString(
439       *getSectionByIndex(symbol.first->sh_link), symbol.second->st_name);
440 }
441
442 } // namespace symbolizer
443 } // namespace folly