Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Hide the backtrace implementation in a private pimpl
[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 namespace simgrid {
66 namespace xbt {
67
68 std::unique_ptr<char, void(*)(void*)> demangle(const char* name)
69 {
70 #ifdef __GXX_ABI_VERSION
71   int status;
72   auto res = std::unique_ptr<char, void(*)(void*)>(
73     abi::__cxa_demangle(name, nullptr, nullptr, &status),
74     std::free
75   );
76   if (res != nullptr)
77     return res;
78   // We did not manage to resolve this. Probably because this is not a mangled symbol:
79 #endif
80   // Return the symbol:
81   return std::unique_ptr<char, void(*)(void*)>(xbt_strdup(name), std::free);
82 }
83
84 class BacktraceImpl {
85   short refcount_ = 1;
86
87 public:
88   void ref() { refcount_++; }
89   bool unref()
90   {
91     refcount_--;
92     return refcount_ == 0;
93   }
94 #if HAVE_BACKTRACE
95   std::vector<void*> frames;
96 #endif
97 };
98
99 Backtrace::Backtrace()
100 {
101 #if HAVE_BACKTRACE
102   impl_ = new BacktraceImpl();
103   impl_->frames.resize(15);
104   int used = backtrace(impl_->frames.data(), impl_->frames.size());
105   if (used == 0) {
106     std::fprintf(stderr, "The backtrace() function failed, which probably means that the memory is exhausted\n.");
107     std::fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory\n.");
108     std::fprintf(stderr, "Please go fix the memleaks\n");
109     std::exit(1);
110   }
111   impl_->frames.shrink_to_fit();
112 #endif
113 }
114 Backtrace::Backtrace(const Backtrace& bt)
115 {
116   impl_ = bt.impl_;
117   impl_->ref();
118 }
119
120 Backtrace::~Backtrace()
121 {
122   if (impl_->unref()) {
123 #if HAVE_BACKTRACE
124     delete impl_;
125 #endif
126   }
127 }
128 } // namespace xbt
129 } // namespace simgrid
130
131 namespace simgrid {
132 namespace xbt {
133
134 /** Find the path of the binary file from the name found in argv */
135 static std::string get_binary_path()
136 {
137   struct stat stat_buf;
138
139   if (xbt_binary_name == nullptr)
140     return "";
141
142   // We found it, we are happy:
143   if (stat(xbt_binary_name, &stat_buf) == 0)
144     return xbt_binary_name;
145
146   // Not found, look in the PATH:
147   char* path = getenv("PATH");
148   if (path == nullptr)
149     return "";
150
151   XBT_DEBUG("Looking in the PATH: %s\n", path);
152   std::vector<std::string> path_list;
153   boost::split(path_list, path, boost::is_any_of(":;"));
154
155   for (std::string const& path_item : path_list) {
156     std::string binary_name = simgrid::xbt::string_printf("%s/%s", path_item.c_str(), xbt_binary_name);
157     bool found              = (stat(binary_name.c_str(), &stat_buf) == 0);
158     XBT_DEBUG("Looked in the PATH for the binary. %s %s", found ? "Found" : "Not found", binary_name.c_str());
159     if (found)
160       return binary_name;
161   }
162
163   // Not found at all:
164   return "";
165 }
166
167 std::vector<std::string> resolve_backtrace(const Backtrace& bt)
168 {
169   std::vector<std::string> result;
170
171 #if HAVE_BACKTRACE && HAVE_EXECINFO_H && HAVE_POPEN && defined(ADDR2LINE)
172   // FIXME: This code could be greatly improved/simplified with
173   //   http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
174   if (bt.impl_->frames.size() == 0)
175     return result;
176
177   if (xbt_binary_name == nullptr)
178     XBT_WARN("XBT not initialized, the backtrace will not be resolved.");
179
180   char** backtrace_syms   = backtrace_symbols(bt.impl_->frames.data(), bt.impl_->frames.size());
181   std::string binary_name = get_binary_path();
182
183   if (binary_name.empty()) {
184     for (std::size_t i = 1; i < bt.impl_->frames.size(); i++) // the first one is not interesting
185       result.push_back(simgrid::xbt::string_printf("%p", bt.impl_->frames[i]));
186     return result;
187   }
188
189   // Create the system command for add2line:
190   std::ostringstream stream;
191   stream << ADDR2LINE << " -f -e " << binary_name << ' ';
192   std::vector<std::string> addrs(bt.impl_->frames.size());
193   for (std::size_t i = 1; i < bt.impl_->frames.size(); i++) { // the first one is not interesting
194     /* retrieve this address */
195     XBT_DEBUG("Retrieving address number %zu from '%s'", i, backtrace_syms[i]);
196     char buff[256];
197     snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
198     char* p = strchr(buff, ']');
199     *p      = '\0';
200     if (strcmp(buff, "(nil)"))
201       addrs[i] = buff;
202     else
203       addrs[i] = "0x0";
204     XBT_DEBUG("Set up a new address: %zu, '%s'", i, addrs[i].c_str());
205     /* Add it to the command line args */
206     stream << addrs[i] << ' ';
207   }
208   std::string cmd = stream.str();
209
210   /* size (in char) of pointers on this arch */
211   int addr_len = addrs[0].size();
212
213   XBT_VERB("Fire a first command: '%s'", cmd.c_str());
214   FILE* pipe = popen(cmd.c_str(), "r");
215   xbt_assert(pipe, "Cannot fork addr2line to display the backtrace");
216
217   /* To read the output of addr2line */
218   char line_func[1024];
219   char line_pos[1024];
220   for (std::size_t i = 1; i < bt.impl_->frames.size(); i++) { // The first one is not interesting
221     XBT_DEBUG("Looking for symbol %zu, addr = '%s'", i, addrs[i].c_str());
222     if (fgets(line_func, 1024, pipe)) {
223       line_func[strlen(line_func) - 1] = '\0';
224     } else {
225       XBT_VERB("Cannot run fgets to look for symbol %zu, addr %s", i, addrs[i].c_str());
226       strncpy(line_func, "???", 4);
227     }
228     if (fgets(line_pos, 1024, pipe)) {
229       line_pos[strlen(line_pos) - 1] = '\0';
230     } else {
231       XBT_VERB("Cannot run fgets to look for symbol %zu, addr %s", i, addrs[i].c_str());
232       strncpy(line_pos, backtrace_syms[i], 1024);
233     }
234
235     if (strcmp("??", line_func) != 0) {
236       auto name = simgrid::xbt::demangle(line_func);
237       XBT_DEBUG("Found static symbol %s at %s", name.get(), line_pos);
238       result.push_back(simgrid::xbt::string_printf("%s at %s, %p", name.get(), line_pos, bt.impl_->frames[i]));
239     } else {
240       /* Damn. The symbol is in a dynamic library. Let's get wild */
241
242       unsigned long int offset = 0;
243       int found                = 0;
244
245       /* let's look for the offset of this library in our addressing space */
246       std::string maps_name = std::string("/proc/") + std::to_string(getpid()) + "/maps";
247       std::ifstream maps(maps_name);
248       if (not maps) {
249         XBT_CRITICAL("open(\"%s\") failed: %s", maps_name.c_str(), strerror(errno));
250         continue;
251       }
252       size_t pos;
253       unsigned long int addr = std::stoul(addrs[i], &pos, 16);
254       if (pos != addrs[i].length()) {
255         XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)", addrs[i].c_str(), addr);
256       }
257       XBT_DEBUG("addr=%s (as string) =%#lx (as number)", addrs[i].c_str(), addr);
258
259       while (not found) {
260         unsigned long int first;
261         unsigned long int last;
262
263         std::string maps_buff;
264         if (not std::getline(maps, maps_buff))
265           break;
266         if (i == 0) {
267           XBT_DEBUG("map line: %s", maps_buff.c_str());
268         }
269         first = std::stoul(maps_buff, &pos, 16);
270         maps_buff.erase(0, pos + 1);
271         last = std::stoul(maps_buff, nullptr, 16);
272         if (first < addr && addr < last) {
273           offset = first;
274           found  = 1;
275         }
276         if (found) {
277           XBT_DEBUG("%#lx in [%#lx-%#lx]", addr, first, last);
278           XBT_DEBUG("Symbol found, map lines not further displayed (even if looking for next ones)");
279         }
280       }
281       maps.close();
282       addrs[i].clear();
283
284       if (not found) {
285         XBT_VERB("Problem while reading the maps file. Following backtrace will be mangled.");
286         XBT_DEBUG("No dynamic. Static symbol: %s", backtrace_syms[i]);
287         result.push_back(simgrid::xbt::string_printf("?? (%s)", backtrace_syms[i]));
288         continue;
289       }
290
291       /* Ok, Found the offset of the maps line containing the searched symbol.
292          We now need to substract this from the address we got from backtrace.
293        */
294
295       addrs[i] = simgrid::xbt::string_printf("0x%0*lx", addr_len - 2, addr - offset);
296       XBT_DEBUG("offset=%#lx new addr=%s", offset, addrs[i].c_str());
297
298       /* Got it. We have our new address. Let's get the library path and we are set */
299       std::string p(backtrace_syms[i]);
300       if (p[0] == '[') {
301         /* library path not displayed in the map file either... */
302         snprintf(line_func, 3, "??");
303       } else {
304         size_t p2 = p.find_first_of("( ");
305         if (p2 != std::string::npos)
306           p.erase(p2);
307
308         /* Here we go, fire an addr2line up */
309         std::string subcmd = std::string(ADDR2LINE) + " -f -e " + p + " " + addrs[i];
310         XBT_VERB("Fire another command: '%s'", subcmd.c_str());
311         FILE* subpipe = popen(subcmd.c_str(), "r");
312         if (not subpipe) {
313           xbt_die("Cannot fork addr2line to display the backtrace");
314         }
315         if (fgets(line_func, 1024, subpipe)) {
316           line_func[strlen(line_func) - 1] = '\0';
317         } else {
318           XBT_VERB("Cannot read result of subcommand %s", subcmd.c_str());
319           strncpy(line_func, "???", 4);
320         }
321         if (fgets(line_pos, 1024, subpipe)) {
322           line_pos[strlen(line_pos) - 1] = '\0';
323         } else {
324           XBT_VERB("Cannot read result of subcommand %s", subcmd.c_str());
325           strncpy(line_pos, backtrace_syms[i], 1024);
326         }
327         pclose(subpipe);
328       }
329
330       /* check whether the trick worked */
331       if (strcmp("??", line_func)) {
332         auto name = simgrid::xbt::demangle(line_func);
333         XBT_DEBUG("Found dynamic symbol %s at %s", name.get(), line_pos);
334         result.push_back(simgrid::xbt::string_printf("%s at %s, %p", name.get(), line_pos, bt.impl_->frames[i]));
335       } else {
336         /* damn, nothing to do here. Let's print the raw address */
337         XBT_DEBUG("Dynamic symbol not found. Raw address = %s", backtrace_syms[i]);
338         result.push_back(simgrid::xbt::string_printf("?? at %s", backtrace_syms[i]));
339       }
340     }
341     addrs[i].clear();
342
343     /* Mask the bottom of the stack */
344     const char* const breakers[] = {
345         "main",
346         "_ZN7simgrid6kernel7context13ThreadContext7wrapperE", // simgrid::kernel::context::ThreadContext::wrapper
347         "_ZN7simgrid6kernel7context8UContext7wrapperE"        // simgrid::kernel::context::UContext::wrapper
348     };
349     bool do_break = false;
350     for (const char* b : breakers) {
351       if (strncmp(b, line_func, strlen(b)) == 0) {
352         do_break = true;
353         break;
354       }
355     }
356     if (do_break)
357       break;
358   }
359   pclose(pipe);
360   xbt_free(backtrace_syms);
361 #endif /* ADDR2LINE usable to resolve the backtrace */
362   return result;
363 }
364
365 } // namespace xbt
366 } // namespace simgrid