Harden failure signal handler in the face of memory corruptions
[folly.git] / folly / experimental / symbolizer / Symbolizer.cpp
1 /*
2  * Copyright 2014 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
17 #include "folly/experimental/symbolizer/Symbolizer.h"
18
19 #include <limits.h>
20 #include <cstdio>
21 #include <iostream>
22 #include <map>
23
24 #ifdef __GNUC__
25 #include <ext/stdio_filebuf.h>
26 #include <ext/stdio_sync_filebuf.h>
27 #endif
28
29 #include "folly/Conv.h"
30 #include "folly/FileUtil.h"
31 #include "folly/ScopeGuard.h"
32 #include "folly/String.h"
33
34 #include "folly/experimental/symbolizer/Elf.h"
35 #include "folly/experimental/symbolizer/Dwarf.h"
36 #include "folly/experimental/symbolizer/LineReader.h"
37
38
39 namespace folly {
40 namespace symbolizer {
41
42 namespace {
43
44 /**
45  * Read a hex value.
46  */
47 uintptr_t readHex(StringPiece& sp) {
48   uintptr_t val = 0;
49   const char* p = sp.begin();
50   for (; p != sp.end(); ++p) {
51     unsigned int v;
52     if (*p >= '0' && *p <= '9') {
53       v = (*p - '0');
54     } else if (*p >= 'a' && *p <= 'f') {
55       v = (*p - 'a') + 10;
56     } else if (*p >= 'A' && *p <= 'F') {
57       v = (*p - 'A') + 10;
58     } else {
59       break;
60     }
61     val = (val << 4) + v;
62   }
63   sp.assign(p, sp.end());
64   return val;
65 }
66
67 /**
68  * Skip over non-space characters.
69  */
70 void skipNS(StringPiece& sp) {
71   const char* p = sp.begin();
72   for (; p != sp.end() && (*p != ' ' && *p != '\t'); ++p) { }
73   sp.assign(p, sp.end());
74 }
75
76 /**
77  * Skip over space and tab characters.
78  */
79 void skipWS(StringPiece& sp) {
80   const char* p = sp.begin();
81   for (; p != sp.end() && (*p == ' ' || *p == '\t'); ++p) { }
82   sp.assign(p, sp.end());
83 }
84
85 /**
86  * Parse a line from /proc/self/maps
87  */
88 bool parseProcMapsLine(StringPiece line,
89                        uintptr_t& from, uintptr_t& to,
90                        StringPiece& fileName) {
91   // from     to       perm offset   dev   inode             path
92   // 00400000-00405000 r-xp 00000000 08:03 35291182          /bin/cat
93   if (line.empty()) {
94     return false;
95   }
96
97   // Remove trailing newline, if any
98   if (line.back() == '\n') {
99     line.pop_back();
100   }
101
102   // from
103   from = readHex(line);
104   if (line.empty() || line.front() != '-') {
105     return false;
106   }
107   line.pop_front();
108
109   // to
110   to = readHex(line);
111   if (line.empty() || line.front() != ' ') {
112     return false;
113   }
114   line.pop_front();
115
116   // perms
117   skipNS(line);
118   if (line.empty() || line.front() != ' ') {
119     return false;
120   }
121   line.pop_front();
122
123   uintptr_t fileOffset = readHex(line);
124   if (line.empty() || line.front() != ' ') {
125     return false;
126   }
127   line.pop_front();
128   if (fileOffset != 0) {
129     return false;  // main mapping starts at 0
130   }
131
132   // dev
133   skipNS(line);
134   if (line.empty() || line.front() != ' ') {
135     return false;
136   }
137   line.pop_front();
138
139   // inode
140   skipNS(line);
141   if (line.empty() || line.front() != ' ') {
142     return false;
143   }
144
145   skipWS(line);
146   if (line.empty()) {
147     fileName.clear();
148     return true;
149   }
150
151   fileName = line;
152   return true;
153 }
154
155 ElfCache* defaultElfCache() {
156   static constexpr size_t defaultCapacity = 500;
157   static ElfCache cache(defaultCapacity);
158   return &cache;
159 }
160
161 }  // namespace
162
163 Symbolizer::Symbolizer(ElfCacheBase* cache)
164   : cache_(cache ?: defaultElfCache()) {
165 }
166
167 void Symbolizer::symbolize(const uintptr_t* addresses,
168                            SymbolizedFrame* frames,
169                            size_t addressCount) {
170   size_t remaining = 0;
171   for (size_t i = 0; i < addressCount; ++i) {
172     auto& frame = frames[i];
173     if (!frame.found) {
174       ++remaining;
175       frame.name.clear();
176       frame.location = Dwarf::LocationInfo();
177     }
178   }
179
180   if (remaining == 0) {  // we're done
181     return;
182   }
183
184   int fd = openNoInt("/proc/self/maps", O_RDONLY);
185   if (fd == -1) {
186     return;
187   }
188
189   char buf[PATH_MAX + 100];  // Long enough for any line
190   LineReader reader(fd, buf, sizeof(buf));
191
192   char fileNameBuf[PATH_MAX];
193
194   while (remaining != 0) {
195     StringPiece line;
196     if (reader.readLine(line) != LineReader::kReading) {
197       break;
198     }
199
200     // Parse line
201     uintptr_t from;
202     uintptr_t to;
203     StringPiece fileName;
204     if (!parseProcMapsLine(line, from, to, fileName)) {
205       continue;
206     }
207
208     bool first = true;
209     std::shared_ptr<ElfFile> elfFile;
210
211     // See if any addresses are here
212     for (size_t i = 0; i < addressCount; ++i) {
213       auto& frame = frames[i];
214       if (frame.found) {
215         continue;
216       }
217
218       uintptr_t address = addresses[i];
219
220       if (from > address || address >= to) {
221         continue;
222       }
223
224       // Found
225       frame.found = true;
226       --remaining;
227
228       // Open the file on first use
229       if (first) {
230         first = false;
231         elfFile = cache_->getFile(fileName);
232       }
233
234       if (!elfFile) {
235         continue;
236       }
237
238       // Undo relocation
239       uintptr_t fileAddress = address - from + elfFile->getBaseAddress();
240       auto sym = elfFile->getDefinitionByAddress(fileAddress);
241       if (!sym.first) {
242         continue;
243       }
244       auto name = elfFile->getSymbolName(sym);
245       if (name) {
246         frame.name = name;
247       }
248
249       Dwarf(elfFile.get()).findAddress(fileAddress, frame.location);
250     }
251   }
252
253   closeNoInt(fd);
254 }
255
256 namespace {
257 const char kHexChars[] = "0123456789abcdef";
258 const SymbolizePrinter::Color kAddressColor = SymbolizePrinter::Color::BLUE;
259 const SymbolizePrinter::Color kFunctionColor = SymbolizePrinter::Color::PURPLE;
260 const SymbolizePrinter::Color kFileColor = SymbolizePrinter::Color::DEFAULT;
261 }  // namespace
262
263 constexpr char AddressFormatter::bufTemplate[];
264
265 AddressFormatter::AddressFormatter() {
266   memcpy(buf_, bufTemplate, sizeof(buf_));
267 }
268
269 folly::StringPiece AddressFormatter::format(uintptr_t address) {
270   // Can't use sprintf, not async-signal-safe
271   static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
272   char* end = buf_ + sizeof(buf_) - 1 - (16 - 2 * sizeof(uintptr_t));
273   char* p = end;
274   *p-- = '\0';
275   while (address != 0) {
276     *p-- = kHexChars[address & 0xf];
277     address >>= 4;
278   }
279
280   return folly::StringPiece(buf_, end);
281 }
282
283 void SymbolizePrinter::print(uintptr_t address, const SymbolizedFrame& frame) {
284   if (options_ & TERSE) {
285     printTerse(address, frame);
286     return;
287   }
288
289   SCOPE_EXIT { color(Color::DEFAULT); };
290
291   color(kAddressColor);
292
293   AddressFormatter formatter;
294   doPrint(formatter.format(address));
295
296   const char padBuf[] = "                       ";
297   folly::StringPiece pad(padBuf,
298                          sizeof(padBuf) - 1 - (16 - 2 * sizeof(uintptr_t)));
299
300   color(kFunctionColor);
301   char mangledBuf[1024];
302   if (!frame.found) {
303     doPrint(" (not found)");
304     return;
305   }
306
307   if (frame.name.empty()) {
308     doPrint(" (unknown)");
309   } else if (frame.name.size() >= sizeof(mangledBuf)) {
310     doPrint(" ");
311     doPrint(frame.name);
312   } else {
313     memcpy(mangledBuf, frame.name.data(), frame.name.size());
314     mangledBuf[frame.name.size()] = '\0';
315
316     char demangledBuf[1024];
317     demangle(mangledBuf, demangledBuf, sizeof(demangledBuf));
318     doPrint(" ");
319     doPrint(demangledBuf);
320   }
321
322   if (!(options_ & NO_FILE_AND_LINE)) {
323     color(kFileColor);
324     char fileBuf[PATH_MAX];
325     fileBuf[0] = '\0';
326     if (frame.location.hasFileAndLine) {
327       frame.location.file.toBuffer(fileBuf, sizeof(fileBuf));
328       doPrint("\n");
329       doPrint(pad);
330       doPrint(fileBuf);
331
332       char buf[22];
333       uint32_t n = uint64ToBufferUnsafe(frame.location.line, buf);
334       doPrint(":");
335       doPrint(StringPiece(buf, n));
336     }
337
338     if (frame.location.hasMainFile) {
339       char mainFileBuf[PATH_MAX];
340       mainFileBuf[0] = '\0';
341       frame.location.mainFile.toBuffer(mainFileBuf, sizeof(mainFileBuf));
342       if (!frame.location.hasFileAndLine || strcmp(fileBuf, mainFileBuf)) {
343         doPrint("\n");
344         doPrint(pad);
345         doPrint("-> ");
346         doPrint(mainFileBuf);
347       }
348     }
349   }
350 }
351
352 namespace {
353
354 const std::map<SymbolizePrinter::Color, std::string> kColorMap = {
355   { SymbolizePrinter::Color::DEFAULT,  "\x1B[0m" },
356   { SymbolizePrinter::Color::RED,  "\x1B[31m" },
357   { SymbolizePrinter::Color::GREEN,  "\x1B[32m" },
358   { SymbolizePrinter::Color::YELLOW,  "\x1B[33m" },
359   { SymbolizePrinter::Color::BLUE,  "\x1B[34m" },
360   { SymbolizePrinter::Color::CYAN,  "\x1B[36m" },
361   { SymbolizePrinter::Color::WHITE,  "\x1B[37m" },
362   { SymbolizePrinter::Color::PURPLE,  "\x1B[35m" },
363 };
364
365 }
366
367 void SymbolizePrinter::color(SymbolizePrinter::Color color) {
368   if ((options_ & COLOR) == 0 &&
369       ((options_ & COLOR_IF_TTY) == 0 || !isTty_)) {
370     return;
371   }
372   auto it = kColorMap.find(color);
373   if (it == kColorMap.end()) {
374     return;
375   }
376   doPrint(it->second);
377 }
378
379 void SymbolizePrinter::println(uintptr_t address,
380                                const SymbolizedFrame& frame) {
381   print(address, frame);
382   doPrint("\n");
383 }
384
385 void SymbolizePrinter::printTerse(uintptr_t address,
386                                   const SymbolizedFrame& frame) {
387   if (frame.found) {
388     char mangledBuf[1024];
389     memcpy(mangledBuf, frame.name.data(), frame.name.size());
390     mangledBuf[frame.name.size()] = '\0';
391
392     char demangledBuf[1024] = {0};
393     demangle(mangledBuf, demangledBuf, sizeof(demangledBuf));
394     doPrint(strlen(demangledBuf) == 0 ? "(unknown)" : demangledBuf);
395   } else {
396     // Can't use sprintf, not async-signal-safe
397     static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
398     char buf[] = "0x0000000000000000";
399     char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));
400     char* p = end;
401     *p-- = '\0';
402     while (address != 0) {
403       *p-- = kHexChars[address & 0xf];
404       address >>= 4;
405     }
406     doPrint(StringPiece(buf, end));
407   }
408 }
409
410 void SymbolizePrinter::println(const uintptr_t* addresses,
411                                const SymbolizedFrame* frames,
412                                size_t frameCount) {
413   for (size_t i = 0; i < frameCount; ++i) {
414     println(addresses[i], frames[i]);
415   }
416 }
417
418 namespace {
419
420 int getFD(const std::ios& stream) {
421 #ifdef __GNUC__
422   std::streambuf* buf = stream.rdbuf();
423   using namespace __gnu_cxx;
424
425   {
426     auto sbuf = dynamic_cast<stdio_sync_filebuf<char>*>(buf);
427     if (sbuf) {
428       return fileno(sbuf->file());
429     }
430   }
431   {
432     auto sbuf = dynamic_cast<stdio_filebuf<char>*>(buf);
433     if (sbuf) {
434       return sbuf->fd();
435     }
436   }
437 #endif  // __GNUC__
438   return -1;
439 }
440
441 bool isTty(int options, int fd) {
442   return ((options & SymbolizePrinter::TERSE) == 0 &&
443           (options & SymbolizePrinter::COLOR_IF_TTY) != 0 &&
444           fd >= 0 && ::isatty(fd));
445 }
446
447 }  // anonymous namespace
448
449 OStreamSymbolizePrinter::OStreamSymbolizePrinter(std::ostream& out, int options)
450   : SymbolizePrinter(options, isTty(options, getFD(out))),
451     out_(out) {
452 }
453
454 void OStreamSymbolizePrinter::doPrint(StringPiece sp) {
455   out_ << sp;
456 }
457
458 FDSymbolizePrinter::FDSymbolizePrinter(int fd, int options)
459   : SymbolizePrinter(options, isTty(options, fd)),
460     fd_(fd) {
461 }
462
463 void FDSymbolizePrinter::doPrint(StringPiece sp) {
464   writeFull(fd_, sp.data(), sp.size());
465 }
466
467 FILESymbolizePrinter::FILESymbolizePrinter(FILE* file, int options)
468   : SymbolizePrinter(options, isTty(options, fileno(file))),
469     file_(file) {
470 }
471
472 void FILESymbolizePrinter::doPrint(StringPiece sp) {
473   fwrite(sp.data(), 1, sp.size(), file_);
474 }
475
476 void StringSymbolizePrinter::doPrint(StringPiece sp) {
477   buf_.append(sp.data(), sp.size());
478 }
479
480 }  // namespace symbolizer
481 }  // namespace folly