Logo AND Algorithmique Numérique Distribuée

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