Logo AND Algorithmique Numérique Distribuée

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