Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Work around newly reincreased paranoia of gcc and libc on ubuntu. It's geting hard...
[simgrid.git] / src / xbt / backtrace_linux.c
1 /* $Id: ex.c 5173 2008-01-07 22:10:52Z mquinson $ */
2
3 /* backtrace_linux - backtrace displaying on linux platform                 */
4 /* This file is included by ex.c on need (have execinfo.h, popen & addrline)*/
5
6 /*  Copyright (c) 2007 The SimGrid team                                     */
7 /*  All rights reserved.                                                    */
8
9 /* This program is free software; you can redistribute it and/or modify it
10  * under the terms of the license (GNU LGPL) which comes with this package. */
11
12 extern char **environ;          /* the environment, as specified by the opengroup */
13
14 /* Module creation/destruction: nothing to do on linux */
15 void xbt_backtrace_init(void) { }
16 void xbt_backtrace_exit(void) { }
17
18 void xbt_backtrace_current(xbt_ex_t * e) {
19   e->used = backtrace((void **) e->bt, XBT_BACKTRACE_SIZE);
20 }
21
22
23 void xbt_ex_setup_backtrace(xbt_ex_t * e)
24 {
25   int i;
26
27   /* to get the backtrace from the libc */
28   char **backtrace_syms;
29
30   /* To build the commandline of addr2line */
31   char *cmd, *curr;
32
33   /* to extract the addresses from the backtrace */
34   char **addrs;
35   char buff[256], *p;
36
37   /* To read the output of addr2line */
38   FILE *pipe;
39   char line_func[1024], line_pos[1024];
40
41   /* size (in char) of pointers on this arch */
42   int addr_len = 0;
43
44   /* To search for the right executable path when not trivial */
45   struct stat stat_buf;
46   char *binary_name = NULL;
47
48   xbt_assert0(e && e->used,"Backtrace not setup yet, cannot set it up for display");
49
50   backtrace_syms = backtrace_symbols(e->bt, e->used);
51   addrs = xbt_new(char *, e->used);
52
53   e->bt_strings = NULL;
54
55   /* Some arches only have stubs of backtrace, no implementation (hppa comes to mind) */
56   if (!e->used)
57     return;
58
59   /* build the commandline */
60   if (stat(xbt_binary_name, &stat_buf)) {
61     /* Damn. binary not in current dir. We'll have to dig the PATH to find it */
62     int i;
63
64     for (i = 0; environ[i]; i++) {
65       if (!strncmp("PATH=", environ[i], 5)) {
66         xbt_dynar_t path = xbt_str_split(environ[i] + 5, ":");
67         unsigned int cpt;
68         char *data;
69
70         xbt_dynar_foreach(path, cpt, data) {
71           if (binary_name)
72             free(binary_name);
73           binary_name = bprintf("%s/%s", data, xbt_binary_name);
74           if (!stat(binary_name, &stat_buf)) {
75             /* Found. */
76             DEBUG1("Looked in the PATH for the binary. Found %s",
77                    binary_name);
78             xbt_dynar_free(&path);
79             break;
80           }
81         }
82         if (stat(binary_name, &stat_buf)) {
83           /* not found */
84           e->used = 1;
85           e->bt_strings = xbt_new(char *, 1);
86
87           e->bt_strings[0] =
88             bprintf("(binary '%s' not found the path)", xbt_binary_name);
89           return;
90         }
91         xbt_dynar_free(&path);
92         break;
93       }
94     }
95   } else {
96     binary_name = xbt_strdup(xbt_binary_name);
97   }
98   cmd = curr =
99     xbt_new(char,
100             strlen(ADDR2LINE) + 25 + strlen(binary_name) + 32 * e->used);
101
102   curr += sprintf(curr, "%s -f -e %s ", ADDR2LINE, binary_name);
103   free(binary_name);
104
105   for (i = 0; i < e->used; i++) {
106     /* retrieve this address */
107     DEBUG2("Retrieving address number %d from '%s'", i, backtrace_syms[i]);
108     snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
109     p = strchr(buff, ']');
110     *p = '\0';
111     if (strcmp(buff, "(nil)"))
112       addrs[i] = bprintf("%s", buff);
113     else
114       addrs[i] = bprintf("0x0");
115     DEBUG3("Set up a new address: %d, '%s'(%p)", i, addrs[i], addrs[i]);
116
117     /* Add it to the command line args */
118     curr += sprintf(curr, "%s ", addrs[i]);
119   }
120   addr_len = strlen(addrs[0]);
121
122   /* parse the output and build a new backtrace */
123   e->bt_strings = xbt_new(char *, e->used);
124
125   VERB1("Fire a first command: '%s'", cmd);
126   pipe = popen(cmd, "r");
127   if (!pipe) {
128     CRITICAL0("Cannot fork addr2line to display the backtrace");
129     abort();
130   }
131
132   for (i = 0; i < e->used; i++) {
133     char *fgets_res;
134     DEBUG2("Looking for symbol %d, addr = '%s'", i, addrs[i]);
135     fgets_res = fgets(line_func, 1024, pipe);
136     if (fgets_res == NULL)
137       THROW2(system_error,0, "Cannot run fgets to look for symbol %d, addr %s",i, addrs[i]);
138     line_func[strlen(line_func) - 1] = '\0';
139     fgets_res = fgets(line_pos, 1024, pipe);
140     if (fgets_res == NULL)
141       THROW2(system_error,0, "Cannot run fgets to look for symbol %d, addr %s",i, addrs[i]);
142     line_pos[strlen(line_pos) - 1] = '\0';
143
144     if (strcmp("??", line_func)) {
145       DEBUG2("Found static symbol %s() at %s", line_func, line_pos);
146       e->bt_strings[i] = bprintf("**   In %s() at %s", line_func, line_pos);
147     } else {
148       /* Damn. The symbol is in a dynamic library. Let's get wild */
149       char *maps_name;
150       FILE *maps;
151       char maps_buff[512];
152
153       long int addr, offset = 0;
154       char *p, *p2;
155
156       char *subcmd;
157       FILE *subpipe;
158       int found = 0;
159
160       /* let's look for the offset of this library in our addressing space */
161       maps_name = bprintf("/proc/%d/maps", (int) getpid());
162       maps = fopen(maps_name, "r");
163
164       sscanf(addrs[i], "%lx", &addr);
165       sprintf(maps_buff, "%#lx", addr);
166
167       if (strcmp(addrs[i], maps_buff)) {
168         CRITICAL2("Cannot parse backtrace address '%s' (addr=%#lx)",
169                   addrs[i], addr);
170       }
171       DEBUG2("addr=%s (as string) =%#lx (as number)", addrs[i], addr);
172
173       while (!found) {
174         long int first, last;
175
176         if (fgets(maps_buff, 512, maps) == NULL)
177           break;
178         if (i == 0) {
179           maps_buff[strlen(maps_buff) - 1] = '\0';
180           DEBUG1("map line: %s", maps_buff);
181         }
182         sscanf(maps_buff, "%lx", &first);
183         p = strchr(maps_buff, '-') + 1;
184         sscanf(p, "%lx", &last);
185         if (first < addr && addr < last) {
186           offset = first;
187           found = 1;
188         }
189         if (found) {
190           DEBUG3("%#lx in [%#lx-%#lx]", addr, first, last);
191           DEBUG0
192           ("Symbol found, map lines not further displayed (even if looking for next ones)");
193         }
194       }
195       fclose(maps);
196       free(maps_name);
197
198       if (!found) {
199         VERB0
200         ("Problem while reading the maps file. Following backtrace will be mangled.");
201         DEBUG1("No dynamic. Static symbol: %s", backtrace_syms[i]);
202         e->bt_strings[i] = bprintf("**   In ?? (%s)", backtrace_syms[i]);
203         continue;
204       }
205
206       /* Ok, Found the offset of the maps line containing the searched symbol.
207          We now need to substract this from the address we got from backtrace.
208        */
209
210       free(addrs[i]);
211       addrs[i] = bprintf("0x%0*lx", addr_len - 2, addr - offset);
212       DEBUG2("offset=%#lx new addr=%s", offset, addrs[i]);
213
214       /* Got it. We have our new address. Let's get the library path and we
215          are set */
216       p = xbt_strdup(backtrace_syms[i]);
217       if (p[0] == '[') {
218         /* library path not displayed in the map file either... */
219         free(p);
220         sprintf(line_func, "??");
221       } else {
222         p2 = strrchr(p, '(');
223         if (p2)
224           *p2 = '\0';
225         p2 = strrchr(p, ' ');
226         if (p2)
227           *p2 = '\0';
228
229         /* Here we go, fire an addr2line up */
230         subcmd = bprintf("%s -f -e %s %s", ADDR2LINE, p, addrs[i]);
231         free(p);
232         VERB1("Fire a new command: '%s'", subcmd);
233         subpipe = popen(subcmd, "r");
234         if (!subpipe) {
235           CRITICAL0("Cannot fork addr2line to display the backtrace");
236           abort();
237         }
238         fgets_res=fgets(line_func, 1024, subpipe);
239         if (fgets_res == NULL)
240           THROW1(system_error,0, "Cannot read result of subcommand %s",subcmd);
241         line_func[strlen(line_func) - 1] = '\0';
242         fgets_res = fgets(line_pos, 1024, subpipe);
243         if (fgets_res == NULL)
244           THROW1(system_error,0, "Cannot read result of subcommand %s",subcmd);
245         line_pos[strlen(line_pos) - 1] = '\0';
246         pclose(subpipe);
247         free(subcmd);
248       }
249
250       /* check whether the trick worked */
251       if (strcmp("??", line_func)) {
252         DEBUG2("Found dynamic symbol %s() at %s", line_func, line_pos);
253         e->bt_strings[i] = bprintf("**   In %s() at %s", line_func, line_pos);
254       } else {
255         /* damn, nothing to do here. Let's print the raw address */
256         DEBUG1("Dynamic symbol not found. Raw address = %s",
257                backtrace_syms[i]);
258         e->bt_strings[i] = bprintf("**   In ?? at %s", backtrace_syms[i]);
259       }
260
261     }
262     free(addrs[i]);
263
264     /* Mask the bottom of the stack */
265     if (!strncmp("main", line_func, strlen("main")) ||
266         !strncmp("xbt_thread_context_wrapper", line_func,
267                  strlen("xbt_thread_context_wrapper"))) {
268       int j;
269
270       for (j = i + 1; j < e->used; j++)
271         free(addrs[j]);
272       e->used = i;
273
274       if (!strncmp
275           ("xbt_thread_context_wrapper", line_func,
276            strlen("xbt_thread_context_wrapper"))) {
277         e->used++;
278         e->bt_strings[i] = bprintf("**   (in a separate thread)");
279       }
280     }
281
282
283   }
284   pclose(pipe);
285   free(addrs);
286   free(backtrace_syms);
287   free(cmd);
288 }