Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
4fc1ebc6f43ec541cd5e9bf3b04a780872cd044f
[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 #include <unwind.h>
29 struct trace_arg {
30   void **array;
31   int cnt, size;
32 };
33
34 static _Unwind_Reason_Code
35 backtrace_helper (struct _Unwind_Context *ctx, void *a)
36 {
37   struct trace_arg *arg = a;
38
39   /* We are first called with address in the __backtrace function.
40      Skip it.  */
41   if (arg->cnt != -1)
42     {
43       arg->array[arg->cnt] = (void *) _Unwind_GetIP(ctx);
44
45       /* Check whether we make any progress.  */
46       if (arg->cnt > 0 && arg->array[arg->cnt - 1] == arg->array[arg->cnt])
47         return _URC_END_OF_STACK;
48     }
49   if (++arg->cnt == arg->size)
50     return _URC_END_OF_STACK;
51   return _URC_NO_REASON;
52 }
53
54 /** @brief reimplementation of glibc backtrace based directly on gcc library, without implicit malloc
55  *
56  * See http://webloria.loria.fr/~quinson/blog/2012/0208/system_programming_fun_in_SimGrid/
57  * for the motivation behind this function
58  * */
59
60 int xbt_backtrace_no_malloc(void **array, int size) {
61   struct trace_arg arg = { .array = array, .size = size, .cnt = -1 };
62
63   if (size >= 1)
64     _Unwind_Backtrace(backtrace_helper, &arg);
65
66   /* _Unwind_Backtrace on IA-64 seems to put NULL address above
67      _start.  Fix it up here.  */
68   if (arg.cnt > 1 && arg.array[arg.cnt - 1] == NULL)
69     --arg.cnt;
70   return arg.cnt != -1 ? arg.cnt : 0;
71 }
72
73 void xbt_backtrace_current(xbt_ex_t * e)
74 {
75   e->used = backtrace((void **) e->bt, XBT_BACKTRACE_SIZE);
76   if (e->used == 0) {
77     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:");
78     fprintf(stderr, "%s:%s(%d) [%s:%d] %s", e->host,e->procname,e->pid, e->file,e->line,e->msg);
79     fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory. Please go fix the memleaks\n");
80     exit(1);
81   }
82 }
83
84
85 void xbt_ex_setup_backtrace(xbt_ex_t * e) //FIXME: This code could be greatly improved/simplifyied with http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
86 {
87   int i;
88
89   /* to get the backtrace from the libc */
90   char **backtrace_syms;
91
92   /* To build the commandline of addr2line */
93   char *cmd, *curr;
94
95   /* to extract the addresses from the backtrace */
96   char **addrs;
97   char buff[256], *p;
98
99   /* To read the output of addr2line */
100   FILE *pipe;
101   char line_func[1024], line_pos[1024];
102
103   /* size (in char) of pointers on this arch */
104   int addr_len = 0;
105
106   /* To search for the right executable path when not trivial */
107   struct stat stat_buf;
108   char *binary_name = NULL;
109
110   xbt_assert(e, "Backtrace not setup yet, cannot set it up for display");
111
112   e->bt_strings = NULL;
113
114   if (!xbt_binary_name) /* no binary name, nothing to do */
115     return;
116
117   if (e->used <= 1)
118     return;
119
120   /* ignore first one, which is xbt_backtrace_current() */
121   e->used--;
122   memmove(e->bt, e->bt + 1, (sizeof *e->bt) * e->used);
123
124   backtrace_syms = backtrace_symbols(e->bt, e->used);
125
126   /* build the commandline */
127   if (stat(xbt_binary_name, &stat_buf)) {
128     /* Damn. binary not in current dir. We'll have to dig the PATH to find it */
129     int i;
130
131     for (i = 0; environ[i]; i++) {
132       if (!strncmp("PATH=", environ[i], 5)) {
133         xbt_dynar_t path = xbt_str_split(environ[i] + 5, ":");
134         unsigned int cpt;
135         char *data;
136
137         xbt_dynar_foreach(path, cpt, data) {
138           free(binary_name);
139           binary_name = bprintf("%s/%s", data, xbt_binary_name);
140           if (!stat(binary_name, &stat_buf)) {
141             /* Found. */
142             XBT_DEBUG("Looked in the PATH for the binary. Found %s",
143                    binary_name);
144             break;
145           }
146         }
147         xbt_dynar_free(&path);
148         if (stat(binary_name, &stat_buf)) {
149           /* not found */
150           e->used = 1;
151           e->bt_strings = xbt_new(char *, 1);
152
153           e->bt_strings[0] =
154               bprintf("(binary '%s' not found the path)", xbt_binary_name);
155           free(backtrace_syms);
156           return;
157         }
158         break;
159       }
160     }
161   } else {
162     binary_name = xbt_strdup(xbt_binary_name);
163   }
164   cmd = curr =
165       xbt_new(char,
166               strlen(ADDR2LINE) + 25 + strlen(binary_name) + 32 * e->used);
167
168   curr += sprintf(curr, "%s -f -e %s ", ADDR2LINE, binary_name);
169   free(binary_name);
170
171   addrs = xbt_new(char *, e->used);
172   for (i = 0; i < e->used; i++) {
173     /* retrieve this address */
174     XBT_DEBUG("Retrieving address number %d from '%s'", i, backtrace_syms[i]);
175     snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
176     p = strchr(buff, ']');
177     *p = '\0';
178     if (strcmp(buff, "(nil)"))
179       addrs[i] = xbt_strdup(buff);
180     else
181       addrs[i] = xbt_strdup("0x0");
182     XBT_DEBUG("Set up a new address: %d, '%s'(%p)", i, addrs[i], addrs[i]);
183
184     /* Add it to the command line args */
185     curr += sprintf(curr, "%s ", addrs[i]);
186   }
187   addr_len = strlen(addrs[0]);
188
189   /* parse the output and build a new backtrace */
190   e->bt_strings = xbt_new(char *, e->used);
191
192   XBT_VERB("Fire a first command: '%s'", cmd);
193   pipe = popen(cmd, "r");
194   if (!pipe) {
195     XBT_CRITICAL("Cannot fork addr2line to display the backtrace");
196     abort();
197   }
198
199   for (i = 0; i < e->used; i++) {
200     char *fgets_res;
201     XBT_DEBUG("Looking for symbol %d, addr = '%s'", i, addrs[i]);
202     fgets_res = fgets(line_func, 1024, pipe);
203     if (fgets_res == NULL)
204       THROWF(system_error, 0,
205              "Cannot run fgets to look for symbol %d, addr %s", i,
206              addrs[i]);
207     line_func[strlen(line_func) - 1] = '\0';
208     fgets_res = fgets(line_pos, 1024, pipe);
209     if (fgets_res == NULL)
210       THROWF(system_error, 0,
211              "Cannot run fgets to look for symbol %d, addr %s", i,
212              addrs[i]);
213     line_pos[strlen(line_pos) - 1] = '\0';
214
215     if (strcmp("??", line_func)) {
216       XBT_DEBUG("Found static symbol %s() at %s", line_func, line_pos);
217       e->bt_strings[i] =
218           bprintf("**   In %s() at %s", line_func, line_pos);
219     } else {
220       /* Damn. The symbol is in a dynamic library. Let's get wild */
221       char *maps_name;
222       FILE *maps;
223       char maps_buff[512];
224
225       long int addr, offset = 0;
226       char *p, *p2;
227
228       char *subcmd;
229       FILE *subpipe;
230       int found = 0;
231
232       /* let's look for the offset of this library in our addressing space */
233       maps_name = bprintf("/proc/%d/maps", (int) getpid());
234       maps = fopen(maps_name, "r");
235
236       addr = strtol(addrs[i], &p, 16);
237       if (*p != '\0') {
238         XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)",
239                   addrs[i], addr);
240       }
241       XBT_DEBUG("addr=%s (as string) =%#lx (as number)", addrs[i], addr);
242
243       while (!found) {
244         long int first, last;
245
246         if (fgets(maps_buff, 512, maps) == NULL)
247           break;
248         if (i == 0) {
249           maps_buff[strlen(maps_buff) - 1] = '\0';
250           XBT_DEBUG("map line: %s", maps_buff);
251         }
252         sscanf(maps_buff, "%lx", &first);
253         p = strchr(maps_buff, '-') + 1;
254         sscanf(p, "%lx", &last);
255         if (first < addr && addr < last) {
256           offset = first;
257           found = 1;
258         }
259         if (found) {
260           XBT_DEBUG("%#lx in [%#lx-%#lx]", addr, first, last);
261           XBT_DEBUG
262               ("Symbol found, map lines not further displayed (even if looking for next ones)");
263         }
264       }
265       fclose(maps);
266       free(maps_name);
267       free(addrs[i]);
268
269       if (!found) {
270         XBT_VERB
271             ("Problem while reading the maps file. Following backtrace will be mangled.");
272         XBT_DEBUG("No dynamic. Static symbol: %s", backtrace_syms[i]);
273         e->bt_strings[i] = bprintf("**   In ?? (%s)", backtrace_syms[i]);
274         continue;
275       }
276
277       /* Ok, Found the offset of the maps line containing the searched symbol.
278          We now need to substract this from the address we got from backtrace.
279        */
280
281       addrs[i] = bprintf("0x%0*lx", addr_len - 2, addr - offset);
282       XBT_DEBUG("offset=%#lx new addr=%s", offset, addrs[i]);
283
284       /* Got it. We have our new address. Let's get the library path and we
285          are set */
286       p = xbt_strdup(backtrace_syms[i]);
287       if (p[0] == '[') {
288         /* library path not displayed in the map file either... */
289         free(p);
290         sprintf(line_func, "??");
291       } else {
292         p2 = strrchr(p, '(');
293         if (p2)
294           *p2 = '\0';
295         p2 = strrchr(p, ' ');
296         if (p2)
297           *p2 = '\0';
298
299         /* Here we go, fire an addr2line up */
300         subcmd = bprintf("%s -f -e %s %s", ADDR2LINE, p, addrs[i]);
301         free(p);
302         XBT_VERB("Fire a new command: '%s'", subcmd);
303         subpipe = popen(subcmd, "r");
304         if (!subpipe) {
305           XBT_CRITICAL("Cannot fork addr2line to display the backtrace");
306           abort();
307         }
308         fgets_res = fgets(line_func, 1024, subpipe);
309         if (fgets_res == NULL)
310           THROWF(system_error, 0, "Cannot read result of subcommand %s",
311                  subcmd);
312         line_func[strlen(line_func) - 1] = '\0';
313         fgets_res = fgets(line_pos, 1024, subpipe);
314         if (fgets_res == NULL)
315           THROWF(system_error, 0, "Cannot read result of subcommand %s",
316                  subcmd);
317         line_pos[strlen(line_pos) - 1] = '\0';
318         pclose(subpipe);
319         free(subcmd);
320       }
321
322       /* check whether the trick worked */
323       if (strcmp("??", line_func)) {
324         XBT_DEBUG("Found dynamic symbol %s() at %s", line_func, line_pos);
325         e->bt_strings[i] =
326             bprintf("**   In %s() at %s", line_func, line_pos);
327       } else {
328         /* damn, nothing to do here. Let's print the raw address */
329         XBT_DEBUG("Dynamic symbol not found. Raw address = %s",
330                backtrace_syms[i]);
331         e->bt_strings[i] = bprintf("**   In ?? at %s", backtrace_syms[i]);
332       }
333
334     }
335     free(addrs[i]);
336
337     /* Mask the bottom of the stack */
338     if (!strncmp("main", line_func, strlen("main")) ||
339         !strncmp("xbt_thread_context_wrapper", line_func,
340                  strlen("xbt_thread_context_wrapper"))
341         || !strncmp("smx_ctx_sysv_wrapper", line_func,
342                     strlen("smx_ctx_sysv_wrapper"))) {
343       int j;
344
345       for (j = i + 1; j < e->used; j++)
346         free(addrs[j]);
347       e->used = i + 1;
348
349       if (!strncmp
350           ("xbt_thread_context_wrapper", line_func,
351            strlen("xbt_thread_context_wrapper"))) {
352         free(e->bt_strings[i]);
353         e->bt_strings[i] = xbt_strdup("**   (in a separate thread)");
354       }
355     }
356
357
358   }
359   pclose(pipe);
360   free(addrs);
361   free(backtrace_syms);
362   free(cmd);
363 }