1 // GNU D Compiler routines for stack backtrace support.
2 // Copyright (C) 2013-2019 Free Software Foundation, Inc.
4 // GCC is free software; you can redistribute it and/or modify it under
5 // the terms of the GNU General Public License as published by the Free
6 // Software Foundation; either version 3, or (at your option) any later
9 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
10 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 // Under Section 7 of GPL version 3, you are granted additional
15 // permissions described in the GCC Runtime Library Exception, version
16 // 3.1, as published by the Free Software Foundation.
18 // You should have received a copy of the GNU General Public License and
19 // a copy of the GCC Runtime Library Exception along with this program;
20 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
21 // <http://www.gnu.org/licenses/>.
25 import gcc.libbacktrace;
29 // NOTE: The first 5 frames with the current implementation are
30 // inside core.runtime and the object code, so eliminate
31 // these for readability. The alternative would be to
32 // exclude the first N frames that are in a list of
33 // mangled function names.
34 private enum FIRSTFRAME = 5;
38 // NOTE: On Windows, the number of frames to exclude is based on
39 // whether the exception is user or system-generated, so
40 // it may be necessary to exclude a list of function names
42 private enum FIRSTFRAME = 0;
45 // Max size per line of the traceback.
46 private enum MAX_BUFSIZE = 1536;
48 static if (BACKTRACE_SUPPORTED && !BACKTRACE_USES_MALLOC)
50 import core.stdc.stdint, core.stdc.string, core.stdc.stdio;
51 private enum MAXFRAMES = 128;
53 extern(C) int simpleCallback(void* data, uintptr_t pc)
55 auto context = cast(LibBacktrace)data;
57 if (context.numPCs == MAXFRAMES)
60 context.pcs[context.numPCs++] = pc;
65 * Used for backtrace_create_state and backtrace_simple
67 extern(C) void simpleErrorCallback(void* data, const(char)* msg, int errnum)
69 if (data) // context is not available in backtrace_create_state
71 auto context = cast(LibBacktrace)data;
72 strncpy(context.errorBuf.ptr, msg, context.errorBuf.length - 1);
73 context.error = errnum;
78 * Used for backtrace_pcinfo
80 extern(C) int pcinfoCallback(void* data, uintptr_t pc, const(char)* filename,
81 int lineno, const(char)* func)
83 auto context = cast(SymbolCallbackInfo*)data;
85 // Try to get the function name via backtrace_syminfo
88 SymbolCallbackInfo2 info;
90 info.filename = filename;
92 if (backtrace_syminfo(context.state, pc, &syminfoCallback2, null, &info) != 0)
94 return context.retval;
98 auto sym = SymbolOrError(0, SymbolInfo(func, filename, lineno, cast(void*)pc));
99 context.retval = context.applyCB(context.num, sym);
102 return context.retval;
106 * Used for backtrace_pcinfo and backtrace_syminfo
108 extern(C) void pcinfoErrorCallback(void* data, const(char)* msg, int errnum)
110 auto context = cast(SymbolCallbackInfo*)data;
114 context.noInfo = true;
118 SymbolOrError symError;
119 symError.errnum = errnum;
123 context.retval = context.applyCB(i, symError);
127 * Used for backtrace_syminfo (in opApply)
129 extern(C) void syminfoCallback(void* data, uintptr_t pc,
130 const(char)* symname, uintptr_t symval)
132 auto context = cast(SymbolCallbackInfo*)data;
134 auto sym = SymbolOrError(0, SymbolInfo(symname, null, 0, cast(void*)pc));
135 context.retval = context.applyCB(context.num, sym);
141 * This callback is used if backtrace_syminfo is called from the pcinfoCallback
142 * callback. It merges it's information with the information from pcinfoCallback.
144 extern(C) void syminfoCallback2(void* data, uintptr_t pc,
145 const(char)* symname, uintptr_t symval)
147 auto context = cast(SymbolCallbackInfo2*)data;
149 auto sym = SymbolOrError(0, SymbolInfo(symname, context.filename, context.lineno,
151 context.base.retval = context.base.applyCB(context.base.num, sym);
157 * The callback type used with the opApply overload which returns a SymbolOrError
159 private alias int delegate(ref size_t, ref SymbolOrError) ApplyCallback;
162 * Passed to syminfoCallback, pcinfoCallback and pcinfoErrorCallback
164 struct SymbolCallbackInfo
166 bool noInfo = false; // True if debug info / symbol table is not available
167 size_t num = 0; // Counter for opApply
168 int retval; // Value returned by applyCB
169 backtrace_state* state;
171 // info.fileName / funcName / errmsg may become invalid after this delegate returned
172 ApplyCallback applyCB;
182 * Passed to the syminfoCallback2 callback. That function merges it's
183 * funcName with this information and updates base as all other callbacks do.
185 struct SymbolCallbackInfo2
187 SymbolCallbackInfo* base;
188 const(char)* filename;
193 * Contains a valid symbol or an error message if errnum is != 0.
197 int errnum; // == 0: No error
205 // FIXME: state is never freed as libbacktrace doesn't provide a free function...
206 public class LibBacktrace : Throwable.TraceInfo
208 enum MaxAlignment = (void*).alignof;
210 static void initLibBacktrace()
214 state = backtrace_create_state(null, false, &simpleErrorCallback, null);
219 this(int firstFrame = FIRSTFRAME)
221 _firstFrame = firstFrame;
227 backtrace_simple(state, _firstFrame, &simpleCallback,
228 &simpleErrorCallback, cast(void*)this);
232 override int opApply(scope int delegate(ref const(char[])) dg) const
235 (ref size_t, ref const(char[]) buf)
242 override int opApply(scope int delegate(ref size_t, ref const(char[])) dg) const
245 (ref size_t i, ref SymbolOrError sym)
247 char[MAX_BUFSIZE] buffer = void;
251 auto retval = snprintf(buffer.ptr, buffer.length,
252 "libbacktrace error: '%s' errno: %d", sym.msg, sym.errnum);
253 if (retval >= buffer.length)
254 retval = buffer.length - 1; // Ignore zero terminator
256 msg = buffer[0 .. retval];
261 msg = formatLine(sym.symbol, buffer);
262 int ret = dg(i, msg);
264 if (!ret && sym.symbol.funcName && strcmp(sym.symbol.funcName, "_Dmain") == 0)
272 int opApply(scope ApplyCallback dg) const
276 // If backtrace_simple produced an error report it and exit
277 if (!state || error != 0)
280 SymbolOrError symError;
283 symError.msg = "libbacktrace failed to initialize\0";
288 symError.errnum = error;
289 symError.msg = errorBuf.ptr;
292 return dg(pos, symError);
295 SymbolCallbackInfo cinfo;
297 cinfo.state = cast(backtrace_state*)state;
299 // Try using debug info first
300 foreach (i, pc; pcs[0 .. numPCs])
302 // FIXME: We may violate const guarantees here...
303 if (backtrace_pcinfo(cast(backtrace_state*)state, pc, &pcinfoCallback,
304 &pcinfoErrorCallback, &cinfo) != 0)
306 break; // User delegate requested abort or no debug info at all
310 // If no error or other error which has already been reported via callback
314 // Try using symbol table
316 foreach (pc; pcs[0 .. numPCs])
318 if (backtrace_syminfo(cast(backtrace_state*)state, pc, &syminfoCallback,
319 &pcinfoErrorCallback, &cinfo) == 0)
329 foreach (i, pc; pcs[0 .. numPCs])
331 auto sym = SymbolOrError(0, SymbolInfo(null, null, 0, cast(void*)pc));
332 if (auto ret = dg(i, sym) != 0)
339 override string toString() const
342 foreach (i, const(char[]) line; this)
343 buf ~= i ? "\n" ~ line : line;
348 static backtrace_state* state = null;
349 static bool initialized = false;
351 uintptr_t[MAXFRAMES] pcs;
355 char[128] errorBuf = "\0";
361 * Our fallback backtrace implementation using libgcc's unwind
362 * and backtrace support. In theory libbacktrace should be available
363 * everywhere where this code works. We keep it anyway till libbacktrace
366 public class UnwindBacktrace : Throwable.TraceInfo
368 this(int firstFrame = FIRSTFRAME)
370 _firstFrame = firstFrame;
371 _callstack = getBacktrace();
372 _framelist = getBacktraceSymbols(_callstack);
375 override int opApply(scope int delegate(ref const(char[])) dg) const
378 (ref size_t, ref const(char[]) buf)
385 override int opApply(scope int delegate(ref size_t, ref const(char[])) dg) const
387 char[MAX_BUFSIZE] buffer = void;
390 for (int i = _firstFrame; i < _framelist.entries; ++i)
392 auto pos = cast(size_t)(i - _firstFrame);
393 auto msg = formatLine(_framelist.symbols[i], buffer);
401 override string toString() const
404 foreach (i, line; this)
405 buf ~= i ? "\n" ~ line : line;
410 BTSymbolData _framelist;
411 UnwindBacktraceData _callstack;
415 // Implementation details
420 import core.sys.linux.dlfcn;
422 import core.sys.darwin.dlfcn;
423 else version (FreeBSD)
424 import core.sys.freebsd.dlfcn;
425 else version (NetBSD)
426 import core.sys.netbsd.dlfcn;
427 else version (Solaris)
428 import core.sys.netbsd.dlfcn;
430 import core.sys.posix.dlfcn;
432 private enum MAXFRAMES = 128;
434 struct UnwindBacktraceData
436 void*[MAXFRAMES] callstack;
443 SymbolInfo[MAXFRAMES] symbols;
446 static extern (C) _Unwind_Reason_Code unwindCB(_Unwind_Context *ctx, void *d)
448 UnwindBacktraceData* bt = cast(UnwindBacktraceData*)d;
449 if (bt.numframes >= MAXFRAMES)
450 return _URC_NO_REASON;
452 bt.callstack[bt.numframes] = cast(void*)_Unwind_GetIP(ctx);
454 return _URC_NO_REASON;
457 UnwindBacktraceData getBacktrace()
459 UnwindBacktraceData stackframe;
460 _Unwind_Backtrace(&unwindCB, &stackframe);
464 BTSymbolData getBacktraceSymbols(UnwindBacktraceData data)
466 BTSymbolData symData;
468 for (auto i = 0; i < data.numframes; i++)
470 static if ( __traits(compiles, Dl_info))
474 if (data.callstack[i] !is null && dladdr(data.callstack[i], &funcInfo) != 0)
476 symData.symbols[symData.entries].funcName = funcInfo.dli_sname;
478 symData.symbols[symData.entries].address = data.callstack[i];
483 symData.symbols[symData.entries].address = data.callstack[i];
489 symData.symbols[symData.entries].address = data.callstack[i];
499 * Struct representing a symbol (function) in the backtrace
503 const(char)* funcName, fileName;
505 const(void)* address;
509 * Format one output line for symbol sym.
510 * Returns a slice of buffer.
512 char[] formatLine(const SymbolInfo sym, return ref char[MAX_BUFSIZE] buffer)
514 import core.demangle, core.stdc.config;
515 import core.stdc.stdio : snprintf, printf;
516 import core.stdc.string : strlen;
518 size_t bufferLength = 0;
520 void appendToBuffer(Args...)(const(char)* format, Args args)
522 const count = snprintf(buffer.ptr + bufferLength,
523 buffer.length - bufferLength,
526 bufferLength += count;
527 if (bufferLength >= buffer.length)
528 bufferLength = buffer.length - 1;
532 if (sym.fileName is null)
533 appendToBuffer("??:? ");
535 appendToBuffer("%s:%d ", sym.fileName, sym.line);
537 if (sym.funcName is null)
538 appendToBuffer("???");
541 char[1024] symbol = void;
542 auto demangled = demangle(sym.funcName[0 .. strlen(sym.funcName)], symbol);
544 if (demangled.length > 0)
545 appendToBuffer("%.*s ", cast(int) demangled.length, demangled.ptr);
549 appendToBuffer("[0x%llx]", cast(size_t)sym.address);
551 appendToBuffer("[0x%x]", cast(size_t)sym.address);
553 return buffer[0 .. bufferLength];
559 char[MAX_BUFSIZE] sbuf = '\0';
562 for (size_t i = 0; i < 60; i++)
563 longString ~= "abcdefghij";
566 auto symbol = SymbolInfo(null, null, 0, null);
567 result = formatLine(symbol, sbuf);
568 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
570 symbol = SymbolInfo(longString.ptr, null, 0, null);
571 result = formatLine(symbol, sbuf);
572 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
574 symbol = SymbolInfo("func", "test.d", 0, null);
575 result = formatLine(symbol, sbuf);
576 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
578 symbol = SymbolInfo("func", longString.ptr, 0, null);
579 result = formatLine(symbol, sbuf);
580 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
582 symbol = SymbolInfo(longString.ptr, "test.d", 0, null);
583 result = formatLine(symbol, sbuf);
584 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
586 symbol = SymbolInfo(longString.ptr, longString.ptr, 0, null);
587 result = formatLine(symbol, sbuf);
588 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
590 symbol = SymbolInfo("func", "test.d", 1000, null);
591 result = formatLine(symbol, sbuf);
592 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
594 symbol = SymbolInfo(null, (longString[0..500] ~ '\0').ptr, 100000000, null);
595 result = formatLine(symbol, sbuf);
596 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
598 symbol = SymbolInfo("func", "test.d", 0, cast(void*)0x100000);
599 result = formatLine(symbol, sbuf);
600 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
602 symbol = SymbolInfo("func", null, 0, cast(void*)0x100000);
603 result = formatLine(symbol, sbuf);
604 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
606 symbol = SymbolInfo(null, "test.d", 0, cast(void*)0x100000);
607 result = formatLine(symbol, sbuf);
608 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
610 symbol = SymbolInfo(longString.ptr, "test.d", 0, cast(void*)0x100000);
611 result = formatLine(symbol, sbuf);
612 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');