Logo AND Algorithmique Numérique Distribuée

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