Logo AND Algorithmique Numérique Distribuée

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