Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Make the future simgrid::*Exception inherit of legacy xbt_ex
[simgrid.git] / src / xbt / exception.cpp
1 /* Copyright (c) 2005-2018. 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 <cstdlib>
7
8 #include <atomic>
9 #include <exception>
10 #include <string>
11 #include <typeinfo>
12 #include <vector>
13 #include <memory>
14 #include <mutex>
15
16 #include "simgrid/Exception.hpp"
17 #include <xbt/backtrace.hpp>
18 #include <xbt/config.hpp>
19 #include <xbt/log.h>
20 #include <xbt/log.hpp>
21
22 XBT_LOG_EXTERNAL_CATEGORY(xbt);
23 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_exception, xbt, "Exceptions");
24
25 // DO NOT define ~xbt_ex() in exception.hpp.
26 // Defining it here ensures that xbt_ex is defined only in libsimgrid, but not in libsimgrid-java.
27 // Doing otherwise naturally breaks things (at least on freebsd with clang).
28
29 xbt_ex::~xbt_ex() = default;
30
31 void _xbt_throw(char* message, xbt_errcat_t errcat, int value, const char* file, int line, const char* func)
32 {
33   xbt_ex e(simgrid::xbt::ThrowPoint(file, line, func, simgrid::xbt::backtrace(), xbt_procname(), xbt_getpid()),
34            message);
35   xbt_free(message);
36   e.category = errcat;
37   e.value    = value;
38   throw e;
39 }
40
41 /** @brief shows an exception content and the associated stack if available */
42 void xbt_ex_display(xbt_ex_t* e)
43 {
44   simgrid::xbt::log_exception(xbt_log_priority_critical, "UNCAUGHT EXCEPTION", *e);
45 }
46
47 /** @brief returns a short name for the given exception category */
48 const char* xbt_ex_catname(xbt_errcat_t cat)
49 {
50   switch (cat) {
51     case unknown_error:
52       return "unknown error";
53     case arg_error:
54       return "invalid argument";
55     case bound_error:
56       return "out of bounds";
57     case mismatch_error:
58       return "mismatch";
59     case not_found_error:
60       return "not found";
61     case system_error:
62       return "system error";
63     case network_error:
64       return "network error";
65     case timeout_error:
66       return "timeout";
67     case cancel_error:
68       return "action canceled";
69     case thread_error:
70       return "thread error";
71     case host_error:
72       return "host failed";
73     case tracing_error:
74       return "tracing error";
75     case io_error:
76       return "io error";
77     case vm_error:
78       return "vm error";
79     default:
80       return "INVALID ERROR";
81   }
82   return "INVALID ERROR";
83 }
84
85 namespace simgrid {
86 namespace xbt {
87
88 void log_exception(e_xbt_log_priority_t prio, const char* context, std::exception const& exception)
89 {
90   try {
91     auto name = simgrid::xbt::demangle(typeid(exception).name());
92
93     auto* with_context = dynamic_cast<const simgrid::Exception*>(&exception);
94     if (with_context != nullptr)
95       XBT_LOG(prio, "%s %s by %s/%d: %s", context, name.get(), with_context->throw_point().procname_.c_str(),
96               with_context->throw_point().pid_, exception.what());
97     else
98       XBT_LOG(prio, "%s %s: %s", context, name.get(), exception.what());
99
100     // Do we have a backtrace?
101     if (with_context != nullptr && not simgrid::config::get_value<bool>("exception/cutpath")) {
102       auto backtrace = simgrid::xbt::resolve_backtrace(with_context->throw_point().backtrace_.data(),
103                                                        with_context->throw_point().backtrace_.size());
104       for (std::string const& s : backtrace)
105         XBT_LOG(prio, "  -> %s", s.c_str());
106     }
107
108     // Do we have a nested exception?
109     auto* with_nested = dynamic_cast<const std::nested_exception*>(&exception);
110     if (with_nested == nullptr ||  with_nested->nested_ptr() == nullptr)
111       return;
112     try {
113       with_nested->rethrow_nested();
114     }
115     catch (std::exception& nested_exception) {
116       log_exception(prio, "Caused by", nested_exception);
117     }
118     // We could catch nested_exception or WithContextException but we don't bother:
119     catch (...) {
120       XBT_LOG(prio, "Caused by an unknown exception");
121     }
122   }
123   catch (...) {
124     // Don't log exceptions we got when trying to log exception
125   }
126 }
127
128 static void showBacktrace(std::vector<xbt_backtrace_location_t>& bt)
129 {
130   if (simgrid::config::get_value<bool>("exception/cutpath")) {
131     XBT_LOG(xbt_log_priority_critical, "Display of current backtrace disabled by --cfg=exception/cutpath.");
132     return;
133   }
134   std::vector<std::string> res = resolve_backtrace(&bt[0], bt.size());
135   XBT_LOG(xbt_log_priority_critical, "Current backtrace:");
136   for (std::string const& s : res)
137     XBT_LOG(xbt_log_priority_critical, "  -> %s", s.c_str());
138 }
139
140 static std::terminate_handler previous_terminate_handler = nullptr;
141
142 static void handler()
143 {
144   // Avoid doing crazy things if we get an uncaught exception inside
145   // an uncaught exception
146   static std::atomic_flag lock = ATOMIC_FLAG_INIT;
147   if (lock.test_and_set()) {
148     XBT_ERROR("Handling an exception raised an exception. Bailing out.");
149     std::abort();
150   }
151
152   // Get the current backtrace and exception
153   auto e = std::current_exception();
154   auto bt = backtrace();
155   try {
156     std::rethrow_exception(e);
157   }
158
159   // We manage C++ exception ourselves
160   catch (std::exception& e) {
161     log_exception(xbt_log_priority_critical, "Uncaught exception", e);
162     showBacktrace(bt);
163     std::abort();
164   }
165
166   // We don't know how to manage other exceptions
167   catch (...) {
168     // If there was another handler let's delegate to it
169     if (previous_terminate_handler)
170       previous_terminate_handler();
171     else {
172       XBT_ERROR("Unknown uncaught exception");
173       showBacktrace(bt);
174       std::abort();
175     }
176   }
177
178 }
179
180 void install_exception_handler()
181 {
182   static std::once_flag handler_flag;
183   std::call_once(handler_flag, [] {
184     previous_terminate_handler = std::set_terminate(handler);
185   });
186 }
187 // deprecated
188 void logException(e_xbt_log_priority_t priority, const char* context, std::exception const& exception)
189 {
190   log_exception(priority, context, exception);
191 }
192 void installExceptionHandler()
193 {
194   install_exception_handler();
195 }
196
197 } // namespace xbt
198 }