Logo AND Algorithmique Numérique Distribuée

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