Logo AND Algorithmique Numérique Distribuée

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