Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'pikachuyann/simgrid-xbt_random'
[simgrid.git] / src / xbt / backtrace.cpp
1 /* Copyright (c) 2005-2020. 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 <xbt/backtrace.hpp>
9 #include <xbt/string.hpp>
10 #include <xbt/sysdep.h>
11 #include <xbt/virtu.h>
12
13 #include <cstdio>
14 #include <cstdlib>
15 #include <sstream>
16
17 // Try to detect and use the C++ itanium ABI for name demangling:
18 #ifdef __GXX_ABI_VERSION
19 #include <cxxabi.h>
20 #endif
21
22 #if HAVE_BOOST_STACKTRACE_BACKTRACE
23 #define BOOST_STACKTRACE_USE_BACKTRACE
24 #include <boost/stacktrace.hpp>
25 #elif HAVE_BOOST_STACKTRACE_ADDR2LINE
26 #define BOOST_STACKTRACE_USE_ADDR2LINE
27 #include <boost/stacktrace.hpp>
28 #endif
29
30 /** @brief show the backtrace of the current point (lovely while debugging) */
31 void xbt_backtrace_display_current()
32 {
33   simgrid::xbt::Backtrace().display();
34 }
35
36 namespace simgrid {
37 namespace xbt {
38
39 std::unique_ptr<char, std::function<void(char*)>> demangle(const char* name)
40 {
41 #ifdef __GXX_ABI_VERSION
42   int status;
43   std::unique_ptr<char, std::function<void(char*)>> res(abi::__cxa_demangle(name, nullptr, nullptr, &status),
44                                                         &std::free);
45   if (res != nullptr)
46     return res;
47   // We did not manage to resolve this. Probably because this is not a mangled symbol:
48 #endif
49   // Return the symbol:
50   return std::unique_ptr<char, std::function<void(char*)>>(xbt_strdup(name), &xbt_free_f);
51 }
52
53 class BacktraceImpl {
54 #if HAVE_BOOST_STACKTRACE_BACKTRACE || HAVE_BOOST_STACKTRACE_ADDR2LINE
55   const boost::stacktrace::stacktrace st = boost::stacktrace::stacktrace();
56 #else
57   const char st[1] = ""; // fallback value
58 #endif
59 public:
60   std::string resolve() const
61   {
62     std::stringstream ss;
63     ss << st;
64     return ss.str();
65   }
66 };
67
68 Backtrace::Backtrace() : impl_(std::make_shared<BacktraceImpl>()) {}
69
70 std::string Backtrace::resolve() const
71 {
72   return impl_->resolve();
73 }
74
75 void Backtrace::display() const
76 {
77   std::string backtrace = resolve();
78   std::fprintf(stderr, "Backtrace (displayed in actor %s):\n%s\n", xbt_procname(),
79                backtrace.empty() ? "(backtrace not set -- did you install Boost.Stacktrace?)" : backtrace.c_str());
80 }
81
82 } // namespace xbt
83 } // namespace simgrid