2 * Copyright 2017 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.
24 #include <folly/FBString.h>
25 #include <folly/Range.h>
26 #include <folly/String.h>
27 #include <folly/experimental/symbolizer/Dwarf.h>
28 #include <folly/experimental/symbolizer/Elf.h>
29 #include <folly/experimental/symbolizer/ElfCache.h>
30 #include <folly/experimental/symbolizer/StackTrace.h>
31 #include <folly/io/IOBuf.h>
34 namespace symbolizer {
39 * Frame information: symbol name and location.
41 struct SymbolizedFrame {
45 const std::shared_ptr<ElfFile>& file,
47 Dwarf::LocationInfoMode mode);
50 *this = SymbolizedFrame();
54 const char* name = nullptr;
55 Dwarf::LocationInfo location;
58 * Demangle the name and return it. Not async-signal-safe; allocates memory.
60 fbstring demangledName() const {
61 return name ? demangle(name) : fbstring();
65 std::shared_ptr<ElfFile> file_;
72 size_t frameCount = 0;
73 uintptr_t addresses[N];
74 SymbolizedFrame frames[N];
78 * Get stack trace into a given FrameArray, return true on success (and
79 * set frameCount to the actual frame count, which may be > N) and false
84 bool fixFrameArray(FrameArray<N>& fa, ssize_t n) {
87 for (size_t i = 0; i < fa.frameCount; ++i) {
88 fa.frames[i].found = false;
98 // Always inline these functions; they don't do much, and unittests rely
99 // on them never showing up in a stack trace.
101 FOLLY_ALWAYS_INLINE bool getStackTrace(FrameArray<N>& fa);
104 inline bool getStackTrace(FrameArray<N>& fa) {
105 return detail::fixFrameArray(fa, getStackTrace(fa.addresses, N));
108 FOLLY_ALWAYS_INLINE bool getStackTraceSafe(FrameArray<N>& fa);
111 inline bool getStackTraceSafe(FrameArray<N>& fa) {
112 return detail::fixFrameArray(fa, getStackTraceSafe(fa.addresses, N));
117 static constexpr Dwarf::LocationInfoMode kDefaultLocationInfoMode =
118 Dwarf::LocationInfoMode::FAST;
120 explicit Symbolizer(Dwarf::LocationInfoMode mode = kDefaultLocationInfoMode)
121 : Symbolizer(nullptr, mode) {}
125 Dwarf::LocationInfoMode mode = kDefaultLocationInfoMode);
128 * Symbolize given addresses.
131 const uintptr_t* addresses,
132 SymbolizedFrame* frames,
136 void symbolize(FrameArray<N>& fa) {
137 symbolize(fa.addresses, fa.frames, fa.frameCount);
141 * Shortcut to symbolize one address.
143 bool symbolize(uintptr_t address, SymbolizedFrame& frame) {
144 symbolize(&address, &frame, 1);
149 ElfCacheBase* const cache_;
150 const Dwarf::LocationInfoMode mode_;
154 * Format one address in the way it's usually printed by SymbolizePrinter.
157 class AddressFormatter {
162 * Format the address. Returns an internal buffer.
164 StringPiece format(uintptr_t address);
167 static constexpr char bufTemplate[] = " @ 0000000000000000";
168 char buf_[sizeof(bufTemplate)];
172 * Print a list of symbolized addresses. Base class.
174 class SymbolizePrinter {
177 * Print one address, no ending newline.
179 void print(uintptr_t address, const SymbolizedFrame& frame);
182 * Print one address with ending newline.
184 void println(uintptr_t address, const SymbolizedFrame& frame);
187 * Print multiple addresses on separate lines.
190 const uintptr_t* addresses,
191 const SymbolizedFrame* frames,
195 * Print a string, no endling newline.
197 void print(StringPiece sp) {
202 * Print multiple addresses on separate lines, skipping the first
206 void println(const FrameArray<N>& fa, size_t skip = 0) {
207 if (skip < fa.frameCount) {
208 println(fa.addresses + skip, fa.frames + skip, fa.frameCount - skip);
212 virtual ~SymbolizePrinter() {}
215 // Skip file and line information
216 NO_FILE_AND_LINE = 1 << 0,
218 // As terse as it gets: function name if found, address otherwise
221 // Always colorize output (ANSI escape code)
224 // Colorize output only if output is printed to a TTY (ANSI escape code)
225 COLOR_IF_TTY = 1 << 3,
227 // Skip frame address information
228 NO_FRAME_ADDRESS = 1 << 4,
231 // NOTE: enum values used as indexes in kColorMap.
232 enum Color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, WHITE, PURPLE, NUM };
236 explicit SymbolizePrinter(int options, bool isTty = false)
237 : options_(options), isTty_(isTty) {}
243 void printTerse(uintptr_t address, const SymbolizedFrame& frame);
244 virtual void doPrint(StringPiece sp) = 0;
246 static constexpr std::array<const char*, Color::NUM> kColorMap = {{
259 * Print a list of symbolized addresses to a stream.
260 * Not reentrant. Do not use from signal handling code.
262 class OStreamSymbolizePrinter : public SymbolizePrinter {
264 explicit OStreamSymbolizePrinter(std::ostream& out, int options = 0);
267 void doPrint(StringPiece sp) override;
272 * Print a list of symbolized addresses to a file descriptor.
273 * Ignores errors. Async-signal-safe.
275 class FDSymbolizePrinter : public SymbolizePrinter {
277 explicit FDSymbolizePrinter(int fd, int options = 0, size_t bufferSize = 0);
278 ~FDSymbolizePrinter() override;
282 void doPrint(StringPiece sp) override;
285 std::unique_ptr<IOBuf> buffer_;
289 * Print a list of symbolized addresses to a FILE*.
290 * Ignores errors. Not reentrant. Do not use from signal handling code.
292 class FILESymbolizePrinter : public SymbolizePrinter {
294 explicit FILESymbolizePrinter(FILE* file, int options = 0);
297 void doPrint(StringPiece sp) override;
298 FILE* const file_ = nullptr;
302 * Print a list of symbolized addresses to a std::string.
303 * Not reentrant. Do not use from signal handling code.
305 class StringSymbolizePrinter : public SymbolizePrinter {
307 explicit StringSymbolizePrinter(int options = 0)
308 : SymbolizePrinter(options) {}
310 std::string str() const {
311 return buf_.toStdString();
313 const fbstring& fbstr() const {
316 fbstring moveFbString() {
317 return std::move(buf_);
321 void doPrint(StringPiece sp) override;
326 * Use this class to print a stack trace from a signal handler, or other place
327 * where you shouldn't allocate memory on the heap, and fsync()ing your file
328 * descriptor is more important than performance.
330 * Make sure to create one of these on startup, not in the signal handler, as
331 * the constructo allocates on the heap, whereas the other methods don't. Best
332 * practice is to just leak this object, rather than worry about destruction
335 * These methods aren't thread safe, so if you could have signals on multiple
336 * threads at the same time, you need to do your own locking to ensure you don't
337 * call these methods from multiple threads. They are signal safe, however.
339 class StackTracePrinter {
341 static constexpr size_t kDefaultMinSignalSafeElfCacheSize = 500;
343 explicit StackTracePrinter(
344 size_t minSignalSafeElfCacheSize = kDefaultMinSignalSafeElfCacheSize,
345 int fd = STDERR_FILENO);
348 * Only allocates on the stack and is signal-safe but not thread-safe. Don't
349 * call printStackTrace() on the same StackTracePrinter object from multiple
350 * threads at the same time.
352 FOLLY_NOINLINE void printStackTrace(bool symbolize);
354 void print(StringPiece sp) {
358 // Flush printer_, also fsync, in case we're about to crash again...
362 static constexpr size_t kMaxStackTraceDepth = 100;
365 SignalSafeElfCache elfCache_;
366 FDSymbolizePrinter printer_;
367 std::unique_ptr<FrameArray<kMaxStackTraceDepth>> addresses_;
370 } // namespace symbolizer