Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
mask bottom of stacks when using sysv ctx
[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, addrs[i]);
155     line_func[strlen(line_func) - 1] = '\0';
156     fgets_res = fgets(line_pos, 1024, pipe);
157     if (fgets_res == NULL)
158       THROW2(system_error, 0,
159              "Cannot run fgets to look for symbol %d, addr %s", i, addrs[i]);
160     line_pos[strlen(line_pos) - 1] = '\0';
161
162     if (strcmp("??", line_func)) {
163       DEBUG2("Found static symbol %s() at %s", line_func, line_pos);
164       e->bt_strings[i] = bprintf("**   In %s() at %s", line_func, line_pos);
165     } else {
166       /* Damn. The symbol is in a dynamic library. Let's get wild */
167       char *maps_name;
168       FILE *maps;
169       char maps_buff[512];
170
171       long int addr, offset = 0;
172       char *p, *p2;
173
174       char *subcmd;
175       FILE *subpipe;
176       int found = 0;
177
178       /* let's look for the offset of this library in our addressing space */
179       maps_name = bprintf("/proc/%d/maps", (int) getpid());
180       maps = fopen(maps_name, "r");
181
182       sscanf(addrs[i], "%lx", &addr);
183       sprintf(maps_buff, "%#lx", addr);
184
185       if (strcmp(addrs[i], maps_buff)) {
186         CRITICAL2("Cannot parse backtrace address '%s' (addr=%#lx)",
187                   addrs[i], addr);
188       }
189       DEBUG2("addr=%s (as string) =%#lx (as number)", addrs[i], addr);
190
191       while (!found) {
192         long int first, last;
193
194         if (fgets(maps_buff, 512, maps) == NULL)
195           break;
196         if (i == 0) {
197           maps_buff[strlen(maps_buff) - 1] = '\0';
198           DEBUG1("map line: %s", maps_buff);
199         }
200         sscanf(maps_buff, "%lx", &first);
201         p = strchr(maps_buff, '-') + 1;
202         sscanf(p, "%lx", &last);
203         if (first < addr && addr < last) {
204           offset = first;
205           found = 1;
206         }
207         if (found) {
208           DEBUG3("%#lx in [%#lx-%#lx]", addr, first, last);
209           DEBUG0
210             ("Symbol found, map lines not further displayed (even if looking for next ones)");
211         }
212       }
213       fclose(maps);
214       free(maps_name);
215
216       if (!found) {
217         VERB0
218           ("Problem while reading the maps file. Following backtrace will be mangled.");
219         DEBUG1("No dynamic. Static symbol: %s", backtrace_syms[i]);
220         e->bt_strings[i] = bprintf("**   In ?? (%s)", backtrace_syms[i]);
221         continue;
222       }
223
224       /* Ok, Found the offset of the maps line containing the searched symbol.
225          We now need to substract this from the address we got from backtrace.
226        */
227
228       free(addrs[i]);
229       addrs[i] = bprintf("0x%0*lx", addr_len - 2, addr - offset);
230       DEBUG2("offset=%#lx new addr=%s", offset, addrs[i]);
231
232       /* Got it. We have our new address. Let's get the library path and we
233          are set */
234       p = xbt_strdup(backtrace_syms[i]);
235       if (p[0] == '[') {
236         /* library path not displayed in the map file either... */
237         free(p);
238         sprintf(line_func, "??");
239       } else {
240         p2 = strrchr(p, '(');
241         if (p2)
242           *p2 = '\0';
243         p2 = strrchr(p, ' ');
244         if (p2)
245           *p2 = '\0';
246
247         /* Here we go, fire an addr2line up */
248         subcmd = bprintf("%s -f -e %s %s", ADDR2LINE, p, addrs[i]);
249         free(p);
250         VERB1("Fire a new command: '%s'", subcmd);
251         subpipe = popen(subcmd, "r");
252         if (!subpipe) {
253           CRITICAL0("Cannot fork addr2line to display the backtrace");
254           abort();
255         }
256         fgets_res = fgets(line_func, 1024, subpipe);
257         if (fgets_res == NULL)
258           THROW1(system_error, 0, "Cannot read result of subcommand %s",
259                  subcmd);
260         line_func[strlen(line_func) - 1] = '\0';
261         fgets_res = fgets(line_pos, 1024, subpipe);
262         if (fgets_res == NULL)
263           THROW1(system_error, 0, "Cannot read result of subcommand %s",
264                  subcmd);
265         line_pos[strlen(line_pos) - 1] = '\0';
266         pclose(subpipe);
267         free(subcmd);
268       }
269
270       /* check whether the trick worked */
271       if (strcmp("??", line_func)) {
272         DEBUG2("Found dynamic symbol %s() at %s", line_func, line_pos);
273         e->bt_strings[i] = bprintf("**   In %s() at %s", line_func, line_pos);
274       } else {
275         /* damn, nothing to do here. Let's print the raw address */
276         DEBUG1("Dynamic symbol not found. Raw address = %s",
277                backtrace_syms[i]);
278         e->bt_strings[i] = bprintf("**   In ?? at %s", backtrace_syms[i]);
279       }
280
281     }
282     free(addrs[i]);
283
284     /* Mask the bottom of the stack */
285     if (!strncmp("main", line_func, strlen("main")) ||
286         !strncmp("xbt_thread_context_wrapper", line_func, strlen("xbt_thread_context_wrapper"))||
287         !strncmp("smx_ctx_sysv_wrapper",line_func,strlen("smx_ctx_sysv_wrapper"))) {
288       int j;
289
290       for (j = i + 1; j < e->used; j++)
291         free(addrs[j]);
292       e->used = i;
293
294       if (!strncmp
295           ("xbt_thread_context_wrapper", line_func,
296            strlen("xbt_thread_context_wrapper"))) {
297         e->used++;
298         e->bt_strings[i] = bprintf("**   (in a separate thread)");
299       }
300     }
301
302
303   }
304   pclose(pipe);
305   free(addrs);
306   free(backtrace_syms);
307   free(cmd);
308 }