Logo AND Algorithmique Numérique Distribuée

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