/*
- * Copyright 2013 Facebook, Inc.
+ * Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* limitations under the License.
*/
-// Must be first to ensure that UNW_LOCAL_ONLY is defined
-#define UNW_LOCAL_ONLY 1
-#include <libunwind.h>
+#include <folly/experimental/symbolizer/Symbolizer.h>
-#include "folly/experimental/symbolizer/Symbolizer.h"
+#include <link.h>
-#include <limits.h>
+#include <climits>
+#include <cstdio>
+#include <cstdlib>
+#include <iostream>
-#include "folly/Conv.h"
-#include "folly/FileUtil.h"
-#include "folly/String.h"
+#ifdef __GLIBCXX__
+#include <ext/stdio_filebuf.h>
+#include <ext/stdio_sync_filebuf.h>
+#endif
-#include "folly/experimental/symbolizer/Elf.h"
-#include "folly/experimental/symbolizer/Dwarf.h"
-#include "folly/experimental/symbolizer/LineReader.h"
+#include <folly/Conv.h>
+#include <folly/FileUtil.h>
+#include <folly/Memory.h>
+#include <folly/ScopeGuard.h>
+#include <folly/String.h>
+
+#include <folly/experimental/symbolizer/Dwarf.h>
+#include <folly/experimental/symbolizer/Elf.h>
+#include <folly/experimental/symbolizer/LineReader.h>
+#include <folly/portability/Unistd.h>
+
+/*
+ * This is declared in `link.h' on Linux platforms, but apparently not on the
+ * Mac version of the file. It's harmless to declare again, in any case.
+ *
+ * Note that declaring it with `extern "C"` results in linkage conflicts.
+ */
+extern struct r_debug _r_debug;
namespace folly {
namespace symbolizer {
namespace {
-/**
- * Read a hex value.
- */
-uintptr_t readHex(StringPiece& sp) {
- uintptr_t val = 0;
- const char* p = sp.begin();
- for (; p != sp.end(); ++p) {
- unsigned int v;
- if (*p >= '0' && *p <= '9') {
- v = (*p - '0');
- } else if (*p >= 'a' && *p <= 'f') {
- v = (*p - 'a') + 10;
- } else if (*p >= 'A' && *p <= 'F') {
- v = (*p - 'A') + 10;
- } else {
- break;
- }
- val = (val << 4) + v;
- }
- sp.assign(p, sp.end());
- return val;
+ElfCache* defaultElfCache() {
+ static constexpr size_t defaultCapacity = 500;
+ static auto cache = new ElfCache(defaultCapacity);
+ return cache;
}
-/**
- * Skip over non-space characters.
- */
-void skipNS(StringPiece& sp) {
- const char* p = sp.begin();
- for (; p != sp.end() && (*p != ' ' && *p != '\t'); ++p) { }
- sp.assign(p, sp.end());
-}
+} // namespace
-/**
- * Skip over space and tab characters.
- */
-void skipWS(StringPiece& sp) {
- const char* p = sp.begin();
- for (; p != sp.end() && (*p == ' ' || *p == '\t'); ++p) { }
- sp.assign(p, sp.end());
-}
+void SymbolizedFrame::set(
+ const std::shared_ptr<ElfFile>& file,
+ uintptr_t address,
+ Dwarf::LocationInfoMode mode) {
+ clear();
+ found = true;
-/**
- * Parse a line from /proc/self/maps
- */
-bool parseProcMapsLine(StringPiece line,
- uintptr_t& from, uintptr_t& to,
- StringPiece& fileName) {
- // from to perm offset dev inode path
- // 00400000-00405000 r-xp 00000000 08:03 35291182 /bin/cat
- if (line.empty()) {
- return false;
+ address += file->getBaseAddress();
+ auto sym = file->getDefinitionByAddress(address);
+ if (!sym.first) {
+ return;
}
- // Remove trailing newline, if any
- if (line.back() == '\n') {
- line.pop_back();
- }
+ file_ = file;
+ name = file->getSymbolName(sym);
- // from
- from = readHex(line);
- if (line.empty() || line.front() != '-') {
- return false;
- }
- line.pop_front();
+ Dwarf(file.get()).findAddress(address, location, mode);
+}
- // to
- to = readHex(line);
- if (line.empty() || line.front() != ' ') {
- return false;
- }
- line.pop_front();
+Symbolizer::Symbolizer(ElfCacheBase* cache, Dwarf::LocationInfoMode mode)
+ : cache_(cache ? cache : defaultElfCache()), mode_(mode) {}
- // perms
- skipNS(line);
- if (line.empty() || line.front() != ' ') {
- return false;
- }
- line.pop_front();
-
- uintptr_t fileOffset = readHex(line);
- if (line.empty() || line.front() != ' ') {
- return false;
- }
- line.pop_front();
- if (fileOffset != 0) {
- return false; // main mapping starts at 0
+void Symbolizer::symbolize(
+ const uintptr_t* addresses,
+ SymbolizedFrame* frames,
+ size_t addrCount) {
+ size_t remaining = 0;
+ for (size_t i = 0; i < addrCount; ++i) {
+ auto& frame = frames[i];
+ if (!frame.found) {
+ ++remaining;
+ frame.clear();
+ }
}
- // dev
- skipNS(line);
- if (line.empty() || line.front() != ' ') {
- return false;
+ if (remaining == 0) { // we're done
+ return;
}
- line.pop_front();
- // inode
- skipNS(line);
- if (line.empty() || line.front() != ' ') {
- return false;
+ if (_r_debug.r_version != 1) {
+ return;
}
- skipWS(line);
- if (line.empty()) {
- fileName.clear();
- return true;
+ char selfPath[PATH_MAX + 8];
+ ssize_t selfSize;
+ if ((selfSize = readlink("/proc/self/exe", selfPath, PATH_MAX + 1)) == -1) {
+ // Something has gone terribly wrong.
+ return;
}
+ selfPath[selfSize] = '\0';
+
+ for (auto lmap = _r_debug.r_map; lmap != nullptr && remaining != 0;
+ lmap = lmap->l_next) {
+ // The empty string is used in place of the filename for the link_map
+ // corresponding to the running executable. Additionally, the `l_addr' is
+ // 0 and the link_map appears to be first in the list---but none of this
+ // behavior appears to be documented, so checking for the empty string is
+ // as good as anything.
+ auto const objPath = lmap->l_name[0] != '\0' ? lmap->l_name : selfPath;
+
+ auto const elfFile = cache_->getFile(objPath);
+ if (!elfFile) {
+ continue;
+ }
- fileName = line;
- return true;
-}
-
-} // namespace
+ // Get the address at which the object is loaded. We have to use the ELF
+ // header for the running executable, since its `l_addr' is zero, but we
+ // should use `l_addr' for everything else---in particular, if the object
+ // is position-independent, getBaseAddress() (which is p_vaddr) will be 0.
+ auto const base =
+ lmap->l_addr != 0 ? lmap->l_addr : elfFile->getBaseAddress();
-ssize_t getStackTrace(FrameInfo* addresses,
- size_t maxAddresses,
- size_t skip) {
- unw_context_t uctx;
- int r = unw_getcontext(&uctx);
- if (r < 0) {
- return -1;
- }
-
- unw_cursor_t cursor;
- size_t idx = 0;
- bool first = true;
- for (;;) {
- if (first) {
- first = false;
- r = unw_init_local(&cursor, &uctx);
- } else {
- r = unw_step(&cursor);
- if (r == 0) {
- break;
+ for (size_t i = 0; i < addrCount && remaining != 0; ++i) {
+ auto& frame = frames[i];
+ if (frame.found) {
+ continue;
}
- }
- if (r < 0) {
- return -1;
- }
- if (skip != 0) {
- --skip;
- continue;
- }
+ auto const addr = addresses[i];
+ // Get the unrelocated, ELF-relative address.
+ auto const adjusted = addr - base;
- if (idx < maxAddresses) {
- unw_word_t ip;
- int rr = unw_get_reg(&cursor, UNW_REG_IP, &ip);
- if (rr < 0) {
- return -1;
+ if (elfFile->getSectionContainingAddress(adjusted)) {
+ frame.set(elfFile, adjusted, mode_);
+ --remaining;
}
-
- // If error, assume not a signal frame
- rr = unw_is_signal_frame(&cursor);
- addresses[idx] = FrameInfo(ip, (rr > 0));
}
- ++idx;
}
+}
- return idx;
+namespace {
+constexpr char kHexChars[] = "0123456789abcdef";
+constexpr auto kAddressColor = SymbolizePrinter::Color::BLUE;
+constexpr auto kFunctionColor = SymbolizePrinter::Color::PURPLE;
+constexpr auto kFileColor = SymbolizePrinter::Color::DEFAULT;
+} // namespace
+
+constexpr char AddressFormatter::bufTemplate[];
+constexpr std::array<const char*, SymbolizePrinter::Color::NUM>
+ SymbolizePrinter::kColorMap;
+
+AddressFormatter::AddressFormatter() {
+ memcpy(buf_, bufTemplate, sizeof(buf_));
}
-void Symbolizer::symbolize(FrameInfo* addresses, size_t addressCount) {
- size_t remaining = 0;
- for (size_t i = 0; i < addressCount; ++i) {
- auto& ainfo = addresses[i];
- if (!ainfo.found) {
- ++remaining;
- ainfo.name.clear();
- ainfo.location = Dwarf::LocationInfo();
- }
+folly::StringPiece AddressFormatter::format(uintptr_t address) {
+ // Can't use sprintf, not async-signal-safe
+ static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
+ char* end = buf_ + sizeof(buf_) - 1 - (16 - 2 * sizeof(uintptr_t));
+ char* p = end;
+ *p-- = '\0';
+ while (address != 0) {
+ *p-- = kHexChars[address & 0xf];
+ address >>= 4;
}
- if (remaining == 0) { // we're done
- return;
- }
+ return folly::StringPiece(buf_, end);
+}
- int fd = openNoInt("/proc/self/maps", O_RDONLY);
- if (fd == -1) {
+void SymbolizePrinter::print(uintptr_t address, const SymbolizedFrame& frame) {
+ if (options_ & TERSE) {
+ printTerse(address, frame);
return;
}
- char buf[PATH_MAX + 100]; // Long enough for any line
- LineReader reader(fd, buf, sizeof(buf));
-
- char fileNameBuf[PATH_MAX];
+ SCOPE_EXIT {
+ color(Color::DEFAULT);
+ };
- while (remaining != 0) {
- StringPiece line;
- if (reader.readLine(line) != LineReader::kReading) {
- break;
- }
+ if (!(options_ & NO_FRAME_ADDRESS)) {
+ color(kAddressColor);
- // Parse line
- uintptr_t from;
- uintptr_t to;
- StringPiece fileName;
- if (!parseProcMapsLine(line, from, to, fileName)) {
- continue;
- }
+ AddressFormatter formatter;
+ doPrint(formatter.format(address));
+ }
- bool first = true;
- ElfFile* elfFile = nullptr;
+ const char padBuf[] = " ";
+ folly::StringPiece pad(
+ padBuf, sizeof(padBuf) - 1 - (16 - 2 * sizeof(uintptr_t)));
- // See if any addresses are here
- for (size_t i = 0; i < addressCount; ++i) {
- auto& ainfo = addresses[i];
- if (ainfo.found) {
- continue;
- }
+ color(kFunctionColor);
+ if (!frame.found) {
+ doPrint(" (not found)");
+ return;
+ }
- uintptr_t address = ainfo.address;
+ if (!frame.name || frame.name[0] == '\0') {
+ doPrint(" (unknown)");
+ } else {
+ char demangledBuf[2048];
+ demangle(frame.name, demangledBuf, sizeof(demangledBuf));
+ doPrint(" ");
+ doPrint(demangledBuf[0] == '\0' ? frame.name : demangledBuf);
+ }
- // If the next address (closer to the top of the stack) was a signal
- // frame, then this is the *resume* address, which is the address
- // after the location where the signal was caught. This might be in
- // the next function, so subtract 1 before symbolizing.
- if (i != 0 && addresses[i-1].isSignalFrame) {
- --address;
- }
+ if (!(options_ & NO_FILE_AND_LINE)) {
+ color(kFileColor);
+ char fileBuf[PATH_MAX];
+ fileBuf[0] = '\0';
+ if (frame.location.hasFileAndLine) {
+ frame.location.file.toBuffer(fileBuf, sizeof(fileBuf));
+ doPrint("\n");
+ doPrint(pad);
+ doPrint(fileBuf);
- if (from > address || address >= to) {
- continue;
- }
+ char buf[22];
+ uint32_t n = uint64ToBufferUnsafe(frame.location.line, buf);
+ doPrint(":");
+ doPrint(StringPiece(buf, n));
+ }
- // Found
- ainfo.found = true;
- --remaining;
-
- // Open the file on first use
- if (first) {
- first = false;
- if (fileCount_ < kMaxFiles &&
- !fileName.empty() &&
- fileName.size() < sizeof(fileNameBuf)) {
- memcpy(fileNameBuf, fileName.data(), fileName.size());
- fileNameBuf[fileName.size()] = '\0';
- auto& f = files_[fileCount_++];
- if (f.openNoThrow(fileNameBuf) != -1) {
- elfFile = &f;
- }
- }
+ if (frame.location.hasMainFile) {
+ char mainFileBuf[PATH_MAX];
+ mainFileBuf[0] = '\0';
+ frame.location.mainFile.toBuffer(mainFileBuf, sizeof(mainFileBuf));
+ if (!frame.location.hasFileAndLine || strcmp(fileBuf, mainFileBuf)) {
+ doPrint("\n");
+ doPrint(pad);
+ doPrint("-> ");
+ doPrint(mainFileBuf);
}
+ }
+ }
+}
- if (!elfFile) {
- continue;
- }
+void SymbolizePrinter::color(SymbolizePrinter::Color color) {
+ if ((options_ & COLOR) == 0 && ((options_ & COLOR_IF_TTY) == 0 || !isTty_)) {
+ return;
+ }
+ if (static_cast<size_t>(color) >= kColorMap.size()) { // catches underflow too
+ return;
+ }
+ doPrint(kColorMap[color]);
+}
- // Undo relocation
- uintptr_t fileAddress = address - from + elfFile->getBaseAddress();
- auto sym = elfFile->getDefinitionByAddress(fileAddress);
- if (!sym.first) {
- continue;
- }
- auto name = elfFile->getSymbolName(sym);
- if (name) {
- ainfo.name = name;
- }
+void SymbolizePrinter::println(
+ uintptr_t address,
+ const SymbolizedFrame& frame) {
+ print(address, frame);
+ doPrint("\n");
+}
- Dwarf(elfFile).findAddress(fileAddress, ainfo.location);
+void SymbolizePrinter::printTerse(
+ uintptr_t address,
+ const SymbolizedFrame& frame) {
+ if (frame.found && frame.name && frame.name[0] != '\0') {
+ char demangledBuf[2048] = {0};
+ demangle(frame.name, demangledBuf, sizeof(demangledBuf));
+ doPrint(demangledBuf[0] == '\0' ? frame.name : demangledBuf);
+ } else {
+ // Can't use sprintf, not async-signal-safe
+ static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
+ char buf[] = "0x0000000000000000";
+ char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));
+ char* p = end;
+ *p-- = '\0';
+ while (address != 0) {
+ *p-- = kHexChars[address & 0xf];
+ address >>= 4;
}
+ doPrint(StringPiece(buf, end));
}
+}
- closeNoInt(fd);
+void SymbolizePrinter::println(
+ const uintptr_t* addresses,
+ const SymbolizedFrame* frames,
+ size_t frameCount) {
+ for (size_t i = 0; i < frameCount; ++i) {
+ println(addresses[i], frames[i]);
+ }
}
namespace {
-const char kHexChars[] = "0123456789abcdef";
-} // namespace
-void SymbolizePrinter::print(const FrameInfo& ainfo) {
- uintptr_t address = ainfo.address;
- // Can't use sprintf, not async-signal-safe
- static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
- char buf[] = " @ 0000000000000000";
- char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));
- const char padBuf[] = " ";
- folly::StringPiece pad(padBuf,
- sizeof(padBuf) - 1 - (16 - 2 * sizeof(uintptr_t)));
- char* p = end;
- *p-- = '\0';
- while (address != 0) {
- *p-- = kHexChars[address & 0xf];
- address >>= 4;
+int getFD(const std::ios& stream) {
+#ifdef __GNUC__
+ std::streambuf* buf = stream.rdbuf();
+ using namespace __gnu_cxx;
+
+ {
+ auto sbuf = dynamic_cast<stdio_sync_filebuf<char>*>(buf);
+ if (sbuf) {
+ return fileno(sbuf->file());
+ }
}
- doPrint(folly::StringPiece(buf, end));
+ {
+ auto sbuf = dynamic_cast<stdio_filebuf<char>*>(buf);
+ if (sbuf) {
+ return sbuf->fd();
+ }
+ }
+#endif // __GNUC__
+ return -1;
+}
- char mangledBuf[1024];
- if (!ainfo.found) {
- doPrint(" (not found)\n");
- return;
+bool isColorfulTty(int options, int fd) {
+ if ((options & SymbolizePrinter::TERSE) != 0 ||
+ (options & SymbolizePrinter::COLOR_IF_TTY) == 0 || fd < 0 ||
+ !::isatty(fd)) {
+ return false;
}
+ auto term = ::getenv("TERM");
+ return !(term == nullptr || term[0] == '\0' || strcmp(term, "dumb") == 0);
+}
- if (ainfo.name.empty()) {
- doPrint(" (unknown)\n");
- } else if (ainfo.name.size() >= sizeof(mangledBuf)) {
- doPrint(" ");
- doPrint(ainfo.name);
- doPrint("\n");
- } else {
- memcpy(mangledBuf, ainfo.name.data(), ainfo.name.size());
- mangledBuf[ainfo.name.size()] = '\0';
+} // namespace
- char demangledBuf[1024];
- demangle(mangledBuf, demangledBuf, sizeof(demangledBuf));
- doPrint(" ");
- doPrint(demangledBuf);
- doPrint("\n");
- }
+OStreamSymbolizePrinter::OStreamSymbolizePrinter(std::ostream& out, int options)
+ : SymbolizePrinter(options, isColorfulTty(options, getFD(out))),
+ out_(out) {}
- char fileBuf[PATH_MAX];
- fileBuf[0] = '\0';
- if (ainfo.location.hasFileAndLine) {
- ainfo.location.file.toBuffer(fileBuf, sizeof(fileBuf));
- doPrint(pad);
- doPrint(fileBuf);
-
- char buf[22];
- uint32_t n = uint64ToBufferUnsafe(ainfo.location.line, buf);
- doPrint(":");
- doPrint(StringPiece(buf, n));
- doPrint("\n");
- }
+void OStreamSymbolizePrinter::doPrint(StringPiece sp) {
+ out_ << sp;
+}
- if (ainfo.location.hasMainFile) {
- char mainFileBuf[PATH_MAX];
- mainFileBuf[0] = '\0';
- ainfo.location.mainFile.toBuffer(mainFileBuf, sizeof(mainFileBuf));
- if (!ainfo.location.hasFileAndLine || strcmp(fileBuf, mainFileBuf)) {
- doPrint(pad);
- doPrint("-> ");
- doPrint(mainFileBuf);
- doPrint("\n");
+FDSymbolizePrinter::FDSymbolizePrinter(int fd, int options, size_t bufferSize)
+ : SymbolizePrinter(options, isColorfulTty(options, fd)),
+ fd_(fd),
+ buffer_(bufferSize ? IOBuf::create(bufferSize) : nullptr) {}
+
+FDSymbolizePrinter::~FDSymbolizePrinter() {
+ flush();
+}
+
+void FDSymbolizePrinter::doPrint(StringPiece sp) {
+ if (buffer_) {
+ if (sp.size() > buffer_->tailroom()) {
+ flush();
+ writeFull(fd_, sp.data(), sp.size());
+ } else {
+ memcpy(buffer_->writableTail(), sp.data(), sp.size());
+ buffer_->append(sp.size());
}
+ } else {
+ writeFull(fd_, sp.data(), sp.size());
}
}
-void SymbolizePrinter::print(const FrameInfo* addresses,
- size_t addressesSize,
- size_t frameCount) {
- for (size_t i = 0; i < std::min(addressesSize, frameCount); ++i) {
- auto& ainfo = addresses[i];
- print(ainfo);
+void FDSymbolizePrinter::flush() {
+ if (buffer_ && !buffer_->empty()) {
+ writeFull(fd_, buffer_->data(), buffer_->length());
+ buffer_->clear();
}
+}
- // Indicate the number of frames that we couldn't log due to space
- if (frameCount > addressesSize) {
- char buf[22];
- uint32_t n = uint64ToBufferUnsafe(frameCount - addressesSize, buf);
- doPrint(" (");
- doPrint(StringPiece(buf, n));
- doPrint(" omitted, max buffer size reached)\n");
- }
+FILESymbolizePrinter::FILESymbolizePrinter(FILE* file, int options)
+ : SymbolizePrinter(options, isColorfulTty(options, fileno(file))),
+ file_(file) {}
+
+void FILESymbolizePrinter::doPrint(StringPiece sp) {
+ fwrite(sp.data(), 1, sp.size(), file_);
}
-void OStreamSymbolizePrinter::doPrint(StringPiece sp) {
- out_ << sp;
+void StringSymbolizePrinter::doPrint(StringPiece sp) {
+ buf_.append(sp.data(), sp.size());
}
-void FDSymbolizePrinter::doPrint(StringPiece sp) {
- writeFull(fd_, sp.data(), sp.size());
+StackTracePrinter::StackTracePrinter(size_t minSignalSafeElfCacheSize, int fd)
+ : fd_(fd),
+ elfCache_(std::max(countLoadedElfFiles(), minSignalSafeElfCacheSize)),
+ printer_(
+ fd,
+ SymbolizePrinter::COLOR_IF_TTY,
+ size_t(64) << 10), // 64KiB
+ addresses_(std::make_unique<FrameArray<kMaxStackTraceDepth>>()) {}
+
+void StackTracePrinter::flush() {
+ printer_.flush();
+ fsyncNoInt(fd_);
}
-std::ostream& operator<<(std::ostream& out, const FrameInfo& ainfo) {
- OStreamSymbolizePrinter osp(out);
- osp.print(ainfo);
- return out;
+void StackTracePrinter::printStackTrace(bool symbolize) {
+ SCOPE_EXIT {
+ flush();
+ };
+
+ // Skip the getStackTrace frame
+ if (!getStackTraceSafe(*addresses_)) {
+ print("(error retrieving stack trace)\n");
+ } else if (symbolize) {
+ // Do our best to populate location info, process is going to terminate,
+ // so performance isn't critical.
+ Symbolizer symbolizer(&elfCache_, Dwarf::LocationInfoMode::FULL);
+ symbolizer.symbolize(*addresses_);
+
+ // Skip the top 2 frames:
+ // getStackTraceSafe
+ // StackTracePrinter::printStackTrace (here)
+ //
+ // Leaving signalHandler on the stack for clarity, I think.
+ printer_.println(*addresses_, 2);
+ } else {
+ print("(safe mode, symbolizer not available)\n");
+ AddressFormatter formatter;
+ for (size_t i = 0; i < addresses_->frameCount; ++i) {
+ print(formatter.format(addresses_->addresses[i]));
+ print("\n");
+ }
+ }
}
-} // namespace symbolizer
-} // namespace folly
+} // namespace symbolizer
+} // namespace folly