Logo AND Algorithmique Numérique Distribuée

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