Logo AND Algorithmique Numérique Distribuée

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