Logo AND Algorithmique Numérique Distribuée

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