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