2 * Copyright 2015 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 name = file->getSymbolName(sym);
177 Dwarf(file.get()).findAddress(address, location);
181 Symbolizer::Symbolizer(ElfCacheBase* cache)
182 : cache_(cache ?: defaultElfCache()) {
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];
197 if (remaining == 0) { // we're done
201 int fd = openNoInt("/proc/self/maps", O_RDONLY);
206 char buf[PATH_MAX + 100]; // Long enough for any line
207 LineReader reader(fd, buf, sizeof(buf));
209 while (remaining != 0) {
211 if (reader.readLine(line) != LineReader::kReading) {
218 StringPiece fileName;
219 if (!parseProcMapsLine(line, from, to, fileName)) {
224 std::shared_ptr<ElfFile> elfFile;
226 // See if any addresses are here
227 for (size_t i = 0; i < addressCount; ++i) {
228 auto& frame = frames[i];
233 uintptr_t address = addresses[i];
235 if (from > address || address >= to) {
243 // Open the file on first use
246 elfFile = cache_->getFile(fileName);
254 frame.set(elfFile, address - from);
262 constexpr char kHexChars[] = "0123456789abcdef";
263 constexpr auto kAddressColor = SymbolizePrinter::Color::BLUE;
264 constexpr auto kFunctionColor = SymbolizePrinter::Color::PURPLE;
265 constexpr auto kFileColor = SymbolizePrinter::Color::DEFAULT;
268 constexpr char AddressFormatter::bufTemplate[];
269 constexpr std::array<const char*, SymbolizePrinter::Color::NUM>
270 SymbolizePrinter::kColorMap;
272 AddressFormatter::AddressFormatter() {
273 memcpy(buf_, bufTemplate, sizeof(buf_));
276 folly::StringPiece AddressFormatter::format(uintptr_t address) {
277 // Can't use sprintf, not async-signal-safe
278 static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
279 char* end = buf_ + sizeof(buf_) - 1 - (16 - 2 * sizeof(uintptr_t));
282 while (address != 0) {
283 *p-- = kHexChars[address & 0xf];
287 return folly::StringPiece(buf_, end);
290 void SymbolizePrinter::print(uintptr_t address, const SymbolizedFrame& frame) {
291 if (options_ & TERSE) {
292 printTerse(address, frame);
296 SCOPE_EXIT { color(Color::DEFAULT); };
298 color(kAddressColor);
300 AddressFormatter formatter;
301 doPrint(formatter.format(address));
303 const char padBuf[] = " ";
304 folly::StringPiece pad(padBuf,
305 sizeof(padBuf) - 1 - (16 - 2 * sizeof(uintptr_t)));
307 color(kFunctionColor);
309 doPrint(" (not found)");
313 if (!frame.name || frame.name[0] == '\0') {
314 doPrint(" (unknown)");
316 char demangledBuf[2048];
317 demangle(frame.name, demangledBuf, sizeof(demangledBuf));
319 doPrint(demangledBuf[0] == '\0' ? frame.name : demangledBuf);
322 if (!(options_ & NO_FILE_AND_LINE)) {
324 char fileBuf[PATH_MAX];
326 if (frame.location.hasFileAndLine) {
327 frame.location.file.toBuffer(fileBuf, sizeof(fileBuf));
333 uint32_t n = uint64ToBufferUnsafe(frame.location.line, buf);
335 doPrint(StringPiece(buf, n));
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)) {
346 doPrint(mainFileBuf);
352 void SymbolizePrinter::color(SymbolizePrinter::Color color) {
353 if ((options_ & COLOR) == 0 &&
354 ((options_ & COLOR_IF_TTY) == 0 || !isTty_)) {
357 if (color < 0 || color >= kColorMap.size()) {
360 doPrint(kColorMap[color]);
363 void SymbolizePrinter::println(uintptr_t address,
364 const SymbolizedFrame& frame) {
365 print(address, frame);
369 void SymbolizePrinter::printTerse(uintptr_t address,
370 const SymbolizedFrame& frame) {
371 if (frame.found && frame.name && frame.name[0] != '\0') {
372 char demangledBuf[2048] = {0};
373 demangle(frame.name, demangledBuf, sizeof(demangledBuf));
374 doPrint(demangledBuf[0] == '\0' ? frame.name : demangledBuf);
376 // Can't use sprintf, not async-signal-safe
377 static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
378 char buf[] = "0x0000000000000000";
379 char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));
382 while (address != 0) {
383 *p-- = kHexChars[address & 0xf];
386 doPrint(StringPiece(buf, end));
390 void SymbolizePrinter::println(const uintptr_t* addresses,
391 const SymbolizedFrame* frames,
393 for (size_t i = 0; i < frameCount; ++i) {
394 println(addresses[i], frames[i]);
400 int getFD(const std::ios& stream) {
402 std::streambuf* buf = stream.rdbuf();
403 using namespace __gnu_cxx;
406 auto sbuf = dynamic_cast<stdio_sync_filebuf<char>*>(buf);
408 return fileno(sbuf->file());
412 auto sbuf = dynamic_cast<stdio_filebuf<char>*>(buf);
421 bool isColorfulTty(int options, int fd) {
422 if ((options & SymbolizePrinter::TERSE) != 0 ||
423 (options & SymbolizePrinter::COLOR_IF_TTY) == 0 ||
424 fd < 0 || !::isatty(fd)) {
427 auto term = ::getenv("TERM");
428 return !(term == nullptr || term[0] == '\0' || strcmp(term, "dumb") == 0);
431 } // anonymous namespace
433 OStreamSymbolizePrinter::OStreamSymbolizePrinter(std::ostream& out, int options)
434 : SymbolizePrinter(options, isColorfulTty(options, getFD(out))),
438 void OStreamSymbolizePrinter::doPrint(StringPiece sp) {
442 FDSymbolizePrinter::FDSymbolizePrinter(int fd, int options, size_t bufferSize)
443 : SymbolizePrinter(options, isColorfulTty(options, fd)),
445 buffer_(bufferSize ? IOBuf::create(bufferSize) : nullptr) {
448 FDSymbolizePrinter::~FDSymbolizePrinter() {
452 void FDSymbolizePrinter::doPrint(StringPiece sp) {
454 if (sp.size() > buffer_->tailroom()) {
456 writeFull(fd_, sp.data(), sp.size());
458 memcpy(buffer_->writableTail(), sp.data(), sp.size());
459 buffer_->append(sp.size());
462 writeFull(fd_, sp.data(), sp.size());
466 void FDSymbolizePrinter::flush() {
467 if (buffer_ && !buffer_->empty()) {
468 writeFull(fd_, buffer_->data(), buffer_->length());
473 FILESymbolizePrinter::FILESymbolizePrinter(FILE* file, int options)
474 : SymbolizePrinter(options, isColorfulTty(options, fileno(file))),
478 void FILESymbolizePrinter::doPrint(StringPiece sp) {
479 fwrite(sp.data(), 1, sp.size(), file_);
482 void StringSymbolizePrinter::doPrint(StringPiece sp) {
483 buf_.append(sp.data(), sp.size());
486 } // namespace symbolizer