File: backtrace.h

package info (click to toggle)
xstow 1.0.2-1
  • links: PTS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 1,064 kB
  • ctags: 1,073
  • sloc: cpp: 7,264; sh: 1,216; makefile: 196; awk: 26
file content (132 lines) | stat: -rw-r--r-- 2,098 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*
 * $Log: backtrace.h,v $
 * Revision 1.2  2005/07/04 21:59:42  martin
 * added logging to all files
 *
 */
#ifndef BACKTRACE_H
#define BACKTRACE_H

#include <list>
#include <string>
#include <ostream>
#include "format.h"

class BackTrace
{
private:
    struct Ticket
    {
	int ticket;
	std::string message;
	std::string info;

	Ticket( int t, const std::string &m ) : ticket( t ), message( m ) {}
    };

    std::list<Ticket> stack;
    typedef std::list<Ticket>::iterator it_t;
    typedef std::list<Ticket>::reverse_iterator rit_t;
    int count;
    
public:
    BackTrace() : count( 0 ) {}


    int push( const std::string & message )
	{
	    count++;
	    stack.push_back( Ticket( count, message ) );
	    return count;
	}
    
    void pop( int ticket )
	{
	    if( stack.empty() )
		return;

	    it_t it = stack.end();
	    it--;

	    while( it != stack.end() )
	    {
		if( it->ticket == ticket )
		{
		    stack.erase( it );
		    break;
		} else {		   
		    stack.erase( it );
		    it = stack.end();

		    if( stack.empty() )
			return;

		    it--;
		}
	    }
	}

    void bt( std::ostream &out )
	{
	    for( it_t it = stack.begin(); it != stack.end(); it++ )
	    {
		out << it->ticket << ':' << it->message << ": " << it->info << '\n';
	    }
	}

    std::string bt()
	{
	    std::stringstream out;
	    bt( out );
	    return out.str();
	}


    void add_info( int ticket, const std::string &info )
	{
	    if( stack.empty() )
		return;

	    for( rit_t it = stack.rbegin(); it != stack.rend(); it++ )
	    {
		if( it->ticket == ticket )
		{
		    it->info += info;
		    return;
		}
	    }
	}
};

class BackTraceHelper
{
private:
    int ticket;

public:
    static BackTrace bt;

public:
    BackTraceHelper( const std::string &func_name )
	{
	    ticket = bt.push( func_name );
	}

    ~BackTraceHelper()
	{
	    bt.pop( ticket );
	}

    void add_info( const std::string &info )
	{
	    bt.add_info( ticket, info );
	}
};

#ifndef NDEBUG
#define BT \
  BackTraceHelper bt( format( "%s:%d:%s", __FILE__, __LINE__, __PRETTY_FUNCTION__ ) )
#else
#define BT
#endif
#endif