Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
46c842a93912a01e2380e1bd9e4023f96af3785e
[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     if (!stack_frame) {
173       errno = ENOMEM;
174       break;
175     }
176
177     stack_frame->AddrPC.Offset = context.Eip;
178     stack_frame->AddrPC.Mode = AddrModeFlat;
179
180     stack_frame->AddrFrame.Offset = context.Ebp;
181     stack_frame->AddrFrame.Mode = AddrModeFlat;
182
183     stack_frame->AddrStack.Offset = context.Esp;
184     stack_frame->AddrStack.Mode = AddrModeFlat;
185
186     if ((*(dbg_hlp->stack_walk)) (IMAGE_FILE_MACHINE_I386,
187                                   dbg_hlp->process_handle,
188                                   GetCurrentThread(),
189                                   stack_frame,
190                                   &context,
191                                   NULL,
192                                   dbg_hlp->sym_function_table_access,
193                                   dbg_hlp->sym_get_module_base, NULL)
194         && !first) {
195       if (stack_frame->AddrReturn.Offset) {
196
197         if ((*(dbg_hlp->sym_get_sym_from_addr))
198             (dbg_hlp->process_handle, stack_frame->AddrPC.Offset, &offset,
199              pSym)) {
200           if ((*(dbg_hlp->sym_get_line_from_addr))
201               (dbg_hlp->process_handle, stack_frame->AddrPC.Offset, &offset,
202                &line_info))
203             buffer[pos++] = (void *) stack_frame;
204         }
205       } else {
206         free(stack_frame);      /* no symbol or no line info */
207         break;
208       }
209     } else {
210       free(stack_frame);
211
212       if (first)
213         first = 0;
214       else
215         break;
216     }
217   }
218
219   return pos;
220 }
221
222 char **backtrace_symbols(void *const *buffer, int size)
223 {
224   int pos;
225   int success = 0;
226   char **strings;
227   STACKFRAME *stack_frame;
228   IMAGEHLP_SYMBOL *pSym;
229   unsigned long offset = 0;
230   IMAGEHLP_LINE line_info = { 0 };
231   IMAGEHLP_MODULE module = { 0 };
232   byte
233     __buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) +
234               sizeof(ULONG64) - 1) / sizeof(ULONG64)];
235
236   if ((NULL == dbg_hlp) || (size <= 0) || (NULL == buffer)) {
237     errno = EINVAL;
238     return NULL;
239   }
240
241   strings = xbt_new0(char *, size);
242
243   if (NULL == strings) {
244     errno = ENOMEM;
245     return NULL;
246   }
247
248   pSym = (IMAGEHLP_SYMBOL *) __buffer;
249
250   pSym->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
251   pSym->MaxNameLength = MAX_SYM_NAME;
252
253
254   line_info.SizeOfStruct = sizeof(IMAGEHLP_LINE);
255   module.SizeOfStruct = sizeof(IMAGEHLP_MODULE);
256
257   for (pos = 0; pos < size; pos++) {
258     stack_frame = (STACKFRAME *) (buffer[pos]);
259
260     if (NULL != stack_frame) {
261
262       if ((*(dbg_hlp->sym_get_sym_from_addr))
263           (dbg_hlp->process_handle, stack_frame->AddrPC.Offset, &offset,
264            pSym)) {
265         if ((*(dbg_hlp->sym_get_line_from_addr))
266             (dbg_hlp->process_handle, stack_frame->AddrPC.Offset, &offset,
267              &line_info)) {
268           strings[pos] =
269             bprintf("**   In %s() at %s:%d", pSym->Name, line_info.FileName,
270                     line_info.LineNumber);
271         } else {
272           strings[pos] = bprintf("**   In %s()", pSym->Name);
273         }
274         success = 1;
275       } else {
276         strings[pos] = xbt_strdup("**   <no symbol>");
277       }
278
279       free(stack_frame);
280     } else
281       break;
282   }
283
284   if (!success) {
285     free(strings);
286     strings = NULL;
287   }
288
289   dbg_hlp_finalize();
290
291   return strings;
292 }
293
294 static int dbg_hlp_init(HANDLE process_handle)
295 {
296   if (dbg_hlp) {
297     /* debug help is already loaded */
298     return 0;
299   }
300
301   /* allocation */
302   dbg_hlp = xbt_new0(s_xbt_debug_hlp_t, 1);
303
304   if (!dbg_hlp)
305     return ENOMEM;
306
307   /* load the library */
308   dbg_hlp->instance = LoadLibraryA("Dbghelp.dll");
309
310   if (!(dbg_hlp->instance)) {
311     free(dbg_hlp);
312     dbg_hlp = NULL;
313     return (int) GetLastError();
314   }
315
316   /* get the pointers to debug help library exported functions */
317
318   if (!
319       ((dbg_hlp->sym_initialize) =
320        (xbt_pfn_sym_initialize_t) GetProcAddress(dbg_hlp->instance,
321                                                  "SymInitialize"))) {
322     FreeLibrary(dbg_hlp->instance);
323     free(dbg_hlp);
324     dbg_hlp = NULL;
325     return (int) GetLastError();
326   }
327
328   if (!
329       ((dbg_hlp->sym_cleanup) =
330        (xbt_pfn_sym_cleanup_t) GetProcAddress(dbg_hlp->instance,
331                                               "SymCleanup"))) {
332     FreeLibrary(dbg_hlp->instance);
333     free(dbg_hlp);
334     dbg_hlp = NULL;
335     return (int) GetLastError();
336   }
337
338   if (!
339       ((dbg_hlp->sym_function_table_access) =
340        (xbt_pfn_sym_function_table_access_t) GetProcAddress(dbg_hlp->instance,
341                                                             "SymFunctionTableAccess")))
342   {
343     FreeLibrary(dbg_hlp->instance);
344     free(dbg_hlp);
345     dbg_hlp = NULL;
346     return (int) GetLastError();
347   }
348
349   if (!
350       ((dbg_hlp->sym_get_line_from_addr) =
351        (xbt_pfn_sym_get_line_from_addr_t) GetProcAddress(dbg_hlp->instance,
352                                                          "SymGetLineFromAddr")))
353   {
354     FreeLibrary(dbg_hlp->instance);
355     free(dbg_hlp);
356     dbg_hlp = NULL;
357     return (int) GetLastError();
358   }
359
360   if (!
361       ((dbg_hlp->sym_get_module_base) =
362        (xbt_pfn_sym_get_module_base_t) GetProcAddress(dbg_hlp->instance,
363                                                       "SymGetModuleBase"))) {
364     FreeLibrary(dbg_hlp->instance);
365     free(dbg_hlp);
366     dbg_hlp = NULL;
367     return (int) GetLastError();
368   }
369
370   if (!
371       ((dbg_hlp->sym_get_options) =
372        (xbt_pfn_sym_get_options_t) GetProcAddress(dbg_hlp->instance,
373                                                   "SymGetOptions"))) {
374     FreeLibrary(dbg_hlp->instance);
375     free(dbg_hlp);
376     dbg_hlp = NULL;
377     return (int) GetLastError();
378   }
379
380   if (!
381       ((dbg_hlp->sym_get_sym_from_addr) =
382        (xbt_pfn_sym_get_sym_from_addr_t) GetProcAddress(dbg_hlp->instance,
383                                                         "SymGetSymFromAddr")))
384   {
385     FreeLibrary(dbg_hlp->instance);
386     free(dbg_hlp);
387     dbg_hlp = NULL;
388     return (int) GetLastError();
389   }
390
391   if (!
392       ((dbg_hlp->sym_set_options) =
393        (xbt_pfn_sym_set_options_t) GetProcAddress(dbg_hlp->instance,
394                                                   "SymSetOptions"))) {
395     FreeLibrary(dbg_hlp->instance);
396     free(dbg_hlp);
397     dbg_hlp = NULL;
398     return (int) GetLastError();
399   }
400
401   if (!
402       ((dbg_hlp->stack_walk) =
403        (xbt_pfn_stack_walk_t) GetProcAddress(dbg_hlp->instance,
404                                              "StackWalk"))) {
405     FreeLibrary(dbg_hlp->instance);
406     free(dbg_hlp);
407     dbg_hlp = NULL;
408     return (int) GetLastError();
409   }
410
411   dbg_hlp->process_handle = process_handle;
412
413   (*(dbg_hlp->sym_set_options)) ((*(dbg_hlp->sym_get_options)) () |
414                                  SYMOPT_LOAD_LINES | SYMOPT_DEFERRED_LOADS);
415
416   if (!(*(dbg_hlp->sym_initialize)) (dbg_hlp->process_handle, 0, 1)) {
417     FreeLibrary(dbg_hlp->instance);
418     free(dbg_hlp);
419     dbg_hlp = NULL;
420     return (int) GetLastError();
421   }
422
423
424   return 0;
425 }
426
427 static int dbg_hlp_finalize(void)
428 {
429   if (!dbg_hlp)
430     return EINVAL;
431
432   if (!(*(dbg_hlp->sym_cleanup)) (dbg_hlp->process_handle))
433     return (int) GetLastError();
434
435   if (!FreeLibrary(dbg_hlp->instance))
436     return (int) GetLastError();
437
438   free(dbg_hlp);
439   dbg_hlp = NULL;
440
441   return 0;
442 }