Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
this is definitely a backtrace function
[simgrid.git] / src / xbt / backtrace.cpp
1 /* Copyright (c) 2005-2016. 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 <cstddef>
7 #include <cstdlib>
8
9 #include <vector>
10
11 // Try to detect and use the C++ intanium ABI for name demangling:
12 #ifdef __GXX_ABI_VERSION
13 #include <cxxabi.h>
14 #endif
15
16 #include "simgrid/simix.h" /* SIMIX_process_self_get_name() */
17 #include <xbt/backtrace.h>
18 #include <xbt/backtrace.hpp>
19 #include <xbt/log.h>
20 #include <xbt/sysdep.h>
21
22 #include "src/internal_config.h"
23
24 extern "C" {
25
26 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_backtrace, xbt, "Backtrace");
27
28 }
29
30 void xbt_backtrace_display(xbt_backtrace_location_t* loc, std::size_t count)
31 {
32 #ifdef HAVE_BACKTRACE
33   std::vector<std::string> backtrace = simgrid::xbt::resolveBacktrace(loc, count);
34   if (backtrace.empty()) {
35     fprintf(stderr, "(backtrace not set)\n");
36     return;
37   }
38   fprintf(stderr, "Backtrace (displayed in process %s):\n", SIMIX_process_self_get_name());
39   for (std::string const& s : backtrace)
40     fprintf(stderr, "---> %s\n", s.c_str());
41 #else
42   XBT_ERROR("Cannot display backtrace when compiled without libunwind.");
43 #endif
44 }
45
46 /** @brief show the backtrace of the current point (lovely while debugging) */
47 void xbt_backtrace_display_current()
48 {
49   const std::size_t size = 10;
50   xbt_backtrace_location_t bt[size];
51   size_t used = xbt_backtrace_current(bt, size);
52   xbt_backtrace_display(bt, used);
53 }
54
55 namespace simgrid {
56 namespace xbt {
57
58 std::unique_ptr<char, void(*)(void*)> demangle(const char* name)
59 {
60 #ifdef __GXX_ABI_VERSION
61   int status;
62   auto res = std::unique_ptr<char, void(*)(void*)>(
63     abi::__cxa_demangle(name, nullptr, nullptr, &status),
64     std::free
65   );
66   if (res != nullptr)
67     return res;
68   // We did not manage to resolve this. Probably because this is not a mangled symbol:
69 #endif
70   // Return the symbol:
71   return std::unique_ptr<char, void(*)(void*)>(xbt_strdup(name), std::free);
72 }
73
74 std::vector<xbt_backtrace_location_t> backtrace()
75 {
76   const std::size_t size = 10;
77   xbt_backtrace_location_t loc[size];
78   size_t used = xbt_backtrace_current(loc, size);
79   return std::vector<xbt_backtrace_location_t>(loc, loc + used);
80 }
81
82 }
83 }
84
85 #if HAVE_BACKTRACE && HAVE_EXECINFO_H && HAVE_POPEN && defined(ADDR2LINE)
86 # include "src/xbt/backtrace_linux.cpp"
87 #else
88 # include "src/xbt/backtrace_dummy.cpp"
89 #endif