Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
232e1f7a5d52809738ed9cc57b5059a05b4605fe
[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-2018. 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 <fstream>
12 #include <sstream>
13 #include <string>
14 #include <vector>
15
16 #include <boost/algorithm/string.hpp>
17
18 #include <unistd.h>
19 #include <execinfo.h>
20 #include <sys/stat.h>
21
22 /* 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 */
23 #include <xbt/string.hpp>
24 #include <xbt/backtrace.hpp>
25 #include "xbt/ex.h"
26 #include "xbt/log.h"
27 #include "xbt/module.h"         /* xbt_binary_name */
28 #include "src/xbt_modinter.h"       /* backtrace initialization headers */
29 #if SIMGRID_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 #include <unwind.h>
38 struct trace_arg {
39   void** array;
40   int cnt;
41   int size;
42 };
43
44 static _Unwind_Reason_Code backtrace_helper(_Unwind_Context* ctx, void* a)
45 {
46   trace_arg* arg = static_cast<trace_arg*>(a);
47
48   /* We are first called with address in the __backtrace function.
49      Skip it.  */
50   if (arg->cnt != -1)
51     {
52       arg->array[arg->cnt] = (void *) _Unwind_GetIP(ctx);
53
54       /* Check whether we make any progress.  */
55       if (arg->cnt > 0 && arg->array[arg->cnt - 1] == arg->array[arg->cnt])
56         return _URC_END_OF_STACK;
57     }
58   if (++arg->cnt == arg->size)
59     return _URC_END_OF_STACK;
60   return _URC_NO_REASON;
61 }
62
63 /** @brief reimplementation of glibc backtrace based directly on gcc library, without implicit malloc
64  *
65  * See http://people.irisa.fr/Martin.Quinson/blog/2012/0208/system_programming_fun_in_SimGrid/
66  * for the motivation behind this function
67  * */
68
69 int xbt_backtrace_no_malloc(void **array, int size) {
70   int i = 0;
71   for(i=0; i < size; i++)
72     array[i] = nullptr;
73
74   struct trace_arg arg;
75   arg .array = array;
76   arg.size = size;
77   arg.cnt = -1;
78
79   if (size >= 1)
80     _Unwind_Backtrace(backtrace_helper, &arg);
81
82   /* _Unwind_Backtrace on IA-64 seems to put nullptr address above
83      _start.  Fix it up here.  */
84   if (arg.cnt > 1 && arg.array[arg.cnt - 1] == nullptr)
85     --arg.cnt;
86   return arg.cnt != -1 ? arg.cnt : 0;
87 }
88
89 size_t xbt_backtrace_current(xbt_backtrace_location_t* loc, std::size_t count)
90 {
91   std::size_t used = backtrace(loc, count);
92   if (used == 0) {
93     std::fprintf(stderr, "The backtrace() function failed, which probably means that the memory is exhausted\n.");
94     std::fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory\n.");
95     std::fprintf(stderr, "Please go fix the memleaks\n");
96     std::exit(1);
97   }
98   return used;
99 }
100
101 namespace simgrid {
102 namespace xbt {
103
104 /** Find the path of the binary file from the name found in argv */
105 static std::string get_binary_path()
106 {
107   struct stat stat_buf;
108
109   if (xbt_binary_name == nullptr)
110     return "";
111
112   // We found it, we are happy:
113   if (stat(xbt_binary_name, &stat_buf) == 0)
114     return xbt_binary_name;
115
116   // Not found, look in the PATH:
117   char* path = getenv("PATH");
118   if (path == nullptr)
119     return "";
120   XBT_DEBUG("Looking in the PATH: %s\n", path);
121   std::vector<std::string> path_list;
122   // TODO, on Windows, this is ";"
123   boost::split(path_list, path, boost::is_any_of(":"));
124   for (std::string const& path_item : path_list) {
125     std::string binary_name = simgrid::xbt::string_printf(
126       "%s/%s", path_item.c_str(), xbt_binary_name);
127     bool found = (stat(binary_name.c_str(), &stat_buf) == 0);
128     XBT_DEBUG("Looked in the PATH for the binary. %s %s",
129       found ? "Found" : "Not found",
130       binary_name.c_str());
131     if (found)
132       return binary_name;
133   }
134
135   // Not found at all:
136   return "";
137 }
138
139 //FIXME: This code could be greatly improved/simplifyied with
140 //   http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
141 std::vector<std::string> resolve_backtrace(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   xbt_assert(pipe, "Cannot fork addr2line to display the backtrace");
190
191   /* To read the output of addr2line */
192   char line_func[1024];
193   char line_pos[1024];
194   for (std::size_t i = 0; i < count; i++) {
195     XBT_DEBUG("Looking for symbol %zu, 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 %zu, addr %s", i, addrs[i].c_str());
200       strncpy(line_func, "???", 4);
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 %zu, 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       unsigned long int offset = 0;
219       int found = 0;
220
221       /* let's look for the offset of this library in our addressing space */
222       std::string maps_name = std::string("/proc/") + std::to_string(getpid()) + "/maps";
223       std::ifstream maps(maps_name);
224       if (not maps) {
225         XBT_CRITICAL("open(\"%s\") failed: %s", maps_name.c_str(), strerror(errno));
226         continue;
227       }
228       size_t pos;
229       unsigned long int addr = std::stoul(addrs[i], &pos, 16);
230       if (pos != addrs[i].length()) {
231         XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)", addrs[i].c_str(), addr);
232       }
233       XBT_DEBUG("addr=%s (as string) =%#lx (as number)", addrs[i].c_str(), addr);
234
235       while (not found) {
236         unsigned long int first;
237         unsigned long int last;
238
239         std::string maps_buff;
240         if (not std::getline(maps, maps_buff))
241           break;
242         if (i == 0) {
243           XBT_DEBUG("map line: %s", maps_buff.c_str());
244         }
245         first = std::stoul(maps_buff, &pos, 16);
246         maps_buff.erase(0, pos + 1);
247         last = std::stoul(maps_buff, nullptr, 16);
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       maps.close();
258       addrs[i].clear();
259
260       if (not 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       std::string p(backtrace_syms[i]);
276       if (p[0] == '[') {
277         /* library path not displayed in the map file either... */
278         snprintf(line_func, 3, "??");
279       } else {
280         size_t p2 = p.find_first_of("( ");
281         if (p2 != std::string::npos)
282           p.erase(p2);
283
284         /* Here we go, fire an addr2line up */
285         std::string subcmd = std::string(ADDR2LINE) + " -f -e " + p + " " + addrs[i];
286         XBT_VERB("Fire another command: '%s'", subcmd.c_str());
287         FILE* subpipe = popen(subcmd.c_str(), "r");
288         if (not subpipe) {
289           xbt_die("Cannot fork addr2line to display the backtrace");
290         }
291         if (fgets(line_func, 1024, subpipe)) {
292           line_func[strlen(line_func) - 1] = '\0';
293         } else {
294           XBT_VERB("Cannot read result of subcommand %s", subcmd.c_str());
295           strncpy(line_func, "???", 4);
296         }
297         if (fgets(line_pos, 1024, subpipe)) {
298           line_pos[strlen(line_pos) - 1] = '\0';
299         } else {
300           XBT_VERB("Cannot read result of subcommand %s", subcmd.c_str());
301           strncpy(line_pos, backtrace_syms[i],1024);
302         }
303         pclose(subpipe);
304       }
305
306       /* check whether the trick worked */
307       if (strcmp("??", line_func)) {
308         auto name = simgrid::xbt::demangle(line_func);
309         XBT_DEBUG("Found dynamic symbol %s at %s", name.get(), line_pos);
310         result.push_back(simgrid::xbt::string_printf(
311           "%s at %s, %p", name.get(), line_pos, loc[i]));
312       } else {
313         /* damn, nothing to do here. Let's print the raw address */
314         XBT_DEBUG("Dynamic symbol not found. Raw address = %s", backtrace_syms[i]);
315         result.push_back(simgrid::xbt::string_printf(
316           "?? at %s", backtrace_syms[i]));
317       }
318     }
319     addrs[i].clear();
320
321     /* Mask the bottom of the stack */
322     const char* const breakers[] = {
323         "main",
324         "_ZN7simgrid6kernel7context13ThreadContext7wrapperE", // simgrid::kernel::context::ThreadContext::wrapper
325         "_ZN7simgrid6kernel7context8UContext7wrapperE"        // simgrid::kernel::context::UContext::wrapper
326     };
327     bool do_break = false;
328     for (const char* b : breakers) {
329       if (strncmp(b, line_func, strlen(b)) == 0) {
330         do_break = true;
331         break;
332       }
333     }
334     if (do_break)
335       break;
336   }
337   pclose(pipe);
338   free(backtrace_syms);
339   return result;
340 }
341
342 }
343 }
344
345 #if SIMGRID_HAVE_MC
346 int xbt_libunwind_backtrace(void** bt, int size){
347   for (int i = 0; i < size; i++)
348     bt[i] = nullptr;
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_step(&c);
357
358   int i;
359   for (i = 0; unw_step(&c) >= 0 && i < size; i++) {
360     unw_word_t ip;
361     unw_get_reg(&c, UNW_REG_IP, &ip);
362     bt[i] = (void*)(long)ip;
363   }
364
365   return i;
366 }
367 #endif