_________ __                 __
        /   _____//  |_____________ _/  |______     ____  __ __  ______
        \_____  \\   __\_  __ \__  \\   __\__  \   / ___\|  |  \/  ___/
        /        \|  |  |  | \// __ \|  |  / __ \_/ /_/  >  |  /\___ \
       /_______  /|__|  |__|  (____  /__| (____  /\___  /|____//____  >
               \/                  \/          \//_____/            \/
    ______________________                           ______________________
                          T H E   W A R   B E G I N S
                   Stratagus - A free fantasy real time strategy game engine

st_backtrace.h
Go to the documentation of this file.
1 #ifndef ST_BACKTRACE_H
2 #define ST_BACKTRACE_H 1
3 
4 #include "stdio.h"
5 
6 #ifdef __GLIBC__
7 
8 #include "execinfo.h"
9 inline void print_backtrace(int sz = 100) {
10  int j, nptrs;
11  void *buffer[sz];
12  nptrs = backtrace(buffer, sz);
13  fprintf(stderr, "backtrace() returned %d addresses\n", nptrs);
14  backtrace_symbols_fd(buffer, sz, 2);
15 }
16 
17 #elif defined(USE_WIN32)
18 
19 #include "windows.h"
20 #include "winbase.h"
21 #include "dbghelp.h"
22 #include "process.h"
23 
24 inline void print_backtrace(int sz = 100) {
25  unsigned int i;
26  void *stack[100];
27  unsigned short frames;
28  SYMBOL_INFO *symbol;
29  HANDLE process;
30  DWORD displacement;
31  IMAGEHLP_LINE64 *line;
32  char* name;
33 
34  process = GetCurrentProcess();
35  SymInitialize(process, NULL, TRUE);
36  frames = CaptureStackBackTrace(0, sz, stack, NULL);
37  fprintf(stderr, "backtrace returned %d addresses\n", frames);
38  symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + 1024 * sizeof(char), 1);
39  symbol->MaxNameLen = 1024;
40  symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
41 
42  line = (IMAGEHLP_LINE64 *)malloc(sizeof(IMAGEHLP_LINE64));
43  line->SizeOfStruct = sizeof(IMAGEHLP_LINE64);
44 
45  for(i = 0; i < frames; i++) {
46  SymFromAddr(process, (DWORD64)(stack[i]), 0, symbol);
47  if (symbol->Name) {
48  name = symbol->Name;
49  } else {
50  name = "<unknown frame>";
51  }
52  if (SymGetLineFromAddr64(process, (DWORD64)(stack[i]), &displacement, line)) {
53  fprintf(stderr, "%d: %s in %s:%d 0x%llx\n", frames - i - 1, name, line->FileName, line->LineNumber, symbol->Address);
54  } else {
55  fprintf(stderr, "%d: %s 0x%llx\n", frames - i - 1, name, symbol->Address);
56  }
57  }
58  free(symbol);
59 }
60 
61 #else
62 
63 inline void print_backtrace(int sz = 100) {
64 }
65 
66 #endif
67 
68 #endif
print_backtrace
void print_backtrace(int sz=100)
Definition: st_backtrace.h:24
(C) Copyright 1998-2012 by The Stratagus Project under the GNU General Public License.
All trademarks and copyrights on this page are owned by their respective owners.