Logo AND Algorithmique Numérique Distribuée

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