Logo AND Algorithmique Numérique Distribuée

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