Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2022.
[simgrid.git] / src / xbt / backtrace.cpp
1 /* Copyright (c) 2005-2022. 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 #if HAVE_BOOST_STACKTRACE_BACKTRACE
18 #define BOOST_STACKTRACE_USE_BACKTRACE
19 #include <boost/stacktrace.hpp>
20 #include <boost/stacktrace/detail/frame_decl.hpp>
21 #elif HAVE_BOOST_STACKTRACE_ADDR2LINE
22 #define BOOST_STACKTRACE_USE_ADDR2LINE
23 #include <boost/stacktrace.hpp>
24 #include <boost/stacktrace/detail/frame_decl.hpp>
25 #endif
26
27 /** @brief show the backtrace of the current point (lovely while debugging) */
28 void xbt_backtrace_display_current()
29 {
30   simgrid::xbt::Backtrace().display();
31 }
32
33 namespace simgrid {
34 namespace xbt {
35
36 class BacktraceImpl {
37 #if HAVE_BOOST_STACKTRACE_BACKTRACE || HAVE_BOOST_STACKTRACE_ADDR2LINE
38   const boost::stacktrace::stacktrace st;
39
40 public:
41   std::string resolve() const
42   {
43     std::stringstream ss;
44
45     int frame_count = 0;
46     bool print      = false;
47
48     for (boost::stacktrace::frame const& frame : st) {
49       const std::string frame_name = frame.name();
50       if (print) {
51         if (frame_name.rfind("simgrid::xbt::MainFunction", 0) == 0 ||
52             frame_name.rfind("simgrid::kernel::context::Context::operator()()", 0) == 0)
53           break;
54         ss << "  ->  " << frame_count++ << "# " << frame << "\n";
55         if (frame_name == "main")
56           break;
57       } else {
58         if (frame_name == "simgrid::xbt::Backtrace::Backtrace()")
59           print = true;
60       }
61     }
62
63     return ss.str();
64   }
65 #else
66
67 public:
68   std::string resolve() const { return ""; } // fallback value
69 #endif
70 };
71
72 Backtrace::Backtrace() : impl_(std::make_shared<BacktraceImpl>()) {}
73
74 std::string Backtrace::resolve() const
75 {
76   return impl_->resolve();
77 }
78
79 void Backtrace::display() const
80 {
81   std::string backtrace = resolve();
82   std::fprintf(stderr, "Backtrace (displayed in actor %s):\n%s\n", xbt_procname(),
83                backtrace.empty() ? "(backtrace not set -- did you install Boost.Stacktrace?)" : backtrace.c_str());
84 }
85
86 } // namespace xbt
87 } // namespace simgrid