Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
try to kill the singleton design pattern
[simgrid.git] / src / xbt / backtrace_windows.c
1 /* $Id$ */
2
3 /* backtrace_windows - backtrace displaying on windows platform             */
4 /* This file is included by ex.c on need (windows x86)                      */
5
6 /*  Copyright (c) 2007 The SimGrid team                                     */
7 /*  All rights reserved.                                                    */
8
9 /* This program is free software; you can redistribute it and/or modify it
10  * under the terms of the license (GNU LGPL) which comes with this package. */
11
12 /* 
13  * Win32 (x86) implementation backtrace, backtrace_symbols:
14  *  support for application self-debugging.
15  */
16
17 #include <dbghelp.h>
18
19
20 /* Pointer function to SymInitialize() */
21 BOOL(WINAPI * fun_initialize) (HANDLE, PSTR, BOOL);
22
23 /* Pointer function to SymCleanup() */
24 static BOOL(WINAPI * fun_cleanup) (HANDLE hProcess);
25
26 /* Pointer function to SymFunctionTableAccess() */
27 static PVOID(WINAPI * fun_function_table_access) (HANDLE, DWORD);
28
29 /* Pointer function to SymGetLineFromAddr() */
30 static BOOL(WINAPI * fun_get_line_from_addr) (HANDLE, DWORD,
31                                                 PDWORD,
32                                                 PIMAGEHLP_LINE);
33
34 /* Pointer function to SymGetModuleBase() */
35 static DWORD(WINAPI * fun_get_module_base) (HANDLE, DWORD);
36
37 /* Pointer function to SymGetOptions() */
38 static DWORD(WINAPI * fun_get_options) (VOID);
39
40 /* Pointer function to SymGetSymFromAddr() */
41 static BOOL(WINAPI * fun_get_sym_from_addr) (HANDLE, DWORD, PDWORD,
42                                                OUT PIMAGEHLP_SYMBOL);
43
44 /* Pointer function to SymSetOptions() */
45 static DWORD(WINAPI * fun_set_options) (DWORD);
46
47 /* Pointer function to StackWalk() */
48 static BOOL(WINAPI * xbt_pfn_stack_walk) (DWORD, HANDLE, HANDLE,
49                                             LPSTACKFRAME, PVOID,
50                                             PREAD_PROCESS_MEMORY_ROUTINE,
51                                             PFUNCTION_TABLE_ACCESS_ROUTINE,
52                                             PGET_MODULE_BASE_ROUTINE,
53                                             PTRANSLATE_ADDRESS_ROUTINE);
54
55 static HINSTANCE instance = NULL;
56 static HANDLE process_handle = NULL;
57
58
59 /* Module creation/destruction: nothing to do on linux */
60 void xbt_backtrace_init(void) { 
61   process_handle = GetCurrentProcess();
62
63   if (instance) {
64     /* debug help is already loaded */
65     return;
66   }
67
68   /* load the library */
69   instance = LoadLibraryA("Dbghelp.dll");
70
71   if (!instance)
72     return;
73  
74   /* get the pointers to debug help library exported functions */
75   fun_initialize = GetProcAddress(instance, "SymInitialize");
76   fun_cleanup = GetProcAddress(instance, "SymCleanup");
77   fun_function_table_access = GetProcAddress(instance, "SymFunctionTableAccess");
78   fun_get_line_from_addr = GetProcAddress(instance, "SymGetLineFromAddr");
79   fun_get_module_base = GetProcAddress(instance, "SymGetModuleBase");
80   fun_get_options = GetProcAddress(instance, "SymGetOptions");
81   fun_get_sym_from_addr = GetProcAddress(instance, "SymGetSymFromAddr");
82   fun_set_options = GetProcAddress(instance, "SymSetOptions");
83   fun_stack_walk = GetProcAddress(instance, "StackWalk");
84
85   /* Check that everything worked well */
86   if (!fun_initialize ||
87       !fun_cleanup ||
88       !fun_function_table_access || 
89       !fun_get_line_from_addr ||
90       !fun_get_module_base ||
91       !fun_get_options ||
92       !fun_get_sym_from_addr ||
93       !fun_set_options ||
94       !fun_stack_walk
95       ) {
96     FreeLibrary(instance);
97     instance = NULL;
98     return;
99   }
100
101   (*fun_set_options) ((*fun_get_options) () |
102                         SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS);
103
104   if (!(*fun_initialize) (process_handle, 0, 1)) {
105     FreeLibrary(instance);
106     instance = NULL;
107   }
108 }
109 void xbt_backtrace_exit(void) { 
110   if (!instance)
111     return;
112
113   if ((*fun_cleanup) (process_handle))
114     FreeLibrary(instance);
115
116   instance = NULL;
117 }
118
119 /*
120  * backtrace() function.
121  *
122  * Returns a backtrace for the calling program, in  the  array
123  * pointed  to  by  buffer.  A backtrace is the series of currently active
124  * function calls for the program.  Each item in the array pointed  to  by
125  * buffer  is  of  type  void *, and is the return address from the corre-
126  * sponding stack frame.  The size argument specifies the  maximum  number
127  * of  addresses that can be stored in buffer.  If the backtrace is larger
128  * than size, then the addresses corresponding to  the  size  most  recent
129  * function  calls  are  returned;  to obtain the complete backtrace, make
130  * sure that buffer and size are large enough.
131  */
132
133 int backtrace(void **buffer, int size);
134
135 /*
136  * backtrace_symbols() function.
137  *
138  * Given the set of addresses returned by  backtrace()  in  buffer,  back-
139  * trace_symbols()  translates the addresses into an array of strings containing
140  * the name, the source file and the line number or the las called functions.
141  */
142 char **backtrace_symbols(void *const *buffer, int size);
143
144 void xbt_ex_setup_backtrace(xbt_ex_t * e)
145 {
146   int i;
147   char **backtrace_syms = backtrace_symbols(e->bt, e->used);
148
149   e->used = backtrace((void **) e->bt, XBT_BACKTRACE_SIZE);
150   e->bt_strings = NULL;
151   /* parse the output and build a new backtrace */
152   e->bt_strings = xbt_new(char *, e->used);
153
154
155   for (i = 0; i < e->used; i++)
156     e->bt_strings[i] = backtrace_syms[i];
157
158   free(backtrace_syms);
159 }
160
161 int backtrace(void **buffer, int size)
162 {
163   int pos = 0;
164   STACKFRAME *stack_frame;
165   int first = 1;
166
167   IMAGEHLP_SYMBOL *pSym;
168   unsigned long offset = 0;
169   IMAGEHLP_LINE line_info = { 0 };
170   byte
171     __buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) +
172               sizeof(ULONG64) - 1) / sizeof(ULONG64)];
173
174   CONTEXT context = { CONTEXT_FULL };
175   GetThreadContext(GetCurrentThread(), &context);
176
177   /* ebp points on stack base */
178   /* esp points on stack pointer, ie on last stacked element (current element) */
179   _asm call $ + 5
180   _asm pop eax
181   _asm mov context.Eip, eax
182   _asm mov eax, esp
183   _asm mov context.Esp, eax
184   _asm mov context.Ebp, ebp 
185
186   if ((NULL == dbg_hlp) || (size <= 0) || (NULL == buffer)) {
187     errno = EINVAL;
188     return 0;
189   }
190
191   for (pos = 0; pos < size; pos++)
192     buffer[pos] = NULL;
193
194   pos = 0;
195
196   pSym = (IMAGEHLP_SYMBOL *) __buffer;
197
198   pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
199   pSym->MaxNameLength = MAX_SYM_NAME;
200
201
202   line_info.SizeOfStruct = sizeof(IMAGEHLP_LINE);
203
204
205   while (pos < size) {
206     stack_frame = (void *) xbt_new0(STACKFRAME, 1);
207
208     stack_frame->AddrPC.Offset = context.Eip;
209     stack_frame->AddrPC.Mode = AddrModeFlat;
210
211     stack_frame->AddrFrame.Offset = context.Ebp;
212     stack_frame->AddrFrame.Mode = AddrModeFlat;
213
214     stack_frame->AddrStack.Offset = context.Esp;
215     stack_frame->AddrStack.Mode = AddrModeFlat;
216
217     if ((*fun_stack_walk) (IMAGE_FILE_MACHINE_I386,
218                            process_handle,
219                            GetCurrentThread(),
220                            stack_frame,
221                            &context,
222                            NULL,
223                            fun_function_table_access,
224                            fun_get_module_base, NULL)
225         && !first) {
226       if (stack_frame->AddrReturn.Offset) {
227
228         if ((*fun_get_sym_from_addr) (process_handle, stack_frame->AddrPC.Offset, &offset, pSym)) {
229           if ((*fun_get_line_from_addr) (process_handle, stack_frame->AddrPC.Offset, &offset, &line_info))
230             buffer[pos++] = (void *) stack_frame;
231         }
232       } else {
233         free(stack_frame);      /* no symbol or no line info */
234         break;
235       }
236     } else {
237       free(stack_frame);
238
239       if (first)
240         first = 0;
241       else
242         break;
243     }
244   }
245
246   return pos;
247 }
248
249 char **backtrace_symbols(void *const *buffer, int size)
250 {
251   int pos;
252   int success = 0;
253   char **strings;
254   STACKFRAME *stack_frame;
255   IMAGEHLP_SYMBOL *pSym;
256   unsigned long offset = 0;
257   IMAGEHLP_LINE line_info = { 0 };
258   IMAGEHLP_MODULE module = { 0 };
259   byte
260     __buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) +
261               sizeof(ULONG64) - 1) / sizeof(ULONG64)];
262
263   if ((NULL == dbg_hlp) || (size <= 0) || (NULL == buffer)) {
264     errno = EINVAL;
265     return NULL;
266   }
267
268   strings = xbt_new0(char *, size);
269
270   pSym = (IMAGEHLP_SYMBOL *) __buffer;
271
272   pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
273   pSym->MaxNameLength = MAX_SYM_NAME;
274
275
276   line_info.SizeOfStruct = sizeof(IMAGEHLP_LINE);
277   module.SizeOfStruct = sizeof(IMAGEHLP_MODULE);
278
279   for (pos = 0; pos < size; pos++) {
280     stack_frame = (STACKFRAME *) (buffer[pos]);
281
282     if (NULL != stack_frame) {
283
284       if ((*fun_get_sym_from_addr) (process_handle, stack_frame->AddrPC.Offset, &offset, pSym)) {
285         if ((*fun_get_line_from_addr) (process_handle, stack_frame->AddrPC.Offset, &offset, &line_info)) {
286           strings[pos] =
287             bprintf("**   In %s() at %s:%d", pSym->Name, line_info.FileName,
288                     line_info.LineNumber);
289         } else {
290           strings[pos] = bprintf("**   In %s()", pSym->Name);
291         }
292         success = 1;
293       } else {
294         strings[pos] = xbt_strdup("**   <no symbol>");
295       }
296
297       free(stack_frame);
298     } else
299       break;
300   }
301
302   if (!success) {
303     free(strings);
304     strings = NULL;
305   }
306
307   return strings;
308 }