Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
85b8b9927becb319c22251aaf58aad00790825f5
[simgrid.git] / src / xbt / backtrace_windows.c
1 /* $Id: ex.c 5173 2008-01-07 22:10:52Z mquinson $ */
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 /* Pointer function to SymInitialize() */
20 typedef BOOL(WINAPI * xbt_pfn_sym_initialize_t) (HANDLE, PSTR, BOOL);
21
22 /* Pointer function to SymCleanup() */
23 typedef BOOL(WINAPI * xbt_pfn_sym_cleanup_t) (HANDLE hProcess);
24
25 /* Pointer function to SymFunctionTableAccess() */
26 typedef PVOID(WINAPI * xbt_pfn_sym_function_table_access_t) (HANDLE, DWORD);
27
28 /* Pointer function to SymGetLineFromAddr() */
29 typedef BOOL(WINAPI * xbt_pfn_sym_get_line_from_addr_t) (HANDLE, DWORD,
30                                                          PDWORD,
31                                                          PIMAGEHLP_LINE);
32
33 /* Pointer function to SymGetModuleBase() */
34 typedef DWORD(WINAPI * xbt_pfn_sym_get_module_base_t) (HANDLE, DWORD);
35
36 /* Pointer function to SymGetOptions() */
37 typedef DWORD(WINAPI * xbt_pfn_sym_get_options_t) (VOID);
38
39 /* Pointer function to SymGetSymFromAddr() */
40 typedef BOOL(WINAPI * xbt_pfn_sym_get_sym_from_addr_t) (HANDLE, DWORD, PDWORD,
41                                                         OUT PIMAGEHLP_SYMBOL);
42
43 /* Pointer function to SymSetOptions() */
44 typedef DWORD(WINAPI * xbt_pfn_sym_set_options_t) (DWORD);
45
46 /* Pointer function to StackWalk() */
47 typedef BOOL(WINAPI * xbt_pfn_stack_walk_t) (DWORD, HANDLE, HANDLE,
48                                              LPSTACKFRAME, PVOID,
49                                              PREAD_PROCESS_MEMORY_ROUTINE,
50                                              PFUNCTION_TABLE_ACCESS_ROUTINE,
51                                              PGET_MODULE_BASE_ROUTINE,
52                                              PTRANSLATE_ADDRESS_ROUTINE);
53
54 /* This structure represents the debug_help library used interface */
55 typedef struct s_xbt_debug_help {
56   HINSTANCE instance;
57   HANDLE process_handle;
58   xbt_pfn_sym_initialize_t sym_initialize;
59   xbt_pfn_sym_cleanup_t sym_cleanup;
60   xbt_pfn_sym_function_table_access_t sym_function_table_access;
61   xbt_pfn_sym_get_line_from_addr_t sym_get_line_from_addr;
62   xbt_pfn_sym_get_module_base_t sym_get_module_base;
63   xbt_pfn_sym_get_options_t sym_get_options;
64   xbt_pfn_sym_get_sym_from_addr_t sym_get_sym_from_addr;
65   xbt_pfn_sym_set_options_t sym_set_options;
66   xbt_pfn_stack_walk_t stack_walk;
67 } s_xbt_debug_hlp_t, *xbt_debug_hlp_t;
68
69
70 /* the address to the unique reference to the debug help library interface */
71 static xbt_debug_hlp_t dbg_hlp = NULL;
72
73 /* initialize the debug help library */
74 static int dbg_hlp_init(HANDLE process_handle);
75
76 /* finalize the debug help library */
77 static int dbg_hlp_finalize(void);
78
79 /*
80  * backtrace() function.
81  *
82  * Returns a backtrace for the calling program, in  the  array
83  * pointed  to  by  buffer.  A backtrace is the series of currently active
84  * function calls for the program.  Each item in the array pointed  to  by
85  * buffer  is  of  type  void *, and is the return address from the corre-
86  * sponding stack frame.  The size argument specifies the  maximum  number
87  * of  addresses that can be stored in buffer.  If the backtrace is larger
88  * than size, then the addresses corresponding to  the  size  most  recent
89  * function  calls  are  returned;  to obtain the complete backtrace, make
90  * sure that buffer and size are large enough.
91  */
92
93 int backtrace(void **buffer, int size);
94
95 /*
96  * backtrace_symbols() function.
97  *
98  * Given the set of addresses returned by  backtrace()  in  buffer,  back-
99  * trace_symbols()  translates the addresses into an array of strings containing
100  * the name, the source file and the line number or the las called functions.
101  */
102 char **backtrace_symbols(void *const *buffer, int size);
103
104 void xbt_ex_setup_backtrace(xbt_ex_t * e)
105 {
106   int i;
107   char **backtrace_syms = backtrace_symbols(e->bt, e->used);
108
109   e->used = backtrace((void **) e->bt, XBT_BACKTRACE_SIZE);
110   e->bt_strings = NULL;
111   /* parse the output and build a new backtrace */
112   e->bt_strings = xbt_new(char *, e->used);
113
114
115   for (i = 0; i < e->used; i++) {
116     e->bt_strings[i] = xbt_strdup(backtrace_syms[i]);
117     free(backtrace_syms[i]);
118   }
119
120   free(backtrace_syms);
121 }
122
123 int backtrace(void **buffer, int size)
124 {
125   int pos = 0;
126   STACKFRAME *stack_frame;
127   int first = 1;
128
129   IMAGEHLP_SYMBOL *pSym;
130   unsigned long offset = 0;
131   IMAGEHLP_LINE line_info = { 0 };
132   byte
133     __buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) +
134               sizeof(ULONG64) - 1) / sizeof(ULONG64)];
135
136   CONTEXT context = { CONTEXT_FULL };
137   GetThreadContext(GetCurrentThread(), &context);
138
139   /* ebp points on stack base */
140   /* esp points on stack pointer, ie on last stacked element (current element) */
141   _asm call $ + 5
142   _asm pop eax
143   _asm mov context.Eip, eax
144   _asm mov eax, esp
145   _asm mov context.Esp, eax
146   _asm mov context.Ebp, ebp 
147
148   dbg_hlp_init(GetCurrentProcess());
149
150   if ((NULL == dbg_hlp) || (size <= 0) || (NULL == buffer)) {
151     errno = EINVAL;
152     return 0;
153   }
154
155   for (pos = 0; pos < size; pos++)
156     buffer[pos] = NULL;
157
158   pos = 0;
159
160   pSym = (IMAGEHLP_SYMBOL *) __buffer;
161
162   pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
163   pSym->MaxNameLength = MAX_SYM_NAME;
164
165
166   line_info.SizeOfStruct = sizeof(IMAGEHLP_LINE);
167
168
169   while (pos < size) {
170     stack_frame = (void *) xbt_new0(STACKFRAME, 1);
171
172     stack_frame->AddrPC.Offset = context.Eip;
173     stack_frame->AddrPC.Mode = AddrModeFlat;
174
175     stack_frame->AddrFrame.Offset = context.Ebp;
176     stack_frame->AddrFrame.Mode = AddrModeFlat;
177
178     stack_frame->AddrStack.Offset = context.Esp;
179     stack_frame->AddrStack.Mode = AddrModeFlat;
180
181     if ((*(dbg_hlp->stack_walk)) (IMAGE_FILE_MACHINE_I386,
182                                   dbg_hlp->process_handle,
183                                   GetCurrentThread(),
184                                   stack_frame,
185                                   &context,
186                                   NULL,
187                                   dbg_hlp->sym_function_table_access,
188                                   dbg_hlp->sym_get_module_base, NULL)
189         && !first) {
190       if (stack_frame->AddrReturn.Offset) {
191
192         if ((*(dbg_hlp->sym_get_sym_from_addr))
193             (dbg_hlp->process_handle, stack_frame->AddrPC.Offset, &offset,
194              pSym)) {
195           if ((*(dbg_hlp->sym_get_line_from_addr))
196               (dbg_hlp->process_handle, stack_frame->AddrPC.Offset, &offset,
197                &line_info))
198             buffer[pos++] = (void *) stack_frame;
199         }
200       } else {
201         free(stack_frame);      /* no symbol or no line info */
202         break;
203       }
204     } else {
205       free(stack_frame);
206
207       if (first)
208         first = 0;
209       else
210         break;
211     }
212   }
213
214   return pos;
215 }
216
217 char **backtrace_symbols(void *const *buffer, int size)
218 {
219   int pos;
220   int success = 0;
221   char **strings;
222   STACKFRAME *stack_frame;
223   IMAGEHLP_SYMBOL *pSym;
224   unsigned long offset = 0;
225   IMAGEHLP_LINE line_info = { 0 };
226   IMAGEHLP_MODULE module = { 0 };
227   byte
228     __buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) +
229               sizeof(ULONG64) - 1) / sizeof(ULONG64)];
230
231   if ((NULL == dbg_hlp) || (size <= 0) || (NULL == buffer)) {
232     errno = EINVAL;
233     return NULL;
234   }
235
236   strings = xbt_new0(char *, size);
237
238   pSym = (IMAGEHLP_SYMBOL *) __buffer;
239
240   pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
241   pSym->MaxNameLength = MAX_SYM_NAME;
242
243
244   line_info.SizeOfStruct = sizeof(IMAGEHLP_LINE);
245   module.SizeOfStruct = sizeof(IMAGEHLP_MODULE);
246
247   for (pos = 0; pos < size; pos++) {
248     stack_frame = (STACKFRAME *) (buffer[pos]);
249
250     if (NULL != stack_frame) {
251
252       if ((*(dbg_hlp->sym_get_sym_from_addr))
253           (dbg_hlp->process_handle, stack_frame->AddrPC.Offset, &offset,
254            pSym)) {
255         if ((*(dbg_hlp->sym_get_line_from_addr))
256             (dbg_hlp->process_handle, stack_frame->AddrPC.Offset, &offset,
257              &line_info)) {
258           strings[pos] =
259             bprintf("**   In %s() at %s:%d", pSym->Name, line_info.FileName,
260                     line_info.LineNumber);
261         } else {
262           strings[pos] = bprintf("**   In %s()", pSym->Name);
263         }
264         success = 1;
265       } else {
266         strings[pos] = xbt_strdup("**   <no symbol>");
267       }
268
269       free(stack_frame);
270     } else
271       break;
272   }
273
274   if (!success) {
275     free(strings);
276     strings = NULL;
277   }
278
279   dbg_hlp_finalize();
280
281   return strings;
282 }
283
284 static int dbg_hlp_init(HANDLE process_handle)
285 {
286   if (dbg_hlp) {
287     /* debug help is already loaded */
288     return 0;
289   }
290
291   /* allocation */
292   dbg_hlp = xbt_new0(s_xbt_debug_hlp_t, 1);
293
294   /* load the library */
295   dbg_hlp->instance = LoadLibraryA("Dbghelp.dll");
296
297   if (!(dbg_hlp->instance)) {
298     free(dbg_hlp);
299     dbg_hlp = NULL;
300     return (int) GetLastError();
301   }
302
303   /* get the pointers to debug help library exported functions */
304
305   if (!
306       ((dbg_hlp->sym_initialize) =
307        (xbt_pfn_sym_initialize_t) GetProcAddress(dbg_hlp->instance,
308                                                  "SymInitialize"))) {
309     FreeLibrary(dbg_hlp->instance);
310     free(dbg_hlp);
311     dbg_hlp = NULL;
312     return (int) GetLastError();
313   }
314
315   if (!
316       ((dbg_hlp->sym_cleanup) =
317        (xbt_pfn_sym_cleanup_t) GetProcAddress(dbg_hlp->instance,
318                                               "SymCleanup"))) {
319     FreeLibrary(dbg_hlp->instance);
320     free(dbg_hlp);
321     dbg_hlp = NULL;
322     return (int) GetLastError();
323   }
324
325   if (!
326       ((dbg_hlp->sym_function_table_access) =
327        (xbt_pfn_sym_function_table_access_t) GetProcAddress(dbg_hlp->instance,
328                                                             "SymFunctionTableAccess")))
329   {
330     FreeLibrary(dbg_hlp->instance);
331     free(dbg_hlp);
332     dbg_hlp = NULL;
333     return (int) GetLastError();
334   }
335
336   if (!
337       ((dbg_hlp->sym_get_line_from_addr) =
338        (xbt_pfn_sym_get_line_from_addr_t) GetProcAddress(dbg_hlp->instance,
339                                                          "SymGetLineFromAddr")))
340   {
341     FreeLibrary(dbg_hlp->instance);
342     free(dbg_hlp);
343     dbg_hlp = NULL;
344     return (int) GetLastError();
345   }
346
347   if (!
348       ((dbg_hlp->sym_get_module_base) =
349        (xbt_pfn_sym_get_module_base_t) GetProcAddress(dbg_hlp->instance,
350                                                       "SymGetModuleBase"))) {
351     FreeLibrary(dbg_hlp->instance);
352     free(dbg_hlp);
353     dbg_hlp = NULL;
354     return (int) GetLastError();
355   }
356
357   if (!
358       ((dbg_hlp->sym_get_options) =
359        (xbt_pfn_sym_get_options_t) GetProcAddress(dbg_hlp->instance,
360                                                   "SymGetOptions"))) {
361     FreeLibrary(dbg_hlp->instance);
362     free(dbg_hlp);
363     dbg_hlp = NULL;
364     return (int) GetLastError();
365   }
366
367   if (!
368       ((dbg_hlp->sym_get_sym_from_addr) =
369        (xbt_pfn_sym_get_sym_from_addr_t) GetProcAddress(dbg_hlp->instance,
370                                                         "SymGetSymFromAddr")))
371   {
372     FreeLibrary(dbg_hlp->instance);
373     free(dbg_hlp);
374     dbg_hlp = NULL;
375     return (int) GetLastError();
376   }
377
378   if (!
379       ((dbg_hlp->sym_set_options) =
380        (xbt_pfn_sym_set_options_t) GetProcAddress(dbg_hlp->instance,
381                                                   "SymSetOptions"))) {
382     FreeLibrary(dbg_hlp->instance);
383     free(dbg_hlp);
384     dbg_hlp = NULL;
385     return (int) GetLastError();
386   }
387
388   if (!
389       ((dbg_hlp->stack_walk) =
390        (xbt_pfn_stack_walk_t) GetProcAddress(dbg_hlp->instance,
391                                              "StackWalk"))) {
392     FreeLibrary(dbg_hlp->instance);
393     free(dbg_hlp);
394     dbg_hlp = NULL;
395     return (int) GetLastError();
396   }
397
398   dbg_hlp->process_handle = process_handle;
399
400   (*(dbg_hlp->sym_set_options)) ((*(dbg_hlp->sym_get_options)) () |
401                                  SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS);
402
403   if (!(*(dbg_hlp->sym_initialize)) (dbg_hlp->process_handle, 0, 1)) {
404     FreeLibrary(dbg_hlp->instance);
405     free(dbg_hlp);
406     dbg_hlp = NULL;
407     return (int) GetLastError();
408   }
409
410
411   return 0;
412 }
413
414 static int dbg_hlp_finalize(void)
415 {
416   if (!dbg_hlp)
417     return EINVAL;
418
419   if (!(*(dbg_hlp->sym_cleanup)) (dbg_hlp->process_handle))
420     return (int) GetLastError();
421
422   if (!FreeLibrary(dbg_hlp->instance))
423     return (int) GetLastError();
424
425   free(dbg_hlp);
426   dbg_hlp = NULL;
427
428   return 0;
429 }