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