Logo AND Algorithmique Numérique Distribuée

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