Logo AND Algorithmique Numérique Distribuée

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