Logo AND Algorithmique Numérique Distribuée

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