Logo AND Algorithmique Numérique Distribuée

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