Logo AND Algorithmique Numérique Distribuée

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