Skip to content

Commit

Permalink
add simple backtrace support
Browse files Browse the repository at this point in the history
  • Loading branch information
jcosborn committed Feb 29, 2024
1 parent abce68c commit 8e0f3d1
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/base/backtrace.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
include system/ansi_c

{. pragma: execinfo, header:"execinfo.h" .}

proc backtrace(buffer: ptr pointer, size: cint): cint {.importc,execinfo.}
proc backtrace_symbols(buffer: ptr pointer, size: cint): ptr UncheckedArray[cstring]
{.importc,execinfo.}

proc print_trace =
#void *array[10];
const nmax = 10
var arr: array[nmax, pointer]
#char **strings;

let size = backtrace(addr arr[0], nmax)
let strings = backtrace_symbols(addr arr[0], size);
if not isNil strings:
echo "Stack trace of size: ", size
for i in 0..<size:
echo strings[i]
cfree strings

proc sigtrace(sig: cint) {.noconv.} =
print_trace()

proc setTrace* =
c_signal(SIGSEGV, sigtrace)

when isMainModule:
print_trace()
setTrace()
discard c_raise(SIGSEGV)

0 comments on commit 8e0f3d1

Please sign in to comment.