Logo AND Algorithmique Numérique Distribuée

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