2 * Copyright 2014 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "folly/experimental/symbolizer/Symbolizer.h"
25 #include <ext/stdio_filebuf.h>
26 #include <ext/stdio_sync_filebuf.h>
29 #include "folly/Conv.h"
30 #include "folly/FileUtil.h"
31 #include "folly/ScopeGuard.h"
32 #include "folly/String.h"
34 #include "folly/experimental/symbolizer/Elf.h"
35 #include "folly/experimental/symbolizer/Dwarf.h"
36 #include "folly/experimental/symbolizer/LineReader.h"
40 namespace symbolizer {
47 uintptr_t readHex(StringPiece& sp) {
49 const char* p = sp.begin();
50 for (; p != sp.end(); ++p) {
52 if (*p >= '0' && *p <= '9') {
54 } else if (*p >= 'a' && *p <= 'f') {
56 } else if (*p >= 'A' && *p <= 'F') {
63 sp.assign(p, sp.end());
68 * Skip over non-space characters.
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());
77 * Skip over space and tab characters.
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());
86 * Parse a line from /proc/self/maps
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
97 // Remove trailing newline, if any
98 if (line.back() == '\n') {
103 from = readHex(line);
104 if (line.empty() || line.front() != '-') {
111 if (line.empty() || line.front() != ' ') {
118 if (line.empty() || line.front() != ' ') {
123 uintptr_t fileOffset = readHex(line);
124 if (line.empty() || line.front() != ' ') {
128 if (fileOffset != 0) {
129 return false; // main mapping starts at 0
134 if (line.empty() || line.front() != ' ') {
141 if (line.empty() || line.front() != ' ') {
155 ElfCache* defaultElfCache() {
156 static constexpr size_t defaultCapacity = 500;
157 static ElfCache cache(defaultCapacity);
163 void SymbolizedFrame::set(const std::shared_ptr<ElfFile>& file,
168 address += file->getBaseAddress();
169 auto sym = file->getDefinitionByAddress(address);
175 auto name = file->getSymbolName(sym);
180 Dwarf(file.get()).findAddress(address, location);
184 Symbolizer::Symbolizer(ElfCacheBase* cache)
185 : cache_(cache ?: defaultElfCache()) {
188 void Symbolizer::symbolize(const uintptr_t* addresses,
189 SymbolizedFrame* frames,
190 size_t addressCount) {
191 size_t remaining = 0;
192 for (size_t i = 0; i < addressCount; ++i) {
193 auto& frame = frames[i];
200 if (remaining == 0) { // we're done
204 int fd = openNoInt("/proc/self/maps", O_RDONLY);
209 char buf[PATH_MAX + 100]; // Long enough for any line
210 LineReader reader(fd, buf, sizeof(buf));
212 while (remaining != 0) {
214 if (reader.readLine(line) != LineReader::kReading) {
221 StringPiece fileName;
222 if (!parseProcMapsLine(line, from, to, fileName)) {
227 std::shared_ptr<ElfFile> elfFile;
229 // See if any addresses are here
230 for (size_t i = 0; i < addressCount; ++i) {
231 auto& frame = frames[i];
236 uintptr_t address = addresses[i];
238 if (from > address || address >= to) {
246 // Open the file on first use
249 elfFile = cache_->getFile(fileName);
257 frame.set(elfFile, address - from);
265 const char kHexChars[] = "0123456789abcdef";
266 const SymbolizePrinter::Color kAddressColor = SymbolizePrinter::Color::BLUE;
267 const SymbolizePrinter::Color kFunctionColor = SymbolizePrinter::Color::PURPLE;
268 const SymbolizePrinter::Color kFileColor = SymbolizePrinter::Color::DEFAULT;
271 constexpr char AddressFormatter::bufTemplate[];
273 AddressFormatter::AddressFormatter() {
274 memcpy(buf_, bufTemplate, sizeof(buf_));
277 folly::StringPiece AddressFormatter::format(uintptr_t address) {
278 // Can't use sprintf, not async-signal-safe
279 static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
280 char* end = buf_ + sizeof(buf_) - 1 - (16 - 2 * sizeof(uintptr_t));
283 while (address != 0) {
284 *p-- = kHexChars[address & 0xf];
288 return folly::StringPiece(buf_, end);
291 void SymbolizePrinter::print(uintptr_t address, const SymbolizedFrame& frame) {
292 if (options_ & TERSE) {
293 printTerse(address, frame);
297 SCOPE_EXIT { color(Color::DEFAULT); };
299 color(kAddressColor);
301 AddressFormatter formatter;
302 doPrint(formatter.format(address));
304 const char padBuf[] = " ";
305 folly::StringPiece pad(padBuf,
306 sizeof(padBuf) - 1 - (16 - 2 * sizeof(uintptr_t)));
308 color(kFunctionColor);
309 char mangledBuf[1024];
311 doPrint(" (not found)");
315 if (frame.name.empty()) {
316 doPrint(" (unknown)");
317 } else if (frame.name.size() >= sizeof(mangledBuf)) {
321 memcpy(mangledBuf, frame.name.data(), frame.name.size());
322 mangledBuf[frame.name.size()] = '\0';
324 char demangledBuf[1024];
325 demangle(mangledBuf, demangledBuf, sizeof(demangledBuf));
327 doPrint(demangledBuf);
330 if (!(options_ & NO_FILE_AND_LINE)) {
332 char fileBuf[PATH_MAX];
334 if (frame.location.hasFileAndLine) {
335 frame.location.file.toBuffer(fileBuf, sizeof(fileBuf));
341 uint32_t n = uint64ToBufferUnsafe(frame.location.line, buf);
343 doPrint(StringPiece(buf, n));
346 if (frame.location.hasMainFile) {
347 char mainFileBuf[PATH_MAX];
348 mainFileBuf[0] = '\0';
349 frame.location.mainFile.toBuffer(mainFileBuf, sizeof(mainFileBuf));
350 if (!frame.location.hasFileAndLine || strcmp(fileBuf, mainFileBuf)) {
354 doPrint(mainFileBuf);
362 const std::map<SymbolizePrinter::Color, std::string> kColorMap = {
363 { SymbolizePrinter::Color::DEFAULT, "\x1B[0m" },
364 { SymbolizePrinter::Color::RED, "\x1B[31m" },
365 { SymbolizePrinter::Color::GREEN, "\x1B[32m" },
366 { SymbolizePrinter::Color::YELLOW, "\x1B[33m" },
367 { SymbolizePrinter::Color::BLUE, "\x1B[34m" },
368 { SymbolizePrinter::Color::CYAN, "\x1B[36m" },
369 { SymbolizePrinter::Color::WHITE, "\x1B[37m" },
370 { SymbolizePrinter::Color::PURPLE, "\x1B[35m" },
375 void SymbolizePrinter::color(SymbolizePrinter::Color color) {
376 if ((options_ & COLOR) == 0 &&
377 ((options_ & COLOR_IF_TTY) == 0 || !isTty_)) {
380 auto it = kColorMap.find(color);
381 if (it == kColorMap.end()) {
387 void SymbolizePrinter::println(uintptr_t address,
388 const SymbolizedFrame& frame) {
389 print(address, frame);
393 void SymbolizePrinter::printTerse(uintptr_t address,
394 const SymbolizedFrame& frame) {
396 char mangledBuf[1024];
397 memcpy(mangledBuf, frame.name.data(), frame.name.size());
398 mangledBuf[frame.name.size()] = '\0';
400 char demangledBuf[1024] = {0};
401 demangle(mangledBuf, demangledBuf, sizeof(demangledBuf));
402 doPrint(strlen(demangledBuf) == 0 ? "(unknown)" : demangledBuf);
404 // Can't use sprintf, not async-signal-safe
405 static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
406 char buf[] = "0x0000000000000000";
407 char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));
410 while (address != 0) {
411 *p-- = kHexChars[address & 0xf];
414 doPrint(StringPiece(buf, end));
418 void SymbolizePrinter::println(const uintptr_t* addresses,
419 const SymbolizedFrame* frames,
421 for (size_t i = 0; i < frameCount; ++i) {
422 println(addresses[i], frames[i]);
428 int getFD(const std::ios& stream) {
430 std::streambuf* buf = stream.rdbuf();
431 using namespace __gnu_cxx;
434 auto sbuf = dynamic_cast<stdio_sync_filebuf<char>*>(buf);
436 return fileno(sbuf->file());
440 auto sbuf = dynamic_cast<stdio_filebuf<char>*>(buf);
449 bool isTty(int options, int fd) {
450 return ((options & SymbolizePrinter::TERSE) == 0 &&
451 (options & SymbolizePrinter::COLOR_IF_TTY) != 0 &&
452 fd >= 0 && ::isatty(fd));
455 } // anonymous namespace
457 OStreamSymbolizePrinter::OStreamSymbolizePrinter(std::ostream& out, int options)
458 : SymbolizePrinter(options, isTty(options, getFD(out))),
462 void OStreamSymbolizePrinter::doPrint(StringPiece sp) {
466 FDSymbolizePrinter::FDSymbolizePrinter(int fd, int options)
467 : SymbolizePrinter(options, isTty(options, fd)),
471 void FDSymbolizePrinter::doPrint(StringPiece sp) {
472 writeFull(fd_, sp.data(), sp.size());
475 FILESymbolizePrinter::FILESymbolizePrinter(FILE* file, int options)
476 : SymbolizePrinter(options, isTty(options, fileno(file))),
480 void FILESymbolizePrinter::doPrint(StringPiece sp) {
481 fwrite(sp.data(), 1, sp.size(), file_);
484 void StringSymbolizePrinter::doPrint(StringPiece sp) {
485 buf_.append(sp.data(), sp.size());
488 } // namespace symbolizer