1 // GNU D Compiler routines for stack backtrace support.
2 // Copyright (C) 2013-2024 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;
27 // Max size per line of the traceback.
28 private enum MAX_BUFSIZE = 1536;
30 static if (BACKTRACE_SUPPORTED && !BACKTRACE_USES_MALLOC)
32 import core.stdc.stdint, core.stdc.string, core.stdc.stdio;
33 private enum MAXFRAMES = 128;
35 extern(C) int simpleCallback(void* data, uintptr_t pc)
37 auto context = cast(LibBacktrace)data;
39 if (context.numPCs == MAXFRAMES)
42 context.pcs[context.numPCs++] = pc;
47 * Used for backtrace_create_state and backtrace_simple
49 extern(C) void simpleErrorCallback(void* data, const(char)* msg, int errnum) @nogc
51 if (data) // context is not available in backtrace_create_state
53 auto context = cast(LibBacktrace)data;
54 strncpy(context.errorBuf.ptr, msg, context.errorBuf.length - 1);
55 context.error = errnum;
60 * Used for backtrace_pcinfo
62 extern(C) int pcinfoCallback(void* data, uintptr_t pc, const(char)* filename,
63 int lineno, const(char)* func)
65 auto context = cast(SymbolCallbackInfo*)data;
67 // Try to get the function name via backtrace_syminfo
70 SymbolCallbackInfo2 info;
72 info.filename = filename;
74 if (backtrace_syminfo(context.state, pc, &syminfoCallback2, null, &info) != 0)
76 return context.retval;
80 auto sym = SymbolOrError(0, SymbolInfo(func, filename, lineno, cast(void*)pc));
81 context.retval = context.applyCB(context.num, sym);
84 return context.retval;
88 * Used for backtrace_pcinfo and backtrace_syminfo
90 extern(C) void pcinfoErrorCallback(void* data, const(char)* msg, int errnum)
92 auto context = cast(SymbolCallbackInfo*)data;
96 context.noInfo = true;
100 SymbolOrError symError;
101 symError.errnum = errnum;
105 context.retval = context.applyCB(i, symError);
109 * Used for backtrace_syminfo (in opApply)
111 extern(C) void syminfoCallback(void* data, uintptr_t pc,
112 const(char)* symname, uintptr_t symval)
114 auto context = cast(SymbolCallbackInfo*)data;
116 auto sym = SymbolOrError(0, SymbolInfo(symname, null, 0, cast(void*)pc));
117 context.retval = context.applyCB(context.num, sym);
123 * This callback is used if backtrace_syminfo is called from the pcinfoCallback
124 * callback. It merges it's information with the information from pcinfoCallback.
126 extern(C) void syminfoCallback2(void* data, uintptr_t pc,
127 const(char)* symname, uintptr_t symval)
129 auto context = cast(SymbolCallbackInfo2*)data;
131 auto sym = SymbolOrError(0, SymbolInfo(symname, context.filename, context.lineno,
133 context.base.retval = context.base.applyCB(context.base.num, sym);
139 * The callback type used with the opApply overload which returns a SymbolOrError
141 private alias int delegate(ref size_t, ref SymbolOrError) ApplyCallback;
144 * Passed to syminfoCallback, pcinfoCallback and pcinfoErrorCallback
146 struct SymbolCallbackInfo
148 bool noInfo = false; // True if debug info / symbol table is not available
149 size_t num = 0; // Counter for opApply
150 int retval; // Value returned by applyCB
151 backtrace_state* state;
153 // info.fileName / funcName / errmsg may become invalid after this delegate returned
154 ApplyCallback applyCB;
164 * Passed to the syminfoCallback2 callback. That function merges it's
165 * funcName with this information and updates base as all other callbacks do.
167 struct SymbolCallbackInfo2
169 SymbolCallbackInfo* base;
170 const(char)* filename;
175 * Contains a valid symbol or an error message if errnum is != 0.
179 int errnum; // == 0: No error
187 // FIXME: state is never freed as libbacktrace doesn't provide a free function...
188 public class LibBacktrace : Throwable.TraceInfo
190 static void initLibBacktrace() @nogc
194 state = backtrace_create_state(null, false, &simpleErrorCallback, null);
199 this(int firstFrame) @nogc
201 _firstFrame = firstFrame;
207 backtrace_simple(state, _firstFrame, &simpleCallback,
208 &simpleErrorCallback, cast(void*)this);
212 override int opApply(scope int delegate(ref const(char[])) dg) const
215 (ref size_t, ref const(char[]) buf)
222 override int opApply(scope int delegate(ref size_t, ref const(char[])) dg) const
225 (ref size_t i, ref SymbolOrError sym)
227 char[MAX_BUFSIZE] buffer = void;
231 auto retval = snprintf(buffer.ptr, buffer.length,
232 "libbacktrace error: '%s' errno: %d", sym.msg, sym.errnum);
233 if (retval >= buffer.length)
234 retval = buffer.length - 1; // Ignore zero terminator
236 msg = buffer[0 .. retval];
241 msg = formatLine(sym.symbol, buffer);
242 int ret = dg(i, msg);
244 if (!ret && sym.symbol.funcName && strcmp(sym.symbol.funcName, "_Dmain") == 0)
252 int opApply(scope ApplyCallback dg) const
256 // If backtrace_simple produced an error report it and exit
257 if (!state || error != 0)
260 SymbolOrError symError;
263 symError.msg = "libbacktrace failed to initialize\0";
268 symError.errnum = error;
269 symError.msg = errorBuf.ptr;
272 return dg(pos, symError);
275 SymbolCallbackInfo cinfo;
277 cinfo.state = cast(backtrace_state*)state;
279 // Try using debug info first
280 foreach (i, pc; pcs[0 .. numPCs])
282 // FIXME: We may violate const guarantees here...
283 if (backtrace_pcinfo(cast(backtrace_state*)state, pc, &pcinfoCallback,
284 &pcinfoErrorCallback, &cinfo) != 0)
286 break; // User delegate requested abort or no debug info at all
290 // If no error or other error which has already been reported via callback
294 // Try using symbol table
296 foreach (pc; pcs[0 .. numPCs])
298 if (backtrace_syminfo(cast(backtrace_state*)state, pc, &syminfoCallback,
299 &pcinfoErrorCallback, &cinfo) == 0)
309 foreach (i, pc; pcs[0 .. numPCs])
311 auto sym = SymbolOrError(0, SymbolInfo(null, null, 0, cast(void*)pc));
312 if (auto ret = dg(i, sym) != 0)
319 override string toString() const
322 foreach (i, const(char[]) line; this)
323 buf ~= i ? "\n" ~ line : line;
328 static backtrace_state* state = null;
329 static bool initialized = false;
331 uintptr_t[MAXFRAMES] pcs;
335 char[128] errorBuf = "\0";
341 * Our fallback backtrace implementation using libgcc's unwind
342 * and backtrace support. In theory libbacktrace should be available
343 * everywhere where this code works. We keep it anyway till libbacktrace
346 public class UnwindBacktrace : Throwable.TraceInfo
348 this(int firstFrame) @nogc
350 _firstFrame = firstFrame;
351 _callstack = getBacktrace();
352 _framelist = getBacktraceSymbols(_callstack);
355 override int opApply(scope int delegate(ref const(char[])) dg) const
358 (ref size_t, ref const(char[]) buf)
365 override int opApply(scope int delegate(ref size_t, ref const(char[])) dg) const
367 char[MAX_BUFSIZE] buffer = void;
370 for (int i = _firstFrame; i < _framelist.entries; ++i)
372 auto pos = cast(size_t)(i - _firstFrame);
373 auto msg = formatLine(_framelist.symbols[i], buffer);
381 override string toString() const
384 foreach (i, line; this)
385 buf ~= i ? "\n" ~ line : line;
390 BTSymbolData _framelist;
391 UnwindBacktraceData _callstack;
395 // Implementation details
400 import core.sys.linux.dlfcn;
402 import core.sys.darwin.dlfcn;
403 else version (FreeBSD)
404 import core.sys.freebsd.dlfcn;
405 else version (NetBSD)
406 import core.sys.netbsd.dlfcn;
407 else version (OpenBSD)
408 import core.sys.openbsd.dlfcn;
409 else version (Solaris)
410 import core.sys.solaris.dlfcn;
412 import core.sys.posix.dlfcn;
414 private enum MAXFRAMES = 128;
416 struct UnwindBacktraceData
418 void*[MAXFRAMES] callstack;
425 SymbolInfo[MAXFRAMES] symbols;
428 static extern (C) _Unwind_Reason_Code unwindCB(_Unwind_Context *ctx, void *d)
430 UnwindBacktraceData* bt = cast(UnwindBacktraceData*)d;
431 if (bt.numframes >= MAXFRAMES)
432 return _URC_NO_REASON;
434 bt.callstack[bt.numframes] = cast(void*)_Unwind_GetIP(ctx);
436 return _URC_NO_REASON;
439 UnwindBacktraceData getBacktrace() @nogc
441 UnwindBacktraceData stackframe;
442 _Unwind_Backtrace(&unwindCB, &stackframe);
446 BTSymbolData getBacktraceSymbols(UnwindBacktraceData data) @nogc
448 BTSymbolData symData;
450 for (auto i = 0; i < data.numframes; i++)
452 static if ( __traits(compiles, Dl_info))
456 if (data.callstack[i] !is null && dladdr(data.callstack[i], &funcInfo) != 0)
458 symData.symbols[symData.entries].funcName = funcInfo.dli_sname;
460 symData.symbols[symData.entries].address = data.callstack[i];
465 symData.symbols[symData.entries].address = data.callstack[i];
471 symData.symbols[symData.entries].address = data.callstack[i];
481 * Struct representing a symbol (function) in the backtrace
485 const(char)* funcName, fileName;
487 const(void)* address;
491 * Format one output line for symbol sym.
492 * Returns a slice of buffer.
494 char[] formatLine(const SymbolInfo sym, return ref char[MAX_BUFSIZE] buffer)
496 import core.demangle, core.stdc.config;
497 import core.stdc.stdio : snprintf, printf;
498 import core.stdc.string : strlen;
500 size_t bufferLength = 0;
502 void appendToBuffer(Args...)(const(char)* format, Args args)
504 const count = snprintf(buffer.ptr + bufferLength,
505 buffer.length - bufferLength,
508 bufferLength += count;
509 if (bufferLength >= buffer.length)
510 bufferLength = buffer.length - 1;
514 if (sym.fileName is null)
515 appendToBuffer("??:? ");
517 appendToBuffer("%s:%d ", sym.fileName, sym.line);
519 if (sym.funcName is null)
520 appendToBuffer("???");
523 char[1024] symbol = void;
524 auto demangled = demangle(sym.funcName[0 .. strlen(sym.funcName)], symbol);
526 if (demangled.length > 0)
527 appendToBuffer("%.*s ", cast(int) demangled.length, demangled.ptr);
531 appendToBuffer("[0x%llx]", cast(size_t)sym.address);
533 appendToBuffer("[0x%x]", cast(size_t)sym.address);
535 return buffer[0 .. bufferLength];
541 char[MAX_BUFSIZE] sbuf = '\0';
544 for (size_t i = 0; i < 60; i++)
545 longString ~= "abcdefghij";
548 auto symbol = SymbolInfo(null, null, 0, null);
549 result = formatLine(symbol, sbuf);
550 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
552 symbol = SymbolInfo(longString.ptr, null, 0, null);
553 result = formatLine(symbol, sbuf);
554 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
556 symbol = SymbolInfo("func", "test.d", 0, null);
557 result = formatLine(symbol, sbuf);
558 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
560 symbol = SymbolInfo("func", longString.ptr, 0, null);
561 result = formatLine(symbol, sbuf);
562 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
564 symbol = SymbolInfo(longString.ptr, "test.d", 0, null);
565 result = formatLine(symbol, sbuf);
566 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
568 symbol = SymbolInfo(longString.ptr, longString.ptr, 0, null);
569 result = formatLine(symbol, sbuf);
570 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
572 symbol = SymbolInfo("func", "test.d", 1000, null);
573 result = formatLine(symbol, sbuf);
574 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
576 symbol = SymbolInfo(null, (longString[0..500] ~ '\0').ptr, 100000000, null);
577 result = formatLine(symbol, sbuf);
578 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
580 symbol = SymbolInfo("func", "test.d", 0, cast(void*)0x100000);
581 result = formatLine(symbol, sbuf);
582 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
584 symbol = SymbolInfo("func", null, 0, cast(void*)0x100000);
585 result = formatLine(symbol, sbuf);
586 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
588 symbol = SymbolInfo(null, "test.d", 0, cast(void*)0x100000);
589 result = formatLine(symbol, sbuf);
590 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');
592 symbol = SymbolInfo(longString.ptr, "test.d", 0, cast(void*)0x100000);
593 result = formatLine(symbol, sbuf);
594 assert(result.length < MAX_BUFSIZE && result.ptr[result.length] == '\0' && sbuf[$-1] == '\0');