Logo AND Algorithmique Numérique Distribuée

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