Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Hide the content of a simgrid::xbt::Backtrace and inline a function
[simgrid.git] / src / xbt / backtrace.cpp
1 /* Copyright (c) 2005-2018. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "src/internal_config.h"
7
8 #include <cstddef>
9 #include <cstdlib>
10 #include <cstring>
11 #include <fstream>
12 #include <sstream>
13 #include <sys/stat.h>
14 #include <vector>
15
16 #include <boost/algorithm/string.hpp>
17
18 // Try to detect and use the C++ itanium ABI for name demangling:
19 #ifdef __GXX_ABI_VERSION
20 #include <cxxabi.h>
21 #endif
22 #if HAVE_EXECINFO_H
23 #include <execinfo.h>
24 #endif
25
26 #include "simgrid/simix.h" /* SIMIX_process_self_get_name() */
27 #include <xbt/backtrace.hpp>
28 #include <xbt/log.h>
29 #include <xbt/string.hpp>
30 #include <xbt/sysdep.h>
31
32 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_backtrace, xbt, "Backtrace");
33
34 static bool startWith(std::string str, const char* prefix)
35 {
36   return strncmp(str.c_str(), prefix, strlen(prefix)) == 0;
37 }
38
39 void xbt_backtrace_display(const simgrid::xbt::Backtrace& bt)
40 {
41   std::vector<std::string> backtrace = simgrid::xbt::resolve_backtrace(bt);
42   if (backtrace.empty()) {
43     fprintf(stderr, "(backtrace not set -- maybe unavailable on this architecture?)\n");
44     return;
45   }
46   fprintf(stderr, "Backtrace (displayed in process %s):\n", SIMIX_process_self_get_name());
47   for (std::string const& s : backtrace) {
48     if (startWith(s, "xbt_backtrace_display_current"))
49       continue;
50
51     std::fprintf(stderr, "---> '%s'\n", s.c_str());
52     if (startWith(s, "SIMIX_simcall_handle") ||
53         startWith(s, "simgrid::xbt::MainFunction") /* main used with thread factory */)
54       break;
55   }
56 }
57
58 /** @brief show the backtrace of the current point (lovely while debugging) */
59 void xbt_backtrace_display_current()
60 {
61   simgrid::xbt::Backtrace bt = simgrid::xbt::backtrace();
62   xbt_backtrace_display(bt);
63 }
64
65 #if HAVE_BACKTRACE
66 // For some reason, if I try to use it directly, GCC thinks I try to use xbt::backtrace.
67 // I suspect that this symbol is not presented as a regular function in execinfo.h
68 static int gnu_backtrace(simgrid::xbt::Backtrace& bt)
69 {
70   return backtrace(bt.data(), bt.size());
71 }
72 #endif
73
74 namespace simgrid {
75 namespace xbt {
76
77 std::unique_ptr<char, void(*)(void*)> demangle(const char* name)
78 {
79 #ifdef __GXX_ABI_VERSION
80   int status;
81   auto res = std::unique_ptr<char, void(*)(void*)>(
82     abi::__cxa_demangle(name, nullptr, nullptr, &status),
83     std::free
84   );
85   if (res != nullptr)
86     return res;
87   // We did not manage to resolve this. Probably because this is not a mangled symbol:
88 #endif
89   // Return the symbol:
90   return std::unique_ptr<char, void(*)(void*)>(xbt_strdup(name), std::free);
91 }
92
93 Backtrace backtrace()
94 {
95   simgrid::xbt::Backtrace res;
96 #if HAVE_BACKTRACE
97   res.resize(15);
98   int used = gnu_backtrace(res);
99   if (used == 0) {
100     std::fprintf(stderr, "The backtrace() function failed, which probably means that the memory is exhausted\n.");
101     std::fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory\n.");
102     std::fprintf(stderr, "Please go fix the memleaks\n");
103     std::exit(1);
104   }
105   res.shrink_to_fit();
106 #endif
107   return res;
108 }
109
110 } // namespace xbt
111 } // namespace simgrid
112
113 namespace simgrid {
114 namespace xbt {
115
116 /** Find the path of the binary file from the name found in argv */
117 static std::string get_binary_path()
118 {
119   struct stat stat_buf;
120
121   if (xbt_binary_name == nullptr)
122     return "";
123
124   // We found it, we are happy:
125   if (stat(xbt_binary_name, &stat_buf) == 0)
126     return xbt_binary_name;
127
128   // Not found, look in the PATH:
129   char* path = getenv("PATH");
130   if (path == nullptr)
131     return "";
132
133   XBT_DEBUG("Looking in the PATH: %s\n", path);
134   std::vector<std::string> path_list;
135   boost::split(path_list, path, boost::is_any_of(":;"));
136
137   for (std::string const& path_item : path_list) {
138     std::string binary_name = simgrid::xbt::string_printf("%s/%s", path_item.c_str(), xbt_binary_name);
139     bool found              = (stat(binary_name.c_str(), &stat_buf) == 0);
140     XBT_DEBUG("Looked in the PATH for the binary. %s %s", found ? "Found" : "Not found", binary_name.c_str());
141     if (found)
142       return binary_name;
143   }
144
145   // Not found at all:
146   return "";
147 }
148
149 std::vector<std::string> resolve_backtrace(const Backtrace& bt)
150 {
151   std::vector<std::string> result;
152
153 #if HAVE_BACKTRACE && HAVE_EXECINFO_H && HAVE_POPEN && defined(ADDR2LINE)
154   // FIXME: This code could be greatly improved/simplified with
155   //   http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
156   if (bt.size() == 0)
157     return result;
158
159   if (xbt_binary_name == nullptr)
160     XBT_WARN("XBT not initialized, the backtrace will not be resolved.");
161
162   char** backtrace_syms   = backtrace_symbols(bt.data(), bt.size());
163   std::string binary_name = get_binary_path();
164
165   if (binary_name.empty()) {
166     for (std::size_t i = 1; i < bt.size(); i++) // the first one is not interesting
167       result.push_back(simgrid::xbt::string_printf("%p", bt[i]));
168     return result;
169   }
170
171   // Create the system command for add2line:
172   std::ostringstream stream;
173   stream << ADDR2LINE << " -f -e " << binary_name << ' ';
174   std::vector<std::string> addrs(bt.size());
175   for (std::size_t i = 1; i < bt.size(); i++) { // the first one is not interesting
176     /* retrieve this address */
177     XBT_DEBUG("Retrieving address number %zu from '%s'", i, backtrace_syms[i]);
178     char buff[256];
179     snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
180     char* p = strchr(buff, ']');
181     *p      = '\0';
182     if (strcmp(buff, "(nil)"))
183       addrs[i] = buff;
184     else
185       addrs[i] = "0x0";
186     XBT_DEBUG("Set up a new address: %zu, '%s'", i, addrs[i].c_str());
187     /* Add it to the command line args */
188     stream << addrs[i] << ' ';
189   }
190   std::string cmd = stream.str();
191
192   /* size (in char) of pointers on this arch */
193   int addr_len = addrs[0].size();
194
195   XBT_VERB("Fire a first command: '%s'", cmd.c_str());
196   FILE* pipe = popen(cmd.c_str(), "r");
197   xbt_assert(pipe, "Cannot fork addr2line to display the backtrace");
198
199   /* To read the output of addr2line */
200   char line_func[1024];
201   char line_pos[1024];
202   for (std::size_t i = 1; i < bt.size(); i++) { // The first one is not interesting
203     XBT_DEBUG("Looking for symbol %zu, addr = '%s'", i, addrs[i].c_str());
204     if (fgets(line_func, 1024, pipe)) {
205       line_func[strlen(line_func) - 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_func, "???", 4);
209     }
210     if (fgets(line_pos, 1024, pipe)) {
211       line_pos[strlen(line_pos) - 1] = '\0';
212     } else {
213       XBT_VERB("Cannot run fgets to look for symbol %zu, addr %s", i, addrs[i].c_str());
214       strncpy(line_pos, backtrace_syms[i], 1024);
215     }
216
217     if (strcmp("??", line_func) != 0) {
218       auto name = simgrid::xbt::demangle(line_func);
219       XBT_DEBUG("Found static symbol %s at %s", name.get(), line_pos);
220       result.push_back(simgrid::xbt::string_printf("%s at %s, %p", name.get(), line_pos, bt[i]));
221     } else {
222       /* Damn. The symbol is in a dynamic library. Let's get wild */
223
224       unsigned long int offset = 0;
225       int found                = 0;
226
227       /* let's look for the offset of this library in our addressing space */
228       std::string maps_name = std::string("/proc/") + std::to_string(getpid()) + "/maps";
229       std::ifstream maps(maps_name);
230       if (not maps) {
231         XBT_CRITICAL("open(\"%s\") failed: %s", maps_name.c_str(), strerror(errno));
232         continue;
233       }
234       size_t pos;
235       unsigned long int addr = std::stoul(addrs[i], &pos, 16);
236       if (pos != addrs[i].length()) {
237         XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)", addrs[i].c_str(), addr);
238       }
239       XBT_DEBUG("addr=%s (as string) =%#lx (as number)", addrs[i].c_str(), addr);
240
241       while (not found) {
242         unsigned long int first;
243         unsigned long int last;
244
245         std::string maps_buff;
246         if (not std::getline(maps, maps_buff))
247           break;
248         if (i == 0) {
249           XBT_DEBUG("map line: %s", maps_buff.c_str());
250         }
251         first = std::stoul(maps_buff, &pos, 16);
252         maps_buff.erase(0, pos + 1);
253         last = std::stoul(maps_buff, nullptr, 16);
254         if (first < addr && addr < last) {
255           offset = first;
256           found  = 1;
257         }
258         if (found) {
259           XBT_DEBUG("%#lx in [%#lx-%#lx]", addr, first, last);
260           XBT_DEBUG("Symbol found, map lines not further displayed (even if looking for next ones)");
261         }
262       }
263       maps.close();
264       addrs[i].clear();
265
266       if (not found) {
267         XBT_VERB("Problem while reading the maps file. Following backtrace will be mangled.");
268         XBT_DEBUG("No dynamic. Static symbol: %s", backtrace_syms[i]);
269         result.push_back(simgrid::xbt::string_printf("?? (%s)", backtrace_syms[i]));
270         continue;
271       }
272
273       /* Ok, Found the offset of the maps line containing the searched symbol.
274          We now need to substract this from the address we got from backtrace.
275        */
276
277       addrs[i] = simgrid::xbt::string_printf("0x%0*lx", addr_len - 2, addr - offset);
278       XBT_DEBUG("offset=%#lx new addr=%s", offset, addrs[i].c_str());
279
280       /* Got it. We have our new address. Let's get the library path and we are set */
281       std::string p(backtrace_syms[i]);
282       if (p[0] == '[') {
283         /* library path not displayed in the map file either... */
284         snprintf(line_func, 3, "??");
285       } else {
286         size_t p2 = p.find_first_of("( ");
287         if (p2 != std::string::npos)
288           p.erase(p2);
289
290         /* Here we go, fire an addr2line up */
291         std::string subcmd = std::string(ADDR2LINE) + " -f -e " + p + " " + addrs[i];
292         XBT_VERB("Fire another command: '%s'", subcmd.c_str());
293         FILE* subpipe = popen(subcmd.c_str(), "r");
294         if (not 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.c_str());
301           strncpy(line_func, "???", 4);
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.c_str());
307           strncpy(line_pos, backtrace_syms[i], 1024);
308         }
309         pclose(subpipe);
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("%s at %s, %p", name.get(), line_pos, bt[i]));
317       } else {
318         /* damn, nothing to do here. Let's print the raw address */
319         XBT_DEBUG("Dynamic symbol not found. Raw address = %s", backtrace_syms[i]);
320         result.push_back(simgrid::xbt::string_printf("?? at %s", backtrace_syms[i]));
321       }
322     }
323     addrs[i].clear();
324
325     /* Mask the bottom of the stack */
326     const char* const breakers[] = {
327         "main",
328         "_ZN7simgrid6kernel7context13ThreadContext7wrapperE", // simgrid::kernel::context::ThreadContext::wrapper
329         "_ZN7simgrid6kernel7context8UContext7wrapperE"        // simgrid::kernel::context::UContext::wrapper
330     };
331     bool do_break = false;
332     for (const char* b : breakers) {
333       if (strncmp(b, line_func, strlen(b)) == 0) {
334         do_break = true;
335         break;
336       }
337     }
338     if (do_break)
339       break;
340   }
341   pclose(pipe);
342   xbt_free(backtrace_syms);
343 #endif /* ADDR2LINE usable to resolve the backtrace */
344   return result;
345 }
346
347 } // namespace xbt
348 } // namespace simgrid