Logo AND Algorithmique Numérique Distribuée

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