Logo AND Algorithmique Numérique Distribuée

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