]> git.tdb.fi Git - libs/core.git/blob - source/debug/backtrace.cpp
Improve BackTrace printing
[libs/core.git] / source / debug / backtrace.cpp
1 /* $Id$
2
3 This file is part of libmspcore
4 Copyright © 2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 // Must include something to test for glibc
9 #include <cstdlib>
10 #if !defined(WIN32) && defined(__GLIBC__)
11 #include <dlfcn.h>
12 #include <execinfo.h>
13 #endif
14 #include "backtrace.h"
15 #include "demangle.h"
16
17 using namespace std;
18
19 namespace Msp {
20 namespace Debug {
21
22 Backtrace Backtrace::create()
23 {
24 #if !defined(WIN32) && defined(__GLIBC__)
25         void *addresses[50];
26         int count=::backtrace(addresses, 50);
27
28         Backtrace bt;
29         Dl_info dli;
30         for(int i=0; i<count; ++i)
31         {
32                 StackFrame frame;
33                 frame.address=addresses[i];
34                 if(dladdr(addresses[i], &dli))
35                 {
36                         frame.file=dli.dli_fname;
37                         if(dli.dli_sname)
38                                 frame.symbol=demangle(dli.dli_sname);
39                 }
40                 else
41                         frame.file="<unknown>";
42                 bt.frames.push_back(frame);
43         }
44
45         return bt;
46 #else
47         return Backtrace();
48 #endif
49 }
50
51 ostream &operator<<(ostream &out, const Backtrace &bt)
52 {
53         const Backtrace::FrameSeq &frames=bt.get_frames();
54         for(Backtrace::FrameSeq::const_iterator i=frames.begin(); i!=frames.end(); ++i)
55                 out<<*i<<'\n';
56
57         return out;
58 }
59
60 ostream &operator<<(ostream &out, const Backtrace::StackFrame &sf)
61 {
62         out<<sf.address;
63         if(!sf.symbol.empty())
64                 out<<" in "<<sf.symbol;
65         out<<" from "<<sf.file;
66
67         return out;
68 }
69
70 } // namespace Debug
71 } // namespace Msp