Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge ../simgrid
[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 != NULL) /* 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     XBT_DEBUG("Looking for symbol %d, addr = '%s'", i, addrs[i]);
204     if (fgets(line_func, 1024, pipe)) {
205       line_func[strlen(line_func) - 1] = '\0';
206     } else {
207       XBT_VERB("Cannot run fgets to look for symbol %d, addr %s", i, addrs[i]);
208       strcpy(line_func, "???");
209     }
210     if (fgets(line_pos, 1024, pipe)) {
211       line_pos[strlen(line_pos) - 1] = '\0';
212     } else {
213       XBT_VERB("Cannot run fgets to look for symbol %d, addr %s", i, addrs[i]);
214       strcpy(line_pos, backtrace_syms[i]);
215     }
216
217     if (strcmp("??", line_func) != 0) {
218       XBT_DEBUG("Found static symbol %s() at %s", line_func, line_pos);
219       e->bt_strings[i] =
220           bprintf("**   In %s() at %s", line_func, line_pos);
221     } else {
222       /* Damn. The symbol is in a dynamic library. Let's get wild */
223       char *maps_name;
224       FILE *maps;
225       char maps_buff[512];
226
227       long int addr, offset = 0;
228       char *p, *p2;
229
230       char *subcmd;
231       FILE *subpipe;
232       int found = 0;
233
234       /* let's look for the offset of this library in our addressing space */
235       maps_name = bprintf("/proc/%d/maps", (int) getpid());
236       maps = fopen(maps_name, "r");
237
238       addr = strtol(addrs[i], &p, 16);
239       if (*p != '\0') {
240         XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)",
241                   addrs[i], addr);
242       }
243       XBT_DEBUG("addr=%s (as string) =%#lx (as number)", addrs[i], addr);
244
245       while (!found) {
246         long int first, last;
247
248         if (fgets(maps_buff, 512, maps) == NULL)
249           break;
250         if (i == 0) {
251           maps_buff[strlen(maps_buff) - 1] = '\0';
252           XBT_DEBUG("map line: %s", maps_buff);
253         }
254         sscanf(maps_buff, "%lx", &first);
255         p = strchr(maps_buff, '-') + 1;
256         sscanf(p, "%lx", &last);
257         if (first < addr && addr < last) {
258           offset = first;
259           found = 1;
260         }
261         if (found) {
262           XBT_DEBUG("%#lx in [%#lx-%#lx]", addr, first, last);
263           XBT_DEBUG
264               ("Symbol found, map lines not further displayed (even if looking for next ones)");
265         }
266       }
267       fclose(maps);
268       free(maps_name);
269       free(addrs[i]);
270
271       if (!found) {
272         XBT_VERB
273             ("Problem while reading the maps file. Following backtrace will be mangled.");
274         XBT_DEBUG("No dynamic. Static symbol: %s", backtrace_syms[i]);
275         e->bt_strings[i] = bprintf("**   In ?? (%s)", backtrace_syms[i]);
276         continue;
277       }
278
279       /* Ok, Found the offset of the maps line containing the searched symbol.
280          We now need to substract this from the address we got from backtrace.
281        */
282
283       addrs[i] = bprintf("0x%0*lx", addr_len - 2, addr - offset);
284       XBT_DEBUG("offset=%#lx new addr=%s", offset, addrs[i]);
285
286       /* Got it. We have our new address. Let's get the library path and we
287          are set */
288       p = xbt_strdup(backtrace_syms[i]);
289       if (p[0] == '[') {
290         /* library path not displayed in the map file either... */
291         free(p);
292         sprintf(line_func, "??");
293       } else {
294         p2 = strrchr(p, '(');
295         if (p2)
296           *p2 = '\0';
297         p2 = strrchr(p, ' ');
298         if (p2)
299           *p2 = '\0';
300
301         /* Here we go, fire an addr2line up */
302         subcmd = bprintf("%s -f -e %s %s", ADDR2LINE, p, addrs[i]);
303         free(p);
304         XBT_VERB("Fire a new command: '%s'", subcmd);
305         subpipe = popen(subcmd, "r");
306         if (!subpipe) {
307           xbt_die("Cannot fork addr2line to display the backtrace");
308         }
309         if (fgets(line_func, 1024, subpipe)) {
310           line_func[strlen(line_func) - 1] = '\0';
311         } else {
312           XBT_VERB("Cannot read result of subcommand %s", subcmd);
313           strcpy(line_func, "???");
314         }
315         if (fgets(line_pos, 1024, subpipe)) {
316           line_pos[strlen(line_pos) - 1] = '\0';
317         } else {
318           XBT_VERB("Cannot read result of subcommand %s", subcmd);
319           strcpy(line_pos, backtrace_syms[i]);
320         }
321         pclose(subpipe);
322         free(subcmd);
323       }
324
325       /* check whether the trick worked */
326       if (strcmp("??", line_func)) {
327         XBT_DEBUG("Found dynamic symbol %s() at %s", line_func, line_pos);
328         e->bt_strings[i] =
329             bprintf("**   In %s() at %s", line_func, line_pos);
330       } else {
331         /* damn, nothing to do here. Let's print the raw address */
332         XBT_DEBUG("Dynamic symbol not found. Raw address = %s",
333                backtrace_syms[i]);
334         e->bt_strings[i] = bprintf("**   In ?? at %s", backtrace_syms[i]);
335       }
336
337     }
338     free(addrs[i]);
339
340     /* Mask the bottom of the stack */
341     if (!strncmp("main", line_func, strlen("main")) ||
342         !strncmp("xbt_thread_context_wrapper", line_func,
343                  strlen("xbt_thread_context_wrapper"))
344         || !strncmp("smx_ctx_sysv_wrapper", line_func,
345                     strlen("smx_ctx_sysv_wrapper"))) {
346       int j;
347
348       for (j = i + 1; j < e->used; j++)
349         free(addrs[j]);
350       e->used = i + 1;
351
352       if (!strncmp
353           ("xbt_thread_context_wrapper", line_func,
354            strlen("xbt_thread_context_wrapper"))) {
355         free(e->bt_strings[i]);
356         e->bt_strings[i] = xbt_strdup("**   (in a separate thread)");
357       }
358     }
359
360
361   }
362   pclose(pipe);
363   free(addrs);
364   free(backtrace_syms);
365   free(cmd);
366 }