Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
new function: remove a given element of the xbt_heap
[simgrid.git] / src / xbt / backtrace_linux.c
1 /* backtrace_linux - backtrace displaying on linux platform                 */
2 /* This file is included by ex.c on need (have execinfo.h, popen & addrline)*/
3
4 /* Copyright (c) 2008-2014. 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 /* This file is to be included in ex.c, so the following headers are not mandatory, but it's to make sure that eclipse see them too */
11 #include "xbt/ex.h"
12 #include "xbt/str.h"
13 #include "xbt/module.h"         /* xbt_binary_name */
14 #include "xbt_modinter.h"       /* backtrace initialization headers */
15 #ifdef HAVE_MC
16 #define UNW_LOCAL_ONLY
17 #include <libunwind.h>
18 #endif
19 /* end of "useless" inclusions */
20
21 extern char **environ;          /* the environment, as specified by the opengroup */
22
23 /* Module creation/destruction: nothing to do on linux */
24 void xbt_backtrace_preinit(void)
25 {
26 }
27
28 void xbt_backtrace_postexit(void)
29 {
30 }
31
32 #include <unwind.h>
33 struct trace_arg {
34   void **array;
35   int cnt, size;
36 };
37
38 static _Unwind_Reason_Code
39 backtrace_helper (struct _Unwind_Context *ctx, void *a)
40 {
41   struct trace_arg *arg = a;
42
43   /* We are first called with address in the __backtrace function.
44      Skip it.  */
45   if (arg->cnt != -1)
46     {
47       arg->array[arg->cnt] = (void *) _Unwind_GetIP(ctx);
48
49       /* Check whether we make any progress.  */
50       if (arg->cnt > 0 && arg->array[arg->cnt - 1] == arg->array[arg->cnt])
51         return _URC_END_OF_STACK;
52     }
53   if (++arg->cnt == arg->size)
54     return _URC_END_OF_STACK;
55   return _URC_NO_REASON;
56 }
57
58 /** @brief reimplementation of glibc backtrace based directly on gcc library, without implicit malloc
59  *
60  * See http://webloria.loria.fr/~quinson/blog/2012/0208/system_programming_fun_in_SimGrid/
61  * for the motivation behind this function
62  * */
63
64 int xbt_backtrace_no_malloc(void **array, int size) {
65
66   int i = 0;
67   for(i=0; i < size; i++)
68     array[i] = NULL;
69
70   struct trace_arg arg = { .array = array, .size = size, .cnt = -1 };
71
72   if (size >= 1)
73     _Unwind_Backtrace(backtrace_helper, &arg);
74
75   /* _Unwind_Backtrace on IA-64 seems to put NULL address above
76      _start.  Fix it up here.  */
77   if (arg.cnt > 1 && arg.array[arg.cnt - 1] == NULL)
78     --arg.cnt;
79   return arg.cnt != -1 ? arg.cnt : 0;
80 }
81
82 void xbt_backtrace_current(xbt_ex_t * e)
83 {
84   e->used = backtrace((void **) e->bt, XBT_BACKTRACE_SIZE);
85   if (e->used == 0) {
86     fprintf(stderr, "The backtrace() function failed, which probably means that the memory is exhausted. Here is a crude dump of the exception that I was trying to build:");
87     fprintf(stderr, "%s(%d) [%s:%d] %s",
88             e->procname, e->pid, e->file, e->line, e->msg);
89     fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory. Please go fix the memleaks\n");
90     exit(1);
91   }
92 }
93
94
95 void xbt_ex_setup_backtrace(xbt_ex_t * e) //FIXME: This code could be greatly improved/simplifyied with http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
96 {
97   int i;
98
99   /* to get the backtrace from the libc */
100   char **backtrace_syms;
101
102   /* To build the commandline of addr2line */
103   char *cmd, *curr;
104
105   /* to extract the addresses from the backtrace */
106   char **addrs;
107   char buff[256];
108
109   /* To read the output of addr2line */
110   FILE *pipe;
111   char line_func[1024], line_pos[1024];
112
113   /* size (in char) of pointers on this arch */
114   int addr_len = 0;
115
116   /* To search for the right executable path when not trivial */
117   struct stat stat_buf;
118   char *binary_name = NULL;
119
120   xbt_assert(e, "Backtrace not setup yet, cannot set it up for display");
121
122   e->bt_strings = NULL;
123
124   if (xbt_binary_name == NULL) /* no binary name, nothing to do */
125     return;
126
127   if (e->used <= 1)
128     return;
129
130   /* ignore first one, which is xbt_backtrace_current() */
131   e->used--;
132   memmove(e->bt, e->bt + 1, (sizeof *e->bt) * e->used);
133
134   backtrace_syms = backtrace_symbols(e->bt, e->used);
135
136   /* build the commandline */
137   if (stat(xbt_binary_name, &stat_buf)) {
138     /* Damn. binary not in current dir. We'll have to dig the PATH to find it */
139     for (i = 0; environ[i]; i++) {
140       if (!strncmp("PATH=", environ[i], 5)) {
141         xbt_dynar_t path = xbt_str_split(environ[i] + 5, ":");
142         unsigned int cpt;
143         char *data;
144
145         xbt_dynar_foreach(path, cpt, data) {
146           free(binary_name);
147           binary_name = bprintf("%s/%s", data, xbt_binary_name);
148           if (!stat(binary_name, &stat_buf)) {
149             /* Found. */
150             XBT_DEBUG("Looked in the PATH for the binary. Found %s",
151                    binary_name);
152             break;
153           }
154         }
155         xbt_dynar_free(&path);
156         if (stat(binary_name, &stat_buf)) {
157           /* not found */
158           e->used = 1;
159           e->bt_strings = xbt_new(char *, 1);
160
161           e->bt_strings[0] =
162               bprintf("(binary '%s' not found in the PATH)", xbt_binary_name);
163           free(backtrace_syms);
164           return;
165         }
166         break;
167       }
168     }
169   } else {
170     binary_name = xbt_strdup(xbt_binary_name);
171   }
172   cmd = curr =
173       xbt_new(char,
174               strlen(ADDR2LINE) + 25 + strlen(binary_name) + 32 * e->used);
175
176   curr += sprintf(curr, "%s -f -e %s ", ADDR2LINE, binary_name);
177   free(binary_name);
178
179   addrs = xbt_new(char *, e->used);
180   for (i = 0; i < e->used; i++) {
181     char *p;
182     /* retrieve this address */
183     XBT_DEBUG("Retrieving address number %d from '%s'", i, backtrace_syms[i]);
184     snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
185     p = strchr(buff, ']');
186     *p = '\0';
187     if (strcmp(buff, "(nil)"))
188       addrs[i] = xbt_strdup(buff);
189     else
190       addrs[i] = xbt_strdup("0x0");
191     XBT_DEBUG("Set up a new address: %d, '%s'(%p)", i, addrs[i], addrs[i]);
192
193     /* Add it to the command line args */
194     curr += sprintf(curr, "%s ", addrs[i]);
195   }
196   addr_len = strlen(addrs[0]);
197
198   /* parse the output and build a new backtrace */
199   e->bt_strings = xbt_new(char *, e->used);
200
201   XBT_VERB("Fire a first command: '%s'", cmd);
202   pipe = popen(cmd, "r");
203   if (!pipe) {
204     xbt_die("Cannot fork addr2line to display the backtrace");
205   }
206
207   for (i = 0; i < e->used; i++) {
208     XBT_DEBUG("Looking for symbol %d, addr = '%s'", i, addrs[i]);
209     if (fgets(line_func, 1024, pipe)) {
210       line_func[strlen(line_func) - 1] = '\0';
211     } else {
212       XBT_VERB("Cannot run fgets to look for symbol %d, addr %s", i, addrs[i]);
213       strcpy(line_func, "???");
214     }
215     if (fgets(line_pos, 1024, pipe)) {
216       line_pos[strlen(line_pos) - 1] = '\0';
217     } else {
218       XBT_VERB("Cannot run fgets to look for symbol %d, addr %s", i, addrs[i]);
219       strcpy(line_pos, backtrace_syms[i]);
220     }
221
222     if (strcmp("??", line_func) != 0) {
223       XBT_DEBUG("Found static symbol %s() at %s", line_func, line_pos);
224       e->bt_strings[i] =
225           bprintf("**   In %s() at %s", line_func, line_pos);
226     } else {
227       /* Damn. The symbol is in a dynamic library. Let's get wild */
228       char *maps_name;
229       FILE *maps;
230       char maps_buff[512];
231
232       long int addr, offset = 0;
233       char *p, *p2;
234
235       char *subcmd;
236       FILE *subpipe;
237       int found = 0;
238
239       /* let's look for the offset of this library in our addressing space */
240       maps_name = bprintf("/proc/%d/maps", (int) getpid());
241       maps = fopen(maps_name, "r");
242
243       addr = strtol(addrs[i], &p, 16);
244       if (*p != '\0') {
245         XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)",
246                   addrs[i], addr);
247       }
248       XBT_DEBUG("addr=%s (as string) =%#lx (as number)", addrs[i], addr);
249
250       while (!found) {
251         long int first, last;
252
253         if (fgets(maps_buff, 512, maps) == NULL)
254           break;
255         if (i == 0) {
256           maps_buff[strlen(maps_buff) - 1] = '\0';
257           XBT_DEBUG("map line: %s", maps_buff);
258         }
259         sscanf(maps_buff, "%lx", &first);
260         p = strchr(maps_buff, '-') + 1;
261         sscanf(p, "%lx", &last);
262         if (first < addr && addr < last) {
263           offset = first;
264           found = 1;
265         }
266         if (found) {
267           XBT_DEBUG("%#lx in [%#lx-%#lx]", addr, first, last);
268           XBT_DEBUG
269               ("Symbol found, map lines not further displayed (even if looking for next ones)");
270         }
271       }
272       fclose(maps);
273       free(maps_name);
274       free(addrs[i]);
275
276       if (!found) {
277         XBT_VERB
278             ("Problem while reading the maps file. Following backtrace will be mangled.");
279         XBT_DEBUG("No dynamic. Static symbol: %s", backtrace_syms[i]);
280         e->bt_strings[i] = bprintf("**   In ?? (%s)", backtrace_syms[i]);
281         continue;
282       }
283
284       /* Ok, Found the offset of the maps line containing the searched symbol.
285          We now need to substract this from the address we got from backtrace.
286        */
287
288       addrs[i] = bprintf("0x%0*lx", addr_len - 2, addr - offset);
289       XBT_DEBUG("offset=%#lx new addr=%s", offset, addrs[i]);
290
291       /* Got it. We have our new address. Let's get the library path and we
292          are set */
293       p = xbt_strdup(backtrace_syms[i]);
294       if (p[0] == '[') {
295         /* library path not displayed in the map file either... */
296         free(p);
297         sprintf(line_func, "??");
298       } else {
299         p2 = strrchr(p, '(');
300         if (p2)
301           *p2 = '\0';
302         p2 = strrchr(p, ' ');
303         if (p2)
304           *p2 = '\0';
305
306         /* Here we go, fire an addr2line up */
307         subcmd = bprintf("%s -f -e %s %s", ADDR2LINE, p, addrs[i]);
308         free(p);
309         XBT_VERB("Fire a new command: '%s'", subcmd);
310         subpipe = popen(subcmd, "r");
311         if (!subpipe) {
312           xbt_die("Cannot fork addr2line to display the backtrace");
313         }
314         if (fgets(line_func, 1024, subpipe)) {
315           line_func[strlen(line_func) - 1] = '\0';
316         } else {
317           XBT_VERB("Cannot read result of subcommand %s", subcmd);
318           strcpy(line_func, "???");
319         }
320         if (fgets(line_pos, 1024, subpipe)) {
321           line_pos[strlen(line_pos) - 1] = '\0';
322         } else {
323           XBT_VERB("Cannot read result of subcommand %s", subcmd);
324           strcpy(line_pos, backtrace_syms[i]);
325         }
326         pclose(subpipe);
327         free(subcmd);
328       }
329
330       /* check whether the trick worked */
331       if (strcmp("??", line_func)) {
332         XBT_DEBUG("Found dynamic symbol %s() at %s", line_func, line_pos);
333         e->bt_strings[i] =
334             bprintf("**   In %s() at %s", line_func, line_pos);
335       } else {
336         /* damn, nothing to do here. Let's print the raw address */
337         XBT_DEBUG("Dynamic symbol not found. Raw address = %s",
338                backtrace_syms[i]);
339         e->bt_strings[i] = bprintf("**   In ?? at %s", backtrace_syms[i]);
340       }
341
342     }
343     free(addrs[i]);
344
345     /* Mask the bottom of the stack */
346     if (!strncmp("main", line_func, strlen("main")) ||
347         !strncmp("xbt_thread_context_wrapper", line_func,
348                  strlen("xbt_thread_context_wrapper"))
349         || !strncmp("smx_ctx_sysv_wrapper", line_func,
350                     strlen("smx_ctx_sysv_wrapper"))) {
351       int j;
352
353       for (j = i + 1; j < e->used; j++)
354         free(addrs[j]);
355       e->used = i + 1;
356
357       if (!strncmp
358           ("xbt_thread_context_wrapper", line_func,
359            strlen("xbt_thread_context_wrapper"))) {
360         free(e->bt_strings[i]);
361         e->bt_strings[i] = xbt_strdup("**   (in a separate thread)");
362       }
363     }
364
365
366   }
367   pclose(pipe);
368   free(addrs);
369   free(backtrace_syms);
370   free(cmd);
371 }
372
373 #ifdef HAVE_MC
374
375 int xbt_libunwind_backtrace(void* bt[XBT_BACKTRACE_SIZE], int size){
376   
377   int i = 0;
378   for(i=0; i < size; i++)
379     bt[i] = NULL;
380
381   i=0;
382
383   unw_cursor_t c;
384   unw_context_t uc;
385
386   unw_getcontext (&uc);
387         unw_init_local (&c, &uc);
388  
389   unw_word_t ip;
390
391   unw_step(&c);
392  
393   while(unw_step(&c) >= 0 && i < size){
394
395     unw_get_reg(&c, UNW_REG_IP, &ip);
396     bt[i] = (void*)(long)ip;
397     i++;
398
399   }
400
401   return i;
402   
403 }
404
405 #endif