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