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 Symbolizer::Symbolizer(ElfCacheBase* cache)
164 : cache_(cache ?: defaultElfCache()) {
167 void Symbolizer::symbolize(const uintptr_t* addresses,
168 SymbolizedFrame* frames,
169 size_t addressCount) {
170 size_t remaining = 0;
171 for (size_t i = 0; i < addressCount; ++i) {
172 auto& frame = frames[i];
176 frame.location = Dwarf::LocationInfo();
180 if (remaining == 0) { // we're done
184 int fd = openNoInt("/proc/self/maps", O_RDONLY);
189 char buf[PATH_MAX + 100]; // Long enough for any line
190 LineReader reader(fd, buf, sizeof(buf));
192 char fileNameBuf[PATH_MAX];
194 while (remaining != 0) {
196 if (reader.readLine(line) != LineReader::kReading) {
203 StringPiece fileName;
204 if (!parseProcMapsLine(line, from, to, fileName)) {
209 std::shared_ptr<ElfFile> elfFile;
211 // See if any addresses are here
212 for (size_t i = 0; i < addressCount; ++i) {
213 auto& frame = frames[i];
218 uintptr_t address = addresses[i];
220 if (from > address || address >= to) {
228 // Open the file on first use
231 elfFile = cache_->getFile(fileName);
239 uintptr_t fileAddress = address - from + elfFile->getBaseAddress();
240 auto sym = elfFile->getDefinitionByAddress(fileAddress);
244 auto name = elfFile->getSymbolName(sym);
249 Dwarf(elfFile.get()).findAddress(fileAddress, frame.location);
257 const char kHexChars[] = "0123456789abcdef";
258 const SymbolizePrinter::Color kAddressColor = SymbolizePrinter::Color::BLUE;
259 const SymbolizePrinter::Color kFunctionColor = SymbolizePrinter::Color::PURPLE;
260 const SymbolizePrinter::Color kFileColor = SymbolizePrinter::Color::DEFAULT;
263 void SymbolizePrinter::print(uintptr_t address, const SymbolizedFrame& frame) {
264 if (options_ & TERSE) {
265 printTerse(address, frame);
269 SCOPE_EXIT { color(Color::DEFAULT); };
271 color(kAddressColor);
272 // Can't use sprintf, not async-signal-safe
273 static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
274 char buf[] = " @ 0000000000000000";
275 char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));
276 const char padBuf[] = " ";
277 folly::StringPiece pad(padBuf,
278 sizeof(padBuf) - 1 - (16 - 2 * sizeof(uintptr_t)));
281 while (address != 0) {
282 *p-- = kHexChars[address & 0xf];
285 doPrint(folly::StringPiece(buf, end));
287 color(kFunctionColor);
288 char mangledBuf[1024];
290 doPrint(" (not found)");
294 if (frame.name.empty()) {
295 doPrint(" (unknown)");
296 } else if (frame.name.size() >= sizeof(mangledBuf)) {
300 memcpy(mangledBuf, frame.name.data(), frame.name.size());
301 mangledBuf[frame.name.size()] = '\0';
303 char demangledBuf[1024];
304 demangle(mangledBuf, demangledBuf, sizeof(demangledBuf));
306 doPrint(demangledBuf);
309 if (!(options_ & NO_FILE_AND_LINE)) {
311 char fileBuf[PATH_MAX];
313 if (frame.location.hasFileAndLine) {
314 frame.location.file.toBuffer(fileBuf, sizeof(fileBuf));
320 uint32_t n = uint64ToBufferUnsafe(frame.location.line, buf);
322 doPrint(StringPiece(buf, n));
325 if (frame.location.hasMainFile) {
326 char mainFileBuf[PATH_MAX];
327 mainFileBuf[0] = '\0';
328 frame.location.mainFile.toBuffer(mainFileBuf, sizeof(mainFileBuf));
329 if (!frame.location.hasFileAndLine || strcmp(fileBuf, mainFileBuf)) {
333 doPrint(mainFileBuf);
341 const std::map<SymbolizePrinter::Color, std::string> kColorMap = {
342 { SymbolizePrinter::Color::DEFAULT, "\x1B[0m" },
343 { SymbolizePrinter::Color::RED, "\x1B[31m" },
344 { SymbolizePrinter::Color::GREEN, "\x1B[32m" },
345 { SymbolizePrinter::Color::YELLOW, "\x1B[33m" },
346 { SymbolizePrinter::Color::BLUE, "\x1B[34m" },
347 { SymbolizePrinter::Color::CYAN, "\x1B[36m" },
348 { SymbolizePrinter::Color::WHITE, "\x1B[37m" },
349 { SymbolizePrinter::Color::PURPLE, "\x1B[35m" },
354 void SymbolizePrinter::color(SymbolizePrinter::Color color) {
355 if ((options_ & COLOR) == 0 &&
356 ((options_ & COLOR_IF_TTY) == 0 || !isTty_)) {
359 auto it = kColorMap.find(color);
360 if (it == kColorMap.end()) {
366 void SymbolizePrinter::println(uintptr_t address,
367 const SymbolizedFrame& frame) {
368 print(address, frame);
372 void SymbolizePrinter::printTerse(uintptr_t address,
373 const SymbolizedFrame& frame) {
375 char mangledBuf[1024];
376 memcpy(mangledBuf, frame.name.data(), frame.name.size());
377 mangledBuf[frame.name.size()] = '\0';
379 char demangledBuf[1024] = {0};
380 demangle(mangledBuf, demangledBuf, sizeof(demangledBuf));
381 doPrint(strlen(demangledBuf) == 0 ? "(unknown)" : demangledBuf);
383 // Can't use sprintf, not async-signal-safe
384 static_assert(sizeof(uintptr_t) <= 8, "huge uintptr_t?");
385 char buf[] = "0x0000000000000000";
386 char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));
389 while (address != 0) {
390 *p-- = kHexChars[address & 0xf];
393 doPrint(StringPiece(buf, end));
397 void SymbolizePrinter::println(const uintptr_t* addresses,
398 const SymbolizedFrame* frames,
400 for (size_t i = 0; i < frameCount; ++i) {
401 println(addresses[i], frames[i]);
407 int getFD(const std::ios& stream) {
409 std::streambuf* buf = stream.rdbuf();
410 using namespace __gnu_cxx;
413 auto sbuf = dynamic_cast<stdio_sync_filebuf<char>*>(buf);
415 return fileno(sbuf->file());
419 auto sbuf = dynamic_cast<stdio_filebuf<char>*>(buf);
428 bool isTty(int options, int fd) {
429 return ((options & SymbolizePrinter::TERSE) == 0 &&
430 (options & SymbolizePrinter::COLOR_IF_TTY) != 0 &&
431 fd >= 0 && ::isatty(fd));
434 } // anonymous namespace
436 OStreamSymbolizePrinter::OStreamSymbolizePrinter(std::ostream& out, int options)
437 : SymbolizePrinter(options, isTty(options, getFD(out))),
441 void OStreamSymbolizePrinter::doPrint(StringPiece sp) {
445 FDSymbolizePrinter::FDSymbolizePrinter(int fd, int options)
446 : SymbolizePrinter(options, isTty(options, fd)),
450 void FDSymbolizePrinter::doPrint(StringPiece sp) {
451 writeFull(fd_, sp.data(), sp.size());
454 FILESymbolizePrinter::FILESymbolizePrinter(FILE* file, int options)
455 : SymbolizePrinter(options, isTty(options, fileno(file))),
459 void FILESymbolizePrinter::doPrint(StringPiece sp) {
460 fwrite(sp.data(), 1, sp.size(), file_);
463 void StringSymbolizePrinter::doPrint(StringPiece sp) {
464 buf_.append(sp.data(), sp.size());
467 } // namespace symbolizer