Logo AND Algorithmique Numérique Distribuée

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