Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
00ab8f96c4ff2f80f8c6d3f514a4208ae7b5d8ed
[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_ex_setup_backtrace(xbt_ex_t * e)
169 {
170   int i;
171   char **backtrace_syms = backtrace_symbols(e->bt, e->used);
172
173   e->used = backtrace((void **) e->bt, XBT_BACKTRACE_SIZE);
174   e->bt_strings = NULL;
175   /* parse the output and build a new backtrace */
176   e->bt_strings = xbt_new(char *, e->used);
177
178
179   for (i = 0; i < e->used; i++)
180     e->bt_strings[i] = backtrace_syms[i];
181
182   free(backtrace_syms);
183 }
184
185 int backtrace(void **buffer, int size)
186 {
187   int pos = 0;
188   STACKFRAME *stack_frame;
189   int first = 1;
190
191   IMAGEHLP_SYMBOL *pSym;
192   unsigned long offset = 0;
193   IMAGEHLP_LINE line_info = { 0 };
194   byte
195     __buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) +
196               sizeof(ULONG64) - 1) / sizeof(ULONG64)];
197
198   CONTEXT context = { CONTEXT_FULL };
199   GetThreadContext(GetCurrentThread(), &context);
200
201   /* ebp points on stack base */
202   /* esp points on stack pointer, ie on last stacked element (current element) */
203   _asm call $ + 5
204   _asm pop eax
205   _asm mov context.Eip, eax
206   _asm mov eax, esp
207   _asm mov context.Esp, eax
208   _asm mov context.Ebp, ebp
209      
210   if ((NULL == hlp_dbg_instance) || (size <= 0) || (NULL == buffer)) {
211     errno = EINVAL;
212     return 0;
213   }
214
215   for (pos = 0; pos < size; pos++)
216     buffer[pos] = NULL;
217
218   pos = 0;
219
220   pSym = (IMAGEHLP_SYMBOL *) __buffer;
221
222   pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
223   pSym->MaxNameLength = MAX_SYM_NAME;
224
225
226   line_info.SizeOfStruct = sizeof(IMAGEHLP_LINE);
227
228
229   while (pos < size) {
230     stack_frame = (void *) xbt_new0(STACKFRAME, 1);
231
232     stack_frame->AddrPC.Offset = context.Eip;
233     stack_frame->AddrPC.Mode = AddrModeFlat;
234
235     stack_frame->AddrFrame.Offset = context.Ebp;
236     stack_frame->AddrFrame.Mode = AddrModeFlat;
237
238     stack_frame->AddrStack.Offset = context.Esp;
239     stack_frame->AddrStack.Mode = AddrModeFlat;
240
241     if ((*fun_stack_walk) (IMAGE_FILE_MACHINE_I386,
242                            process_handle,
243                            GetCurrentThread(),
244                            stack_frame,
245                            &context,
246                            NULL,
247                            fun_function_table_access,
248                            fun_get_module_base, NULL)
249         && !first) {
250       if (stack_frame->AddrReturn.Offset) {
251
252         if ((*fun_get_sym_from_addr) (process_handle, stack_frame->AddrPC.Offset, &offset, pSym)) {
253           if ((*fun_get_line_from_addr) (process_handle, stack_frame->AddrPC.Offset, &offset, &line_info))
254             buffer[pos++] = (void *) stack_frame;
255         }
256       } else {
257         free(stack_frame);      /* no symbol or no line info */
258         break;
259       }
260     } else {
261       free(stack_frame);
262
263       if (first)
264         first = 0;
265       else
266         break;
267     }
268   }
269
270   return pos;
271 }
272
273 char **backtrace_symbols(void *const *buffer, int size)
274 {
275   int pos;
276   int success = 0;
277   char **strings;
278   STACKFRAME *stack_frame;
279   IMAGEHLP_SYMBOL *pSym;
280   unsigned long offset = 0;
281   IMAGEHLP_LINE line_info = { 0 };
282   IMAGEHLP_MODULE module = { 0 };
283   byte
284     __buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) +
285               sizeof(ULONG64) - 1) / sizeof(ULONG64)];
286
287   if ((NULL == hlp_dbg_instance) || (size <= 0) || (NULL == buffer)) {
288     errno = EINVAL;
289     return NULL;
290   }
291
292   strings = xbt_new0(char *, size);
293
294   pSym = (IMAGEHLP_SYMBOL *) __buffer;
295
296   pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
297   pSym->MaxNameLength = MAX_SYM_NAME;
298
299
300   line_info.SizeOfStruct = sizeof(IMAGEHLP_LINE);
301   module.SizeOfStruct = sizeof(IMAGEHLP_MODULE);
302
303   for (pos = 0; pos < size; pos++) {
304     stack_frame = (STACKFRAME *) (buffer[pos]);
305
306     if (NULL != stack_frame) {
307
308       if ((*fun_get_sym_from_addr) (process_handle, stack_frame->AddrPC.Offset, &offset, pSym)) {
309         if ((*fun_get_line_from_addr) (process_handle, stack_frame->AddrPC.Offset, &offset, &line_info)) {
310           strings[pos] =
311             bprintf("**   In %s() at %s:%d", pSym->Name, line_info.FileName,
312                     (int)line_info.LineNumber);
313         } else {
314           strings[pos] = bprintf("**   In %s()", pSym->Name);
315         }
316         success = 1;
317       } else {
318         strings[pos] = xbt_strdup("**   <no symbol>");
319       }
320
321       free(stack_frame);
322     } else
323       break;
324   }
325
326   if (!success) {
327     free(strings);
328     strings = NULL;
329   }
330
331   return strings;
332 }