Logo AND Algorithmique Numérique Distribuée

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