Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
make the category setting function public
[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(%d) [%s:%d] %s",
84             e->procname, e->pid, e->file, e->line, e->msg);
85     fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory. Please go fix the memleaks\n");
86     exit(1);
87   }
88 }
89
90
91 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
92 {
93   int i;
94
95   /* to get the backtrace from the libc */
96   char **backtrace_syms;
97
98   /* To build the commandline of addr2line */
99   char *cmd, *curr;
100
101   /* to extract the addresses from the backtrace */
102   char **addrs;
103   char buff[256];
104
105   /* To read the output of addr2line */
106   FILE *pipe;
107   char line_func[1024], line_pos[1024];
108
109   /* size (in char) of pointers on this arch */
110   int addr_len = 0;
111
112   /* To search for the right executable path when not trivial */
113   struct stat stat_buf;
114   char *binary_name = NULL;
115
116   xbt_assert(e, "Backtrace not setup yet, cannot set it up for display");
117
118   e->bt_strings = NULL;
119
120   if (xbt_binary_name == NULL) /* no binary name, nothing to do */
121     return;
122
123   if (e->used <= 1)
124     return;
125
126   /* ignore first one, which is xbt_backtrace_current() */
127   e->used--;
128   memmove(e->bt, e->bt + 1, (sizeof *e->bt) * e->used);
129
130   backtrace_syms = backtrace_symbols(e->bt, e->used);
131
132   /* build the commandline */
133   if (stat(xbt_binary_name, &stat_buf)) {
134     /* Damn. binary not in current dir. We'll have to dig the PATH to find it */
135     for (i = 0; environ[i]; i++) {
136       if (!strncmp("PATH=", environ[i], 5)) {
137         xbt_dynar_t path = xbt_str_split(environ[i] + 5, ":");
138         unsigned int cpt;
139         char *data;
140
141         xbt_dynar_foreach(path, cpt, data) {
142           free(binary_name);
143           binary_name = bprintf("%s/%s", data, xbt_binary_name);
144           if (!stat(binary_name, &stat_buf)) {
145             /* Found. */
146             XBT_DEBUG("Looked in the PATH for the binary. Found %s",
147                    binary_name);
148             break;
149           }
150         }
151         xbt_dynar_free(&path);
152         if (stat(binary_name, &stat_buf)) {
153           /* not found */
154           e->used = 1;
155           e->bt_strings = xbt_new(char *, 1);
156
157           e->bt_strings[0] =
158               bprintf("(binary '%s' not found in the PATH)", xbt_binary_name);
159           free(backtrace_syms);
160           return;
161         }
162         break;
163       }
164     }
165   } else {
166     binary_name = xbt_strdup(xbt_binary_name);
167   }
168   cmd = curr =
169       xbt_new(char,
170               strlen(ADDR2LINE) + 25 + strlen(binary_name) + 32 * e->used);
171
172   curr += sprintf(curr, "%s -f -e %s ", ADDR2LINE, binary_name);
173   free(binary_name);
174
175   addrs = xbt_new(char *, e->used);
176   for (i = 0; i < e->used; i++) {
177     char *p;
178     /* retrieve this address */
179     XBT_DEBUG("Retrieving address number %d from '%s'", i, backtrace_syms[i]);
180     snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
181     p = strchr(buff, ']');
182     *p = '\0';
183     if (strcmp(buff, "(nil)"))
184       addrs[i] = xbt_strdup(buff);
185     else
186       addrs[i] = xbt_strdup("0x0");
187     XBT_DEBUG("Set up a new address: %d, '%s'(%p)", i, addrs[i], addrs[i]);
188
189     /* Add it to the command line args */
190     curr += sprintf(curr, "%s ", addrs[i]);
191   }
192   addr_len = strlen(addrs[0]);
193
194   /* parse the output and build a new backtrace */
195   e->bt_strings = xbt_new(char *, e->used);
196
197   XBT_VERB("Fire a first command: '%s'", cmd);
198   pipe = popen(cmd, "r");
199   if (!pipe) {
200     xbt_die("Cannot fork addr2line to display the backtrace");
201   }
202
203   for (i = 0; i < e->used; i++) {
204     XBT_DEBUG("Looking for symbol %d, addr = '%s'", i, addrs[i]);
205     if (fgets(line_func, 1024, pipe)) {
206       line_func[strlen(line_func) - 1] = '\0';
207     } else {
208       XBT_VERB("Cannot run fgets to look for symbol %d, addr %s", i, addrs[i]);
209       strcpy(line_func, "???");
210     }
211     if (fgets(line_pos, 1024, pipe)) {
212       line_pos[strlen(line_pos) - 1] = '\0';
213     } else {
214       XBT_VERB("Cannot run fgets to look for symbol %d, addr %s", i, addrs[i]);
215       strcpy(line_pos, backtrace_syms[i]);
216     }
217
218     if (strcmp("??", line_func) != 0) {
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         if (fgets(line_func, 1024, subpipe)) {
311           line_func[strlen(line_func) - 1] = '\0';
312         } else {
313           XBT_VERB("Cannot read result of subcommand %s", subcmd);
314           strcpy(line_func, "???");
315         }
316         if (fgets(line_pos, 1024, subpipe)) {
317           line_pos[strlen(line_pos) - 1] = '\0';
318         } else {
319           XBT_VERB("Cannot read result of subcommand %s", subcmd);
320           strcpy(line_pos, backtrace_syms[i]);
321         }
322         pclose(subpipe);
323         free(subcmd);
324       }
325
326       /* check whether the trick worked */
327       if (strcmp("??", line_func)) {
328         XBT_DEBUG("Found dynamic symbol %s() at %s", line_func, line_pos);
329         e->bt_strings[i] =
330             bprintf("**   In %s() at %s", line_func, line_pos);
331       } else {
332         /* damn, nothing to do here. Let's print the raw address */
333         XBT_DEBUG("Dynamic symbol not found. Raw address = %s",
334                backtrace_syms[i]);
335         e->bt_strings[i] = bprintf("**   In ?? at %s", backtrace_syms[i]);
336       }
337
338     }
339     free(addrs[i]);
340
341     /* Mask the bottom of the stack */
342     if (!strncmp("main", line_func, strlen("main")) ||
343         !strncmp("xbt_thread_context_wrapper", line_func,
344                  strlen("xbt_thread_context_wrapper"))
345         || !strncmp("smx_ctx_sysv_wrapper", line_func,
346                     strlen("smx_ctx_sysv_wrapper"))) {
347       int j;
348
349       for (j = i + 1; j < e->used; j++)
350         free(addrs[j]);
351       e->used = i + 1;
352
353       if (!strncmp
354           ("xbt_thread_context_wrapper", line_func,
355            strlen("xbt_thread_context_wrapper"))) {
356         free(e->bt_strings[i]);
357         e->bt_strings[i] = xbt_strdup("**   (in a separate thread)");
358       }
359     }
360
361
362   }
363   pclose(pipe);
364   free(addrs);
365   free(backtrace_syms);
366   free(cmd);
367 }