1 //===------------------------- cxa_exception.cpp --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //
9 //  This file implements the "Exception Handling APIs"
10 //  http://mentorembedded.github.io/cxx-abi/abi-eh.html
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #define _LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS
15 
16 #include "cxxabi.h"
17 
18 #include <exception>        // for std::terminate
19 #include <cstring>          // for memset
20 #include "cxa_exception.hpp"
21 #include "cxa_handlers.hpp"
22 #include "fallback_malloc.h"
23 
24 #if __has_feature(address_sanitizer)
25 extern "C" void __asan_handle_no_return(void);
26 #endif
27 
28 // +---------------------------+-----------------------------+---------------+
29 // | __cxa_exception           | _Unwind_Exception CLNGC++\0 | thrown object |
30 // +---------------------------+-----------------------------+---------------+
31 //                                                           ^
32 //                                                           |
33 //   +-------------------------------------------------------+
34 //   |
35 // +---------------------------+-----------------------------+
36 // | __cxa_dependent_exception | _Unwind_Exception CLNGC++\1 |
37 // +---------------------------+-----------------------------+
38 
39 namespace __cxxabiv1 {
40 
41 //  Utility routines
42 static
43 inline
44 __cxa_exception*
45 cxa_exception_from_thrown_object(void* thrown_object)
46 {
47     return static_cast<__cxa_exception*>(thrown_object) - 1;
48 }
49 
50 // Note:  This is never called when exception_header is masquerading as a
51 //        __cxa_dependent_exception.
52 static
53 inline
54 void*
55 thrown_object_from_cxa_exception(__cxa_exception* exception_header)
56 {
57     return static_cast<void*>(exception_header + 1);
58 }
59 
60 //  Get the exception object from the unwind pointer.
61 //  Relies on the structure layout, where the unwind pointer is right in
62 //  front of the user's exception object
63 static
64 inline
65 __cxa_exception*
66 cxa_exception_from_exception_unwind_exception(_Unwind_Exception* unwind_exception)
67 {
68     return cxa_exception_from_thrown_object(unwind_exception + 1 );
69 }
70 
71 // Round s up to next multiple of a.
72 static inline
73 size_t aligned_allocation_size(size_t s, size_t a) {
74     return (s + a - 1) & ~(a - 1);
75 }
76 
77 static inline
78 size_t cxa_exception_size_from_exception_thrown_size(size_t size) {
79     return aligned_allocation_size(size + sizeof (__cxa_exception),
80                                    alignof(__cxa_exception));
81 }
82 
83 static void setExceptionClass(_Unwind_Exception* unwind_exception) {
84     unwind_exception->exception_class = kOurExceptionClass;
85 }
86 
87 static void setDependentExceptionClass(_Unwind_Exception* unwind_exception) {
88     unwind_exception->exception_class = kOurDependentExceptionClass;
89 }
90 
91 //  Is it one of ours?
92 static bool isOurExceptionClass(const _Unwind_Exception* unwind_exception) {
93     return (unwind_exception->exception_class & get_vendor_and_language) ==
94            (kOurExceptionClass                & get_vendor_and_language);
95 }
96 
97 static bool isDependentException(_Unwind_Exception* unwind_exception) {
98     return (unwind_exception->exception_class & 0xFF) == 0x01;
99 }
100 
101 //  This does not need to be atomic
102 static inline int incrementHandlerCount(__cxa_exception *exception) {
103     return ++exception->handlerCount;
104 }
105 
106 //  This does not need to be atomic
107 static inline  int decrementHandlerCount(__cxa_exception *exception) {
108     return --exception->handlerCount;
109 }
110 
111 /*
112     If reason isn't _URC_FOREIGN_EXCEPTION_CAUGHT, then the terminateHandler
113     stored in exc is called.  Otherwise the exceptionDestructor stored in
114     exc is called, and then the memory for the exception is deallocated.
115 
116     This is never called for a __cxa_dependent_exception.
117 */
118 static
119 void
120 exception_cleanup_func(_Unwind_Reason_Code reason, _Unwind_Exception* unwind_exception)
121 {
122     __cxa_exception* exception_header = cxa_exception_from_exception_unwind_exception(unwind_exception);
123     if (_URC_FOREIGN_EXCEPTION_CAUGHT != reason)
124         std::__terminate(exception_header->terminateHandler);
125     // Just in case there exists a dependent exception that is pointing to this,
126     //    check the reference count and only destroy this if that count goes to zero.
127     __cxa_decrement_exception_refcount(unwind_exception + 1);
128 }
129 
130 static _LIBCXXABI_NORETURN void failed_throw(__cxa_exception* exception_header) {
131 //  Section 2.5.3 says:
132 //      * For purposes of this ABI, several things are considered exception handlers:
133 //      ** A terminate() call due to a throw.
134 //  and
135 //      * Upon entry, Following initialization of the catch parameter,
136 //          a handler must call:
137 //      * void *__cxa_begin_catch(void *exceptionObject );
138     (void) __cxa_begin_catch(&exception_header->unwindHeader);
139     std::__terminate(exception_header->terminateHandler);
140 }
141 
142 // Return the offset of the __cxa_exception header from the start of the
143 // allocated buffer. If __cxa_exception's alignment is smaller than the maximum
144 // useful alignment for the target machine, padding has to be inserted before
145 // the header to ensure the thrown object that follows the header is
146 // sufficiently aligned. This happens if _Unwind_exception isn't double-word
147 // aligned (on Darwin, for example).
148 static size_t get_cxa_exception_offset() {
149   struct S {
150   } __attribute__((aligned));
151 
152   // Compute the maximum alignment for the target machine.
153   constexpr size_t alignment = std::alignment_of<S>::value;
154   constexpr size_t excp_size = sizeof(__cxa_exception);
155   constexpr size_t aligned_size =
156       (excp_size + alignment - 1) / alignment * alignment;
157   constexpr size_t offset = aligned_size - excp_size;
158   static_assert((offset == 0 ||
159                  std::alignment_of<_Unwind_Exception>::value < alignment),
160                 "offset is non-zero only if _Unwind_Exception isn't aligned");
161   return offset;
162 }
163 
164 extern "C" {
165 
166 //  Allocate a __cxa_exception object, and zero-fill it.
167 //  Reserve "thrown_size" bytes on the end for the user's exception
168 //  object. Zero-fill the object. If memory can't be allocated, call
169 //  std::terminate. Return a pointer to the memory to be used for the
170 //  user's exception object.
171 void *__cxa_allocate_exception(size_t thrown_size) throw() {
172     size_t actual_size = cxa_exception_size_from_exception_thrown_size(thrown_size);
173 
174     // Allocate extra space before the __cxa_exception header to ensure the
175     // start of the thrown object is sufficiently aligned.
176     size_t header_offset = get_cxa_exception_offset();
177     char *raw_buffer =
178         (char *)__aligned_malloc_with_fallback(header_offset + actual_size);
179     if (NULL == raw_buffer)
180         std::terminate();
181     __cxa_exception *exception_header =
182         static_cast<__cxa_exception *>((void *)(raw_buffer + header_offset));
183     std::memset(exception_header, 0, actual_size);
184     return thrown_object_from_cxa_exception(exception_header);
185 }
186 
187 
188 //  Free a __cxa_exception object allocated with __cxa_allocate_exception.
189 void __cxa_free_exception(void *thrown_object) throw() {
190     // Compute the size of the padding before the header.
191     size_t header_offset = get_cxa_exception_offset();
192     char *raw_buffer =
193         ((char *)cxa_exception_from_thrown_object(thrown_object)) - header_offset;
194     __aligned_free_with_fallback((void *)raw_buffer);
195 }
196 
197 
198 //  This function shall allocate a __cxa_dependent_exception and
199 //  return a pointer to it. (Really to the object, not past its' end).
200 //  Otherwise, it will work like __cxa_allocate_exception.
201 void * __cxa_allocate_dependent_exception () {
202     size_t actual_size = sizeof(__cxa_dependent_exception);
203     void *ptr = __aligned_malloc_with_fallback(actual_size);
204     if (NULL == ptr)
205         std::terminate();
206     std::memset(ptr, 0, actual_size);
207     return ptr;
208 }
209 
210 
211 //  This function shall free a dependent_exception.
212 //  It does not affect the reference count of the primary exception.
213 void __cxa_free_dependent_exception (void * dependent_exception) {
214     __aligned_free_with_fallback(dependent_exception);
215 }
216 
217 
218 // 2.4.3 Throwing the Exception Object
219 /*
220 After constructing the exception object with the throw argument value,
221 the generated code calls the __cxa_throw runtime library routine. This
222 routine never returns.
223 
224 The __cxa_throw routine will do the following:
225 
226 * Obtain the __cxa_exception header from the thrown exception object address,
227 which can be computed as follows:
228  __cxa_exception *header = ((__cxa_exception *) thrown_exception - 1);
229 * Save the current unexpected_handler and terminate_handler in the __cxa_exception header.
230 * Save the tinfo and dest arguments in the __cxa_exception header.
231 * Set the exception_class field in the unwind header. This is a 64-bit value
232 representing the ASCII string "XXXXC++\0", where "XXXX" is a
233 vendor-dependent string. That is, for implementations conforming to this
234 ABI, the low-order 4 bytes of this 64-bit value will be "C++\0".
235 * Increment the uncaught_exception flag.
236 * Call _Unwind_RaiseException in the system unwind library, Its argument is the
237 pointer to the thrown exception, which __cxa_throw itself received as an argument.
238 __Unwind_RaiseException begins the process of stack unwinding, described
239 in Section 2.5. In special cases, such as an inability to find a
240 handler, _Unwind_RaiseException may return. In that case, __cxa_throw
241 will call terminate, assuming that there was no handler for the
242 exception.
243 */
244 void
245 __cxa_throw(void *thrown_object, std::type_info *tinfo, void (*dest)(void *)) {
246     __cxa_eh_globals *globals = __cxa_get_globals();
247     __cxa_exception* exception_header = cxa_exception_from_thrown_object(thrown_object);
248 
249     exception_header->unexpectedHandler = std::get_unexpected();
250     exception_header->terminateHandler  = std::get_terminate();
251     exception_header->exceptionType = tinfo;
252     exception_header->exceptionDestructor = dest;
253     setExceptionClass(&exception_header->unwindHeader);
254     exception_header->referenceCount = 1;  // This is a newly allocated exception, no need for thread safety.
255     globals->uncaughtExceptions += 1;   // Not atomically, since globals are thread-local
256 
257     exception_header->unwindHeader.exception_cleanup = exception_cleanup_func;
258 
259 #if __has_feature(address_sanitizer)
260     // Inform the ASan runtime that now might be a good time to clean stuff up.
261     __asan_handle_no_return();
262 #endif
263 
264 #ifdef __USING_SJLJ_EXCEPTIONS__
265     _Unwind_SjLj_RaiseException(&exception_header->unwindHeader);
266 #else
267     _Unwind_RaiseException(&exception_header->unwindHeader);
268 #endif
269     //  This only happens when there is no handler, or some unexpected unwinding
270     //     error happens.
271     failed_throw(exception_header);
272 }
273 
274 
275 // 2.5.3 Exception Handlers
276 /*
277 The adjusted pointer is computed by the personality routine during phase 1
278   and saved in the exception header (either __cxa_exception or
279   __cxa_dependent_exception).
280 
281   Requires:  exception is native
282 */
283 void *__cxa_get_exception_ptr(void *unwind_exception) throw() {
284 #if defined(_LIBCXXABI_ARM_EHABI)
285     return reinterpret_cast<void*>(
286         static_cast<_Unwind_Control_Block*>(unwind_exception)->barrier_cache.bitpattern[0]);
287 #else
288     return cxa_exception_from_exception_unwind_exception(
289         static_cast<_Unwind_Exception*>(unwind_exception))->adjustedPtr;
290 #endif
291 }
292 
293 #if defined(_LIBCXXABI_ARM_EHABI)
294 /*
295 The routine to be called before the cleanup.  This will save __cxa_exception in
296 __cxa_eh_globals, so that __cxa_end_cleanup() can recover later.
297 */
298 bool __cxa_begin_cleanup(void *unwind_arg) throw() {
299     _Unwind_Exception* unwind_exception = static_cast<_Unwind_Exception*>(unwind_arg);
300     __cxa_eh_globals* globals = __cxa_get_globals();
301     __cxa_exception* exception_header =
302         cxa_exception_from_exception_unwind_exception(unwind_exception);
303 
304     if (isOurExceptionClass(unwind_exception))
305     {
306         if (0 == exception_header->propagationCount)
307         {
308             exception_header->nextPropagatingException = globals->propagatingExceptions;
309             globals->propagatingExceptions = exception_header;
310         }
311         ++exception_header->propagationCount;
312     }
313     else
314     {
315         // If the propagatingExceptions stack is not empty, since we can't
316         // chain the foreign exception, terminate it.
317         if (NULL != globals->propagatingExceptions)
318             std::terminate();
319         globals->propagatingExceptions = exception_header;
320     }
321     return true;
322 }
323 
324 /*
325 The routine to be called after the cleanup has been performed.  It will get the
326 propagating __cxa_exception from __cxa_eh_globals, and continue the stack
327 unwinding with _Unwind_Resume.
328 
329 According to ARM EHABI 8.4.1, __cxa_end_cleanup() should not clobber any
330 register, thus we have to write this function in assembly so that we can save
331 {r1, r2, r3}.  We don't have to save r0 because it is the return value and the
332 first argument to _Unwind_Resume().  In addition, we are saving r4 in order to
333 align the stack to 16 bytes, even though it is a callee-save register.
334 */
335 __attribute__((used)) static _Unwind_Exception *
336 __cxa_end_cleanup_impl()
337 {
338     __cxa_eh_globals* globals = __cxa_get_globals();
339     __cxa_exception* exception_header = globals->propagatingExceptions;
340     if (NULL == exception_header)
341     {
342         // It seems that __cxa_begin_cleanup() is not called properly.
343         // We have no choice but terminate the program now.
344         std::terminate();
345     }
346 
347     if (isOurExceptionClass(&exception_header->unwindHeader))
348     {
349         --exception_header->propagationCount;
350         if (0 == exception_header->propagationCount)
351         {
352             globals->propagatingExceptions = exception_header->nextPropagatingException;
353             exception_header->nextPropagatingException = NULL;
354         }
355     }
356     else
357     {
358         globals->propagatingExceptions = NULL;
359     }
360     return &exception_header->unwindHeader;
361 }
362 
363 asm (
364     "	.pushsection	.text.__cxa_end_cleanup,\"ax\",%progbits\n"
365     "	.globl	__cxa_end_cleanup\n"
366     "	.type	__cxa_end_cleanup,%function\n"
367     "__cxa_end_cleanup:\n"
368     "	push	{r1, r2, r3, r4}\n"
369     "	bl	__cxa_end_cleanup_impl\n"
370     "	pop	{r1, r2, r3, r4}\n"
371     "	bl	_Unwind_Resume\n"
372     "	bl	abort\n"
373     "	.popsection"
374 );
375 #endif  // defined(_LIBCXXABI_ARM_EHABI)
376 
377 /*
378 This routine can catch foreign or native exceptions.  If native, the exception
379 can be a primary or dependent variety.  This routine may remain blissfully
380 ignorant of whether the native exception is primary or dependent.
381 
382 If the exception is native:
383 * Increment's the exception's handler count.
384 * Push the exception on the stack of currently-caught exceptions if it is not
385   already there (from a rethrow).
386 * Decrements the uncaught_exception count.
387 * Returns the adjusted pointer to the exception object, which is stored in
388   the __cxa_exception by the personality routine.
389 
390 If the exception is foreign, this means it did not originate from one of throw
391 routines.  The foreign exception does not necessarily have a __cxa_exception
392 header.  However we can catch it here with a catch (...), or with a call
393 to terminate or unexpected during unwinding.
394 * Do not try to increment the exception's handler count, we don't know where
395   it is.
396 * Push the exception on the stack of currently-caught exceptions only if the
397   stack is empty.  The foreign exception has no way to link to the current
398   top of stack.  If the stack is not empty, call terminate.  Even with an
399   empty stack, this is hacked in by pushing a pointer to an imaginary
400   __cxa_exception block in front of the foreign exception.  It would be better
401   if the __cxa_eh_globals structure had a stack of _Unwind_Exception, but it
402   doesn't.  It has a stack of __cxa_exception (which has a next* in it).
403 * Do not decrement the uncaught_exception count because we didn't increment it
404   in __cxa_throw (or one of our rethrow functions).
405 * If we haven't terminated, assume the exception object is just past the
406   _Unwind_Exception and return a pointer to that.
407 */
408 void*
409 __cxa_begin_catch(void* unwind_arg) throw()
410 {
411     _Unwind_Exception* unwind_exception = static_cast<_Unwind_Exception*>(unwind_arg);
412     bool native_exception = isOurExceptionClass(unwind_exception);
413     __cxa_eh_globals* globals = __cxa_get_globals();
414     // exception_header is a hackish offset from a foreign exception, but it
415     //   works as long as we're careful not to try to access any __cxa_exception
416     //   parts.
417     __cxa_exception* exception_header =
418             cxa_exception_from_exception_unwind_exception
419             (
420                 static_cast<_Unwind_Exception*>(unwind_exception)
421             );
422     if (native_exception)
423     {
424         // Increment the handler count, removing the flag about being rethrown
425         exception_header->handlerCount = exception_header->handlerCount < 0 ?
426             -exception_header->handlerCount + 1 : exception_header->handlerCount + 1;
427         //  place the exception on the top of the stack if it's not already
428         //    there by a previous rethrow
429         if (exception_header != globals->caughtExceptions)
430         {
431             exception_header->nextException = globals->caughtExceptions;
432             globals->caughtExceptions = exception_header;
433         }
434         globals->uncaughtExceptions -= 1;   // Not atomically, since globals are thread-local
435 #if defined(_LIBCXXABI_ARM_EHABI)
436         return reinterpret_cast<void*>(exception_header->unwindHeader.barrier_cache.bitpattern[0]);
437 #else
438         return exception_header->adjustedPtr;
439 #endif
440     }
441     // Else this is a foreign exception
442     // If the caughtExceptions stack is not empty, terminate
443     if (globals->caughtExceptions != 0)
444         std::terminate();
445     // Push the foreign exception on to the stack
446     globals->caughtExceptions = exception_header;
447     return unwind_exception + 1;
448 }
449 
450 
451 /*
452 Upon exit for any reason, a handler must call:
453     void __cxa_end_catch ();
454 
455 This routine can be called for either a native or foreign exception.
456 For a native exception:
457 * Locates the most recently caught exception and decrements its handler count.
458 * Removes the exception from the caught exception stack, if the handler count goes to zero.
459 * If the handler count goes down to zero, and the exception was not re-thrown
460   by throw, it locates the primary exception (which may be the same as the one
461   it's handling) and decrements its reference count. If that reference count
462   goes to zero, the function destroys the exception. In any case, if the current
463   exception is a dependent exception, it destroys that.
464 
465 For a foreign exception:
466 * If it has been rethrown, there is nothing to do.
467 * Otherwise delete the exception and pop the catch stack to empty.
468 */
469 void __cxa_end_catch() {
470   static_assert(sizeof(__cxa_exception) == sizeof(__cxa_dependent_exception),
471                 "sizeof(__cxa_exception) must be equal to "
472                 "sizeof(__cxa_dependent_exception)");
473   static_assert(__builtin_offsetof(__cxa_exception, referenceCount) ==
474                     __builtin_offsetof(__cxa_dependent_exception,
475                                        primaryException),
476                 "the layout of __cxa_exception must match the layout of "
477                 "__cxa_dependent_exception");
478   static_assert(__builtin_offsetof(__cxa_exception, handlerCount) ==
479                     __builtin_offsetof(__cxa_dependent_exception, handlerCount),
480                 "the layout of __cxa_exception must match the layout of "
481                 "__cxa_dependent_exception");
482     __cxa_eh_globals* globals = __cxa_get_globals_fast(); // __cxa_get_globals called in __cxa_begin_catch
483     __cxa_exception* exception_header = globals->caughtExceptions;
484     // If we've rethrown a foreign exception, then globals->caughtExceptions
485     //    will have been made an empty stack by __cxa_rethrow() and there is
486     //    nothing more to be done.  Do nothing!
487     if (NULL != exception_header)
488     {
489         bool native_exception = isOurExceptionClass(&exception_header->unwindHeader);
490         if (native_exception)
491         {
492             // This is a native exception
493             if (exception_header->handlerCount < 0)
494             {
495                 //  The exception has been rethrown by __cxa_rethrow, so don't delete it
496                 if (0 == incrementHandlerCount(exception_header))
497                 {
498                     //  Remove from the chain of uncaught exceptions
499                     globals->caughtExceptions = exception_header->nextException;
500                     // but don't destroy
501                 }
502                 // Keep handlerCount negative in case there are nested catch's
503                 //   that need to be told that this exception is rethrown.  Don't
504                 //   erase this rethrow flag until the exception is recaught.
505             }
506             else
507             {
508                 // The native exception has not been rethrown
509                 if (0 == decrementHandlerCount(exception_header))
510                 {
511                     //  Remove from the chain of uncaught exceptions
512                     globals->caughtExceptions = exception_header->nextException;
513                     // Destroy this exception, being careful to distinguish
514                     //    between dependent and primary exceptions
515                     if (isDependentException(&exception_header->unwindHeader))
516                     {
517                         // Reset exception_header to primaryException and deallocate the dependent exception
518                         __cxa_dependent_exception* dep_exception_header =
519                             reinterpret_cast<__cxa_dependent_exception*>(exception_header);
520                         exception_header =
521                             cxa_exception_from_thrown_object(dep_exception_header->primaryException);
522                         __cxa_free_dependent_exception(dep_exception_header);
523                     }
524                     // Destroy the primary exception only if its referenceCount goes to 0
525                     //    (this decrement must be atomic)
526                     __cxa_decrement_exception_refcount(thrown_object_from_cxa_exception(exception_header));
527                 }
528             }
529         }
530         else
531         {
532             // The foreign exception has not been rethrown.  Pop the stack
533             //    and delete it.  If there are nested catch's and they try
534             //    to touch a foreign exception in any way, that is undefined
535             //     behavior.  They likely can't since the only way to catch
536             //     a foreign exception is with catch (...)!
537             _Unwind_DeleteException(&globals->caughtExceptions->unwindHeader);
538             globals->caughtExceptions = 0;
539         }
540     }
541 }
542 
543 // Note:  exception_header may be masquerading as a __cxa_dependent_exception
544 //        and that's ok.  exceptionType is there too.
545 //        However watch out for foreign exceptions.  Return null for them.
546 std::type_info *__cxa_current_exception_type() {
547 //  get the current exception
548     __cxa_eh_globals *globals = __cxa_get_globals_fast();
549     if (NULL == globals)
550         return NULL;     //  If there have never been any exceptions, there are none now.
551     __cxa_exception *exception_header = globals->caughtExceptions;
552     if (NULL == exception_header)
553         return NULL;        //  No current exception
554     if (!isOurExceptionClass(&exception_header->unwindHeader))
555         return NULL;
556     return exception_header->exceptionType;
557 }
558 
559 // 2.5.4 Rethrowing Exceptions
560 /*  This routine can rethrow native or foreign exceptions.
561 If the exception is native:
562 * marks the exception object on top of the caughtExceptions stack
563   (in an implementation-defined way) as being rethrown.
564 * If the caughtExceptions stack is empty, it calls terminate()
565   (see [C++FDIS] [except.throw], 15.1.8).
566 * It then calls _Unwind_RaiseException which should not return
567    (terminate if it does).
568   Note:  exception_header may be masquerading as a __cxa_dependent_exception
569          and that's ok.
570 */
571 void __cxa_rethrow() {
572     __cxa_eh_globals* globals = __cxa_get_globals();
573     __cxa_exception* exception_header = globals->caughtExceptions;
574     if (NULL == exception_header)
575         std::terminate();      // throw; called outside of a exception handler
576     bool native_exception = isOurExceptionClass(&exception_header->unwindHeader);
577     if (native_exception)
578     {
579         //  Mark the exception as being rethrown (reverse the effects of __cxa_begin_catch)
580         exception_header->handlerCount = -exception_header->handlerCount;
581         globals->uncaughtExceptions += 1;
582         //  __cxa_end_catch will remove this exception from the caughtExceptions stack if necessary
583     }
584     else  // this is a foreign exception
585     {
586         // The only way to communicate to __cxa_end_catch that we've rethrown
587         //   a foreign exception, so don't delete us, is to pop the stack here
588         //   which must be empty afterwards.  Then __cxa_end_catch will do
589         //   nothing
590         globals->caughtExceptions = 0;
591     }
592 #ifdef __USING_SJLJ_EXCEPTIONS__
593     _Unwind_SjLj_RaiseException(&exception_header->unwindHeader);
594 #else
595     _Unwind_RaiseException(&exception_header->unwindHeader);
596 #endif
597 
598     //  If we get here, some kind of unwinding error has occurred.
599     //  There is some weird code generation bug happening with
600     //     Apple clang version 4.0 (tags/Apple/clang-418.0.2) (based on LLVM 3.1svn)
601     //     If we call failed_throw here.  Turns up with -O2 or higher, and -Os.
602     __cxa_begin_catch(&exception_header->unwindHeader);
603     if (native_exception)
604         std::__terminate(exception_header->terminateHandler);
605     // Foreign exception: can't get exception_header->terminateHandler
606     std::terminate();
607 }
608 
609 /*
610     If thrown_object is not null, atomically increment the referenceCount field
611     of the __cxa_exception header associated with the thrown object referred to
612     by thrown_object.
613 
614     Requires:  If thrown_object is not NULL, it is a native exception.
615 */
616 void
617 __cxa_increment_exception_refcount(void *thrown_object) throw() {
618     if (thrown_object != NULL )
619     {
620         __cxa_exception* exception_header = cxa_exception_from_thrown_object(thrown_object);
621         __sync_add_and_fetch(&exception_header->referenceCount, 1);
622     }
623 }
624 
625 /*
626     If thrown_object is not null, atomically decrement the referenceCount field
627     of the __cxa_exception header associated with the thrown object referred to
628     by thrown_object.  If the referenceCount drops to zero, destroy and
629     deallocate the exception.
630 
631     Requires:  If thrown_object is not NULL, it is a native exception.
632 */
633 _LIBCXXABI_NO_CFI
634 void __cxa_decrement_exception_refcount(void *thrown_object) throw() {
635     if (thrown_object != NULL )
636     {
637         __cxa_exception* exception_header = cxa_exception_from_thrown_object(thrown_object);
638         if (__sync_sub_and_fetch(&exception_header->referenceCount, size_t(1)) == 0)
639         {
640             if (NULL != exception_header->exceptionDestructor)
641                 exception_header->exceptionDestructor(thrown_object);
642             __cxa_free_exception(thrown_object);
643         }
644     }
645 }
646 
647 /*
648     Returns a pointer to the thrown object (if any) at the top of the
649     caughtExceptions stack.  Atomically increment the exception's referenceCount.
650     If there is no such thrown object or if the thrown object is foreign,
651     returns null.
652 
653     We can use __cxa_get_globals_fast here to get the globals because if there have
654     been no exceptions thrown, ever, on this thread, we can return NULL without
655     the need to allocate the exception-handling globals.
656 */
657 void *__cxa_current_primary_exception() throw() {
658 //  get the current exception
659     __cxa_eh_globals* globals = __cxa_get_globals_fast();
660     if (NULL == globals)
661         return NULL;        //  If there are no globals, there is no exception
662     __cxa_exception* exception_header = globals->caughtExceptions;
663     if (NULL == exception_header)
664         return NULL;        //  No current exception
665     if (!isOurExceptionClass(&exception_header->unwindHeader))
666         return NULL;        // Can't capture a foreign exception (no way to refcount it)
667     if (isDependentException(&exception_header->unwindHeader)) {
668         __cxa_dependent_exception* dep_exception_header =
669             reinterpret_cast<__cxa_dependent_exception*>(exception_header);
670         exception_header = cxa_exception_from_thrown_object(dep_exception_header->primaryException);
671     }
672     void* thrown_object = thrown_object_from_cxa_exception(exception_header);
673     __cxa_increment_exception_refcount(thrown_object);
674     return thrown_object;
675 }
676 
677 /*
678     If reason isn't _URC_FOREIGN_EXCEPTION_CAUGHT, then the terminateHandler
679     stored in exc is called.  Otherwise the referenceCount stored in the
680     primary exception is decremented, destroying the primary if necessary.
681     Finally the dependent exception is destroyed.
682 */
683 static
684 void
685 dependent_exception_cleanup(_Unwind_Reason_Code reason, _Unwind_Exception* unwind_exception)
686 {
687     __cxa_dependent_exception* dep_exception_header =
688                       reinterpret_cast<__cxa_dependent_exception*>(unwind_exception + 1) - 1;
689     if (_URC_FOREIGN_EXCEPTION_CAUGHT != reason)
690         std::__terminate(dep_exception_header->terminateHandler);
691     __cxa_decrement_exception_refcount(dep_exception_header->primaryException);
692     __cxa_free_dependent_exception(dep_exception_header);
693 }
694 
695 /*
696     If thrown_object is not null, allocate, initialize and throw a dependent
697     exception.
698 */
699 void
700 __cxa_rethrow_primary_exception(void* thrown_object)
701 {
702     if ( thrown_object != NULL )
703     {
704         // thrown_object guaranteed to be native because
705         //   __cxa_current_primary_exception returns NULL for foreign exceptions
706         __cxa_exception* exception_header = cxa_exception_from_thrown_object(thrown_object);
707         __cxa_dependent_exception* dep_exception_header =
708             static_cast<__cxa_dependent_exception*>(__cxa_allocate_dependent_exception());
709         dep_exception_header->primaryException = thrown_object;
710         __cxa_increment_exception_refcount(thrown_object);
711         dep_exception_header->exceptionType = exception_header->exceptionType;
712         dep_exception_header->unexpectedHandler = std::get_unexpected();
713         dep_exception_header->terminateHandler = std::get_terminate();
714         setDependentExceptionClass(&dep_exception_header->unwindHeader);
715         __cxa_get_globals()->uncaughtExceptions += 1;
716         dep_exception_header->unwindHeader.exception_cleanup = dependent_exception_cleanup;
717 #ifdef __USING_SJLJ_EXCEPTIONS__
718         _Unwind_SjLj_RaiseException(&dep_exception_header->unwindHeader);
719 #else
720         _Unwind_RaiseException(&dep_exception_header->unwindHeader);
721 #endif
722         // Some sort of unwinding error.  Note that terminate is a handler.
723         __cxa_begin_catch(&dep_exception_header->unwindHeader);
724     }
725     // If we return client will call terminate()
726 }
727 
728 bool
729 __cxa_uncaught_exception() throw() { return __cxa_uncaught_exceptions() != 0; }
730 
731 unsigned int
732 __cxa_uncaught_exceptions() throw()
733 {
734     // This does not report foreign exceptions in flight
735     __cxa_eh_globals* globals = __cxa_get_globals_fast();
736     if (globals == 0)
737         return 0;
738     return globals->uncaughtExceptions;
739 }
740 
741 }  // extern "C"
742 
743 }  // abi
744