folly: symbolizer: small terse write fix + colorize signal handler output if printing...
[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 }  // namespace
156
157 void Symbolizer::symbolize(const uintptr_t* addresses,
158                            SymbolizedFrame* frames,
159                            size_t addressCount) {
160   size_t remaining = 0;
161   for (size_t i = 0; i < addressCount; ++i) {
162     auto& frame = frames[i];
163     if (!frame.found) {
164       ++remaining;
165       frame.name.clear();
166       frame.location = Dwarf::LocationInfo();
167     }
168   }
169
170   if (remaining == 0) {  // we're done
171     return;
172   }
173
174   int fd = openNoInt("/proc/self/maps", O_RDONLY);
175   if (fd == -1) {
176     return;
177   }
178
179   char buf[PATH_MAX + 100];  // Long enough for any line
180   LineReader reader(fd, buf, sizeof(buf));
181
182   char fileNameBuf[PATH_MAX];
183
184   while (remaining != 0) {
185     StringPiece line;
186     if (reader.readLine(line) != LineReader::kReading) {
187       break;
188     }
189
190     // Parse line
191     uintptr_t from;
192     uintptr_t to;
193     StringPiece fileName;
194     if (!parseProcMapsLine(line, from, to, fileName)) {
195       continue;
196     }
197
198     bool first = true;
199     ElfFile* elfFile = nullptr;
200
201     // See if any addresses are here
202     for (size_t i = 0; i < addressCount; ++i) {
203       auto& frame = frames[i];
204       if (frame.found) {
205         continue;
206       }
207
208       uintptr_t address = addresses[i];
209
210       if (from > address || address >= to) {
211         continue;
212       }
213
214       // Found
215       frame.found = true;
216       --remaining;
217
218       // Open the file on first use
219       if (first) {
220         first = false;
221         if (fileCount_ < kMaxFiles &&
222             !fileName.empty() &&
223             fileName.size() < sizeof(fileNameBuf)) {
224           memcpy(fileNameBuf, fileName.data(), fileName.size());
225           fileNameBuf[fileName.size()] = '\0';
226           auto& f = files_[fileCount_++];
227           if (f.openNoThrow(fileNameBuf) != -1) {
228             elfFile = &f;
229           }
230         }
231       }
232
233       if (!elfFile) {
234         continue;
235       }
236
237       // Undo relocation
238       uintptr_t fileAddress = address - from + elfFile->getBaseAddress();
239       auto sym = elfFile->getDefinitionByAddress(fileAddress);
240       if (!sym.first) {
241         continue;
242       }
243       auto name = elfFile->getSymbolName(sym);
244       if (name) {
245         frame.name = name;
246       }
247
248       Dwarf(elfFile).findAddress(fileAddress, frame.location);
249     }
250   }
251
252   closeNoInt(fd);
253 }
254
255 namespace {
256 const char kHexChars[] = "0123456789abcdef";
257 const SymbolizePrinter::Color kAddressColor = SymbolizePrinter::Color::BLUE;
258 const SymbolizePrinter::Color kFunctionColor = SymbolizePrinter::Color::PURPLE;
259 const SymbolizePrinter::Color kFileColor = SymbolizePrinter::Color::DEFAULT;
260 }  // namespace
261
262 void SymbolizePrinter::print(uintptr_t address, const SymbolizedFrame& frame) {
263   if (options_ & TERSE) {
264     printTerse(address, frame);
265     return;
266   }
267
268   SCOPE_EXIT { color(Color::DEFAULT); };
269
270   color(kAddressColor);
271   // Can't use sprintf, not async-signal-safe
272   static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
273   char buf[] = "    @ 0000000000000000";
274   char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));
275   const char padBuf[] = "                       ";
276   folly::StringPiece pad(padBuf,
277                          sizeof(padBuf) - 1 - (16 - 2 * sizeof(uintptr_t)));
278   char* p = end;
279   *p-- = '\0';
280   while (address != 0) {
281     *p-- = kHexChars[address & 0xf];
282     address >>= 4;
283   }
284   doPrint(folly::StringPiece(buf, end));
285
286   color(kFunctionColor);
287   char mangledBuf[1024];
288   if (!frame.found) {
289     doPrint(" (not found)");
290     return;
291   }
292
293   if (frame.name.empty()) {
294     doPrint(" (unknown)");
295   } else if (frame.name.size() >= sizeof(mangledBuf)) {
296     doPrint(" ");
297     doPrint(frame.name);
298   } else {
299     memcpy(mangledBuf, frame.name.data(), frame.name.size());
300     mangledBuf[frame.name.size()] = '\0';
301
302     char demangledBuf[1024];
303     demangle(mangledBuf, demangledBuf, sizeof(demangledBuf));
304     doPrint(" ");
305     doPrint(demangledBuf);
306   }
307
308   if (!(options_ & NO_FILE_AND_LINE)) {
309     color(kFileColor);
310     char fileBuf[PATH_MAX];
311     fileBuf[0] = '\0';
312     if (frame.location.hasFileAndLine) {
313       frame.location.file.toBuffer(fileBuf, sizeof(fileBuf));
314       doPrint("\n");
315       doPrint(pad);
316       doPrint(fileBuf);
317
318       char buf[22];
319       uint32_t n = uint64ToBufferUnsafe(frame.location.line, buf);
320       doPrint(":");
321       doPrint(StringPiece(buf, n));
322     }
323
324     if (frame.location.hasMainFile) {
325       char mainFileBuf[PATH_MAX];
326       mainFileBuf[0] = '\0';
327       frame.location.mainFile.toBuffer(mainFileBuf, sizeof(mainFileBuf));
328       if (!frame.location.hasFileAndLine || strcmp(fileBuf, mainFileBuf)) {
329         doPrint("\n");
330         doPrint(pad);
331         doPrint("-> ");
332         doPrint(mainFileBuf);
333       }
334     }
335   }
336 }
337
338 namespace {
339
340 const std::map<SymbolizePrinter::Color, std::string> kColorMap = {
341   { SymbolizePrinter::Color::DEFAULT,  "\x1B[0m" },
342   { SymbolizePrinter::Color::RED,  "\x1B[31m" },
343   { SymbolizePrinter::Color::GREEN,  "\x1B[32m" },
344   { SymbolizePrinter::Color::YELLOW,  "\x1B[33m" },
345   { SymbolizePrinter::Color::BLUE,  "\x1B[34m" },
346   { SymbolizePrinter::Color::CYAN,  "\x1B[36m" },
347   { SymbolizePrinter::Color::WHITE,  "\x1B[37m" },
348   { SymbolizePrinter::Color::PURPLE,  "\x1B[35m" },
349 };
350
351 }
352
353 void SymbolizePrinter::color(SymbolizePrinter::Color color) {
354   if ((options_ & COLOR) == 0 &&
355       ((options_ & COLOR_IF_TTY) == 0 || !isTty_)) {
356     return;
357   }
358   auto it = kColorMap.find(color);
359   if (it == kColorMap.end()) {
360     return;
361   }
362   doPrint(it->second);
363 }
364
365 void SymbolizePrinter::println(uintptr_t address,
366                                const SymbolizedFrame& frame) {
367   print(address, frame);
368   doPrint("\n");
369 }
370
371 void SymbolizePrinter::printTerse(uintptr_t address,
372                                   const SymbolizedFrame& frame) {
373   if (frame.found) {
374     char mangledBuf[1024];
375     memcpy(mangledBuf, frame.name.data(), frame.name.size());
376     mangledBuf[frame.name.size()] = '\0';
377
378     char demangledBuf[1024] = {0};
379     demangle(mangledBuf, demangledBuf, sizeof(demangledBuf));
380     doPrint(strlen(demangledBuf) == 0 ? "(unknown)" : demangledBuf);
381   } else {
382     // Can't use sprintf, not async-signal-safe
383     static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
384     char buf[] = "0x0000000000000000";
385     char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));
386     char* p = end;
387     *p-- = '\0';
388     while (address != 0) {
389       *p-- = kHexChars[address & 0xf];
390       address >>= 4;
391     }
392     doPrint(StringPiece(buf, end));
393   }
394 }
395
396 void SymbolizePrinter::println(const uintptr_t* addresses,
397                                const SymbolizedFrame* frames,
398                                size_t frameCount) {
399   for (size_t i = 0; i < frameCount; ++i) {
400     println(addresses[i], frames[i]);
401   }
402 }
403
404 namespace {
405
406 int getFD(const std::ios& stream) {
407 #ifdef __GNUC__
408   std::streambuf* buf = stream.rdbuf();
409   using namespace __gnu_cxx;
410
411   {
412     auto sbuf = dynamic_cast<stdio_sync_filebuf<char>*>(buf);
413     if (sbuf) {
414       return fileno(sbuf->file());
415     }
416   }
417   {
418     auto sbuf = dynamic_cast<stdio_filebuf<char>*>(buf);
419     if (sbuf) {
420       return sbuf->fd();
421     }
422   }
423 #endif  // __GNUC__
424   return -1;
425 }
426
427 bool isTty(int options, int fd) {
428   return ((options & SymbolizePrinter::TERSE) == 0 &&
429           (options & SymbolizePrinter::COLOR_IF_TTY) != 0 &&
430           fd >= 0 && ::isatty(fd));
431 }
432
433 }  // anonymous namespace
434
435 OStreamSymbolizePrinter::OStreamSymbolizePrinter(std::ostream& out, int options)
436   : SymbolizePrinter(options, isTty(options, getFD(out))),
437     out_(out) {
438 }
439
440 void OStreamSymbolizePrinter::doPrint(StringPiece sp) {
441   out_ << sp;
442 }
443
444 FDSymbolizePrinter::FDSymbolizePrinter(int fd, int options)
445   : SymbolizePrinter(options, isTty(options, fd)),
446     fd_(fd) {
447 }
448
449 void FDSymbolizePrinter::doPrint(StringPiece sp) {
450   writeFull(fd_, sp.data(), sp.size());
451 }
452
453 FILESymbolizePrinter::FILESymbolizePrinter(FILE* file, int options)
454   : SymbolizePrinter(options, isTty(options, fileno(file))),
455     file_(file) {
456 }
457
458 void FILESymbolizePrinter::doPrint(StringPiece sp) {
459   fwrite(sp.data(), 1, sp.size(), file_);
460 }
461
462 void StringSymbolizePrinter::doPrint(StringPiece sp) {
463   buf_.append(sp.data(), sp.size());
464 }
465
466 }  // namespace symbolizer
467 }  // namespace folly