Logo AND Algorithmique Numérique Distribuée

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