1 /*
2     Copyright (c) 2005-2021 Intel Corporation
3 
4     Licensed under the Apache License, Version 2.0 (the "License");
5     you may not use this file except in compliance with the License.
6     You may obtain a copy of the License at
7 
8         http://www.apache.org/licenses/LICENSE-2.0
9 
10     Unless required by applicable law or agreed to in writing, software
11     distributed under the License is distributed on an "AS IS" BASIS,
12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13     See the License for the specific language governing permissions and
14     limitations under the License.
15 */
16 
17 #include "oneapi/tbb/detail/_exception.h"
18 #include "oneapi/tbb/detail/_assert.h"
19 #include "oneapi/tbb/detail/_template_helpers.h"
20 
21 #include <cstring>
22 #include <cstdio>
23 #include <stdexcept> // std::runtime_error
24 #include <new>
25 #include <stdexcept>
26 
27 #define __TBB_STD_RETHROW_EXCEPTION_POSSIBLY_BROKEN                             \
28     (__GLIBCXX__ && __TBB_GLIBCXX_VERSION>=40700 && __TBB_GLIBCXX_VERSION<60000 && TBB_USE_EXCEPTIONS)
29 
30 #if __TBB_STD_RETHROW_EXCEPTION_POSSIBLY_BROKEN
31 // GCC ABI declarations necessary for a workaround
32 #include <cxxabi.h>
33 #endif
34 
35 namespace tbb {
36 namespace detail {
37 namespace r1 {
38 
what() const39 const char* bad_last_alloc::what() const noexcept(true) { return "bad allocation in previous or concurrent attempt"; }
what() const40 const char* user_abort::what() const noexcept(true) { return "User-initiated abort has terminated this operation"; }
what() const41 const char* missing_wait::what() const noexcept(true) { return "wait() was not called on the structured_task_group"; }
42 
43 #if TBB_USE_EXCEPTIONS
44     template <typename F>
do_throw_noexcept(F throw_func)45     /*[[noreturn]]*/ void do_throw_noexcept(F throw_func) noexcept {
46         throw_func();
47     }
48 
do_throw_noexcept(void (* throw_func)())49     /*[[noreturn]]*/ void do_throw_noexcept(void (*throw_func)()) noexcept {
50         throw_func();
51 #if __GNUC__ == 7
52         // In release, GCC 7 loses noexcept attribute during tail call optimization.
53         // The following statement prevents tail call optimization.
54         volatile bool reach_this_point = true;
55         suppress_unused_warning(reach_this_point);
56 #endif
57     }
58 
59     bool terminate_on_exception(); // defined in global_control.cpp and ipc_server.cpp
60 
61     template <typename F>
do_throw(F throw_func)62     /*[[noreturn]]*/ void do_throw(F throw_func) {
63         if (terminate_on_exception()) {
64             do_throw_noexcept(throw_func);
65         }
66         throw_func();
67     }
68 
69     #define DO_THROW(exc, init_args) do_throw( []{ throw exc init_args; } );
70 #else /* !TBB_USE_EXCEPTIONS */
71     #define PRINT_ERROR_AND_ABORT(exc_name, msg) \
72         std::fprintf (stderr, "Exception %s with message %s would have been thrown, "  \
73             "if exception handling had not been disabled. Aborting.\n", exc_name, msg); \
74         std::fflush(stderr); \
75         std::abort();
76     #define DO_THROW(exc, init_args) PRINT_ERROR_AND_ABORT(#exc, #init_args)
77 #endif /* !TBB_USE_EXCEPTIONS */
78 
throw_exception(exception_id eid)79 void throw_exception ( exception_id eid ) {
80     switch ( eid ) {
81     case exception_id::bad_alloc: DO_THROW(std::bad_alloc, ()); break;
82     case exception_id::bad_last_alloc: DO_THROW(bad_last_alloc, ()); break;
83     case exception_id::user_abort: DO_THROW( user_abort, () ); break;
84     case exception_id::nonpositive_step: DO_THROW(std::invalid_argument, ("Step must be positive") ); break;
85     case exception_id::out_of_range: DO_THROW(std::out_of_range, ("Index out of requested size range")); break;
86     case exception_id::reservation_length_error: DO_THROW(std::length_error, ("Attempt to exceed implementation defined length limits")); break;
87     case exception_id::missing_wait: DO_THROW(missing_wait, ()); break;
88     case exception_id::invalid_load_factor: DO_THROW(std::out_of_range, ("Invalid hash load factor")); break;
89     case exception_id::invalid_key: DO_THROW(std::out_of_range, ("invalid key")); break;
90     case exception_id::bad_tagged_msg_cast: DO_THROW(std::runtime_error, ("Illegal tagged_msg cast")); break;
91 #if __TBB_SUPPORTS_WORKERS_WAITING_IN_TERMINATE
92     case exception_id::unsafe_wait: DO_THROW(unsafe_wait, ("Unsafe to wait further")); break;
93 #endif
94 #if __TBB_PREVIEW_TASK_GROUP_EXTENSIONS
95     case exception_id::bad_task_handle:                   DO_THROW(std::runtime_error, ("Attempt to schedule empty task_handle")); break;
96     case exception_id::bad_task_handle_wrong_task_group:  DO_THROW(std::runtime_error, ("Attempt to schedule task_handle into different task_group")); break;
97 #endif
98     default: __TBB_ASSERT ( false, "Unknown exception ID" );
99     }
100     __TBB_ASSERT(false, "Unreachable code");
101 }
102 
103 /* The "what" should be fairly short, not more than about 128 characters.
104    Because we control all the call sites to handle_perror, it is pointless
105    to bullet-proof it for very long strings.
106 
107    Design note: ADR put this routine off to the side in tbb_misc.cpp instead of
108    Task.cpp because the throw generates a pathetic lot of code, and ADR wanted
109    this large chunk of code to be placed on a cold page. */
handle_perror(int error_code,const char * what)110 void handle_perror( int error_code, const char* what ) {
111     const int BUF_SIZE = 255;
112     char buf[BUF_SIZE + 1] = { 0 };
113     std::strncat(buf, what, BUF_SIZE);
114     std::size_t buf_len = std::strlen(buf);
115     if (error_code) {
116         std::strncat(buf, ": ", BUF_SIZE - buf_len);
117         buf_len = std::strlen(buf);
118         std::strncat(buf, std::strerror(error_code), BUF_SIZE - buf_len);
119         buf_len = std::strlen(buf);
120     }
121     __TBB_ASSERT(buf_len <= BUF_SIZE && buf[buf_len] == 0, nullptr);
122 #if TBB_USE_EXCEPTIONS
123     do_throw([&buf] { throw std::runtime_error(buf); });
124 #else
125     PRINT_ERROR_AND_ABORT( "runtime_error", buf);
126 #endif /* !TBB_USE_EXCEPTIONS */
127 }
128 
129 #if __TBB_STD_RETHROW_EXCEPTION_POSSIBLY_BROKEN
130 // Runtime detection and workaround for the GCC bug 62258.
131 // The problem is that std::rethrow_exception() does not increment a counter
132 // of active exceptions, causing std::uncaught_exception() to return a wrong value.
133 // The code is created after, and roughly reflects, the workaround
134 // at https://gcc.gnu.org/bugzilla/attachment.cgi?id=34683
135 
fix_broken_rethrow()136 void fix_broken_rethrow() {
137     struct gcc_eh_data {
138         void *       caughtExceptions;
139         unsigned int uncaughtExceptions;
140     };
141     gcc_eh_data* eh_data = punned_cast<gcc_eh_data*>( abi::__cxa_get_globals() );
142     ++eh_data->uncaughtExceptions;
143 }
144 
gcc_rethrow_exception_broken()145 bool gcc_rethrow_exception_broken() {
146     bool is_broken;
147     __TBB_ASSERT( !std::uncaught_exception(),
148         "gcc_rethrow_exception_broken() must not be called when an exception is active" );
149     try {
150         // Throw, catch, and rethrow an exception
151         try {
152             throw __TBB_GLIBCXX_VERSION;
153         } catch(...) {
154             std::rethrow_exception( std::current_exception() );
155         }
156     } catch(...) {
157         // Check the bug presence
158         is_broken = std::uncaught_exception();
159     }
160     if( is_broken ) fix_broken_rethrow();
161     __TBB_ASSERT( !std::uncaught_exception(), NULL );
162     return is_broken;
163 }
164 #else
fix_broken_rethrow()165 void fix_broken_rethrow() {}
gcc_rethrow_exception_broken()166 bool gcc_rethrow_exception_broken() { return false; }
167 #endif /* __TBB_STD_RETHROW_EXCEPTION_POSSIBLY_BROKEN */
168 
169 } // namespace r1
170 } // namespace detail
171 } // namespace tbb
172 
173