Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines.
[simgrid.git] / src / xbt / backtrace.cpp
1 /* Copyright (c) 2005-2021. 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 public:
57   std::string resolve() const
58   {
59     std::stringstream ss;
60     ss << st;
61     return ss.str();
62   }
63 #else
64 public:
65   std::string resolve() const { return ""; } // fallback value
66 #endif
67 };
68
69 Backtrace::Backtrace() : impl_(std::make_shared<BacktraceImpl>()) {}
70
71 std::string Backtrace::resolve() const
72 {
73   return impl_->resolve();
74 }
75
76 void Backtrace::display() const
77 {
78   std::string backtrace = resolve();
79   std::fprintf(stderr, "Backtrace (displayed in actor %s):\n%s\n", xbt_procname(),
80                backtrace.empty() ? "(backtrace not set -- did you install Boost.Stacktrace?)" : backtrace.c_str());
81 }
82
83 } // namespace xbt
84 } // namespace simgrid