Logo AND Algorithmique Numérique Distribuée

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