xref: /freebsd/contrib/libcxxrt/exception.cc (revision 2ed3236082a4473c1da8f72c1ebc071a7b54321f)
1 /*
2  * Copyright 2010-2011 PathScale, Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * 1. Redistributions of source code must retain the above copyright notice,
8  *    this list of conditions and the following disclaimer.
9  *
10  * 2. Redistributions in binary form must reproduce the above copyright notice,
11  *    this list of conditions and the following disclaimer in the documentation
12  *    and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
15  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
21  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
22  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
23  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
24  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <stdlib.h>
28 #include <dlfcn.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdint.h>
32 #include <pthread.h>
33 #include "typeinfo.h"
34 #include "dwarf_eh.h"
35 #include "atomic.h"
36 #include "cxxabi.h"
37 
38 #pragma weak pthread_key_create
39 #pragma weak pthread_setspecific
40 #pragma weak pthread_getspecific
41 #pragma weak pthread_once
42 #ifdef LIBCXXRT_WEAK_LOCKS
43 #pragma weak pthread_mutex_lock
44 #define pthread_mutex_lock(mtx) do {\
45 	if (pthread_mutex_lock) pthread_mutex_lock(mtx);\
46 	} while(0)
47 #pragma weak pthread_mutex_unlock
48 #define pthread_mutex_unlock(mtx) do {\
49 	if (pthread_mutex_unlock) pthread_mutex_unlock(mtx);\
50 	} while(0)
51 #pragma weak pthread_cond_signal
52 #define pthread_cond_signal(cv) do {\
53 	if (pthread_cond_signal) pthread_cond_signal(cv);\
54 	} while(0)
55 #pragma weak pthread_cond_wait
56 #define pthread_cond_wait(cv, mtx) do {\
57 	if (pthread_cond_wait) pthread_cond_wait(cv, mtx);\
58 	} while(0)
59 #endif
60 
61 using namespace ABI_NAMESPACE;
62 
63 /**
64  * Saves the result of the landing pad that we have found.  For ARM, this is
65  * stored in the generic unwind structure, while on other platforms it is
66  * stored in the C++ exception.
67  */
68 static void saveLandingPad(struct _Unwind_Context *context,
69                            struct _Unwind_Exception *ucb,
70                            struct __cxa_exception *ex,
71                            int selector,
72                            dw_eh_ptr_t landingPad)
73 {
74 #if defined(__arm__) && !defined(__ARM_DWARF_EH__)
75 	// On ARM, we store the saved exception in the generic part of the structure
76 	ucb->barrier_cache.sp = _Unwind_GetGR(context, 13);
77 	ucb->barrier_cache.bitpattern[1] = static_cast<uint32_t>(selector);
78 	ucb->barrier_cache.bitpattern[3] = reinterpret_cast<uint32_t>(landingPad);
79 #endif
80 	// Cache the results for the phase 2 unwind, if we found a handler
81 	// and this is not a foreign exception.
82 	if (ex)
83 	{
84 		ex->handlerSwitchValue = selector;
85 		ex->catchTemp = landingPad;
86 	}
87 }
88 
89 /**
90  * Loads the saved landing pad.  Returns 1 on success, 0 on failure.
91  */
92 static int loadLandingPad(struct _Unwind_Context *context,
93                           struct _Unwind_Exception *ucb,
94                           struct __cxa_exception *ex,
95                           unsigned long *selector,
96                           dw_eh_ptr_t *landingPad)
97 {
98 #if defined(__arm__) && !defined(__ARM_DWARF_EH__)
99 	*selector = ucb->barrier_cache.bitpattern[1];
100 	*landingPad = reinterpret_cast<dw_eh_ptr_t>(ucb->barrier_cache.bitpattern[3]);
101 	return 1;
102 #else
103 	if (ex)
104 	{
105 		*selector = ex->handlerSwitchValue;
106 		*landingPad = reinterpret_cast<dw_eh_ptr_t>(ex->catchTemp);
107 		return 0;
108 	}
109 	return 0;
110 #endif
111 }
112 
113 static inline _Unwind_Reason_Code continueUnwinding(struct _Unwind_Exception *ex,
114                                                     struct _Unwind_Context *context)
115 {
116 #if defined(__arm__) && !defined(__ARM_DWARF_EH__)
117 	if (__gnu_unwind_frame(ex, context) != _URC_OK) { return _URC_FAILURE; }
118 #endif
119 	return _URC_CONTINUE_UNWIND;
120 }
121 
122 
123 extern "C" void __cxa_free_exception(void *thrown_exception);
124 extern "C" void __cxa_free_dependent_exception(void *thrown_exception);
125 extern "C" void* __dynamic_cast(const void *sub,
126                                 const __class_type_info *src,
127                                 const __class_type_info *dst,
128                                 ptrdiff_t src2dst_offset);
129 
130 /**
131  * The type of a handler that has been found.
132  */
133 typedef enum
134 {
135 	/** No handler. */
136 	handler_none,
137 	/**
138 	 * A cleanup - the exception will propagate through this frame, but code
139 	 * must be run when this happens.
140 	 */
141 	handler_cleanup,
142 	/**
143 	 * A catch statement.  The exception will not propagate past this frame
144 	 * (without an explicit rethrow).
145 	 */
146 	handler_catch
147 } handler_type;
148 
149 /**
150  * Per-thread info required by the runtime.  We store a single structure
151  * pointer in thread-local storage, because this tends to be a scarce resource
152  * and it's impolite to steal all of it and not leave any for the rest of the
153  * program.
154  *
155  * Instances of this structure are allocated lazily - at most one per thread -
156  * and are destroyed on thread termination.
157  */
158 struct __cxa_thread_info
159 {
160 	/** The termination handler for this thread. */
161 	terminate_handler terminateHandler;
162 	/** The unexpected exception handler for this thread. */
163 	unexpected_handler unexpectedHandler;
164 	/**
165 	 * The number of emergency buffers held by this thread.  This is 0 in
166 	 * normal operation - the emergency buffers are only used when malloc()
167 	 * fails to return memory for allocating an exception.  Threads are not
168 	 * permitted to hold more than 4 emergency buffers (as per recommendation
169 	 * in ABI spec [3.3.1]).
170 	 */
171 	int emergencyBuffersHeld;
172 	/**
173 	 * The exception currently running in a cleanup.
174 	 */
175 	_Unwind_Exception *currentCleanup;
176 	/**
177 	 * Our state with respect to foreign exceptions.  Usually none, set to
178 	 * caught if we have just caught an exception and rethrown if we are
179 	 * rethrowing it.
180 	 */
181 	enum
182 	{
183 		none,
184 		caught,
185 		rethrown
186 	} foreign_exception_state;
187 	/**
188 	 * The public part of this structure, accessible from outside of this
189 	 * module.
190 	 */
191 	__cxa_eh_globals globals;
192 };
193 /**
194  * Dependent exception.  This
195  */
196 struct __cxa_dependent_exception
197 {
198 #if __LP64__
199 	void *primaryException;
200 #endif
201 	std::type_info *exceptionType;
202 	void (*exceptionDestructor) (void *);
203 	unexpected_handler unexpectedHandler;
204 	terminate_handler terminateHandler;
205 	__cxa_exception *nextException;
206 	int handlerCount;
207 #if defined(__arm__) && !defined(__ARM_DWARF_EH__)
208 	_Unwind_Exception *nextCleanup;
209 	int cleanupCount;
210 #endif
211 	int handlerSwitchValue;
212 	const char *actionRecord;
213 	const char *languageSpecificData;
214 	void *catchTemp;
215 	void *adjustedPtr;
216 #if !__LP64__
217 	void *primaryException;
218 #endif
219 	_Unwind_Exception unwindHeader;
220 };
221 
222 
223 namespace std
224 {
225 	void unexpected();
226 	class exception
227 	{
228 		public:
229 			virtual ~exception() throw();
230 			virtual const char* what() const throw();
231 	};
232 
233 }
234 
235 /**
236  * Class of exceptions to distinguish between this and other exception types.
237  *
238  * The first four characters are the vendor ID.  Currently, we use GNUC,
239  * because we aim for ABI-compatibility with the GNU implementation, and
240  * various checks may test for equality of the class, which is incorrect.
241  */
242 static const uint64_t exception_class =
243 	EXCEPTION_CLASS('G', 'N', 'U', 'C', 'C', '+', '+', '\0');
244 /**
245  * Class used for dependent exceptions.
246  */
247 static const uint64_t dependent_exception_class =
248 	EXCEPTION_CLASS('G', 'N', 'U', 'C', 'C', '+', '+', '\x01');
249 /**
250  * The low four bytes of the exception class, indicating that we conform to the
251  * Itanium C++ ABI.  This is currently unused, but should be used in the future
252  * if we change our exception class, to allow this library and libsupc++ to be
253  * linked to the same executable and both to interoperate.
254  */
255 static const uint32_t abi_exception_class =
256 	GENERIC_EXCEPTION_CLASS('C', '+', '+', '\0');
257 
258 static bool isCXXException(uint64_t cls)
259 {
260 	return (cls == exception_class) || (cls == dependent_exception_class);
261 }
262 
263 static bool isDependentException(uint64_t cls)
264 {
265 	return cls == dependent_exception_class;
266 }
267 
268 static __cxa_exception *exceptionFromPointer(void *ex)
269 {
270 	return reinterpret_cast<__cxa_exception*>(static_cast<char*>(ex) -
271 			offsetof(struct __cxa_exception, unwindHeader));
272 }
273 static __cxa_exception *realExceptionFromException(__cxa_exception *ex)
274 {
275 	if (!isDependentException(ex->unwindHeader.exception_class)) { return ex; }
276 	return reinterpret_cast<__cxa_exception*>((reinterpret_cast<__cxa_dependent_exception*>(ex))->primaryException)-1;
277 }
278 
279 
280 namespace std
281 {
282 	// Forward declaration of standard library terminate() function used to
283 	// abort execution.
284 	void terminate(void);
285 }
286 
287 using namespace ABI_NAMESPACE;
288 
289 
290 
291 /** The global termination handler. */
292 static terminate_handler terminateHandler = abort;
293 /** The global unexpected exception handler. */
294 static unexpected_handler unexpectedHandler = std::terminate;
295 
296 /** Key used for thread-local data. */
297 static pthread_key_t eh_key;
298 
299 
300 /**
301  * Cleanup function, allowing foreign exception handlers to correctly destroy
302  * this exception if they catch it.
303  */
304 static void exception_cleanup(_Unwind_Reason_Code reason,
305                               struct _Unwind_Exception *ex)
306 {
307 	// Exception layout:
308 	// [__cxa_exception [_Unwind_Exception]] [exception object]
309 	//
310 	// __cxa_free_exception expects a pointer to the exception object
311 	__cxa_free_exception(static_cast<void*>(ex + 1));
312 }
313 static void dependent_exception_cleanup(_Unwind_Reason_Code reason,
314                               struct _Unwind_Exception *ex)
315 {
316 
317 	__cxa_free_dependent_exception(static_cast<void*>(ex + 1));
318 }
319 
320 /**
321  * Recursively walk a list of exceptions and delete them all in post-order.
322  */
323 static void free_exception_list(__cxa_exception *ex)
324 {
325 	if (0 != ex->nextException)
326 	{
327 		free_exception_list(ex->nextException);
328 	}
329 	// __cxa_free_exception() expects to be passed the thrown object, which
330 	// immediately follows the exception, not the exception itself
331 	__cxa_free_exception(ex+1);
332 }
333 
334 /**
335  * Cleanup function called when a thread exists to make certain that all of the
336  * per-thread data is deleted.
337  */
338 static void thread_cleanup(void* thread_info)
339 {
340 	__cxa_thread_info *info = static_cast<__cxa_thread_info*>(thread_info);
341 	if (info->globals.caughtExceptions)
342 	{
343 		// If this is a foreign exception, ask it to clean itself up.
344 		if (info->foreign_exception_state != __cxa_thread_info::none)
345 		{
346 			_Unwind_Exception *e = reinterpret_cast<_Unwind_Exception*>(info->globals.caughtExceptions);
347 			if (e->exception_cleanup)
348 				e->exception_cleanup(_URC_FOREIGN_EXCEPTION_CAUGHT, e);
349 		}
350 		else
351 		{
352 			free_exception_list(info->globals.caughtExceptions);
353 		}
354 	}
355 	free(thread_info);
356 }
357 
358 
359 /**
360  * Once control used to protect the key creation.
361  */
362 static pthread_once_t once_control = PTHREAD_ONCE_INIT;
363 
364 /**
365  * We may not be linked against a full pthread implementation.  If we're not,
366  * then we need to fake the thread-local storage by storing 'thread-local'
367  * things in a global.
368  */
369 static bool fakeTLS;
370 /**
371  * Thread-local storage for a single-threaded program.
372  */
373 static __cxa_thread_info singleThreadInfo;
374 /**
375  * Initialise eh_key.
376  */
377 static void init_key(void)
378 {
379 	if ((0 == pthread_key_create) ||
380 	    (0 == pthread_setspecific) ||
381 	    (0 == pthread_getspecific))
382 	{
383 		fakeTLS = true;
384 		return;
385 	}
386 	pthread_key_create(&eh_key, thread_cleanup);
387 	pthread_setspecific(eh_key, reinterpret_cast<void *>(0x42));
388 	fakeTLS = (pthread_getspecific(eh_key) != reinterpret_cast<void *>(0x42));
389 	pthread_setspecific(eh_key, 0);
390 }
391 
392 /**
393  * Returns the thread info structure, creating it if it is not already created.
394  */
395 static __cxa_thread_info *thread_info()
396 {
397 	if ((0 == pthread_once) || pthread_once(&once_control, init_key))
398 	{
399 		fakeTLS = true;
400 	}
401 	if (fakeTLS) { return &singleThreadInfo; }
402 	__cxa_thread_info *info = static_cast<__cxa_thread_info*>(pthread_getspecific(eh_key));
403 	if (0 == info)
404 	{
405 		info = static_cast<__cxa_thread_info*>(calloc(1, sizeof(__cxa_thread_info)));
406 		pthread_setspecific(eh_key, info);
407 	}
408 	return info;
409 }
410 /**
411  * Fast version of thread_info().  May fail if thread_info() is not called on
412  * this thread at least once already.
413  */
414 static __cxa_thread_info *thread_info_fast()
415 {
416 	if (fakeTLS) { return &singleThreadInfo; }
417 	return static_cast<__cxa_thread_info*>(pthread_getspecific(eh_key));
418 }
419 /**
420  * ABI function returning the __cxa_eh_globals structure.
421  */
422 extern "C" __cxa_eh_globals *ABI_NAMESPACE::__cxa_get_globals(void)
423 {
424 	return &(thread_info()->globals);
425 }
426 /**
427  * Version of __cxa_get_globals() assuming that __cxa_get_globals() has already
428  * been called at least once by this thread.
429  */
430 extern "C" __cxa_eh_globals *ABI_NAMESPACE::__cxa_get_globals_fast(void)
431 {
432 	return &(thread_info_fast()->globals);
433 }
434 
435 /**
436  * An emergency allocation reserved for when malloc fails.  This is treated as
437  * 16 buffers of 1KB each.
438  */
439 static char emergency_buffer[16384];
440 /**
441  * Flag indicating whether each buffer is allocated.
442  */
443 static bool buffer_allocated[16];
444 /**
445  * Lock used to protect emergency allocation.
446  */
447 static pthread_mutex_t emergency_malloc_lock = PTHREAD_MUTEX_INITIALIZER;
448 /**
449  * Condition variable used to wait when two threads are both trying to use the
450  * emergency malloc() buffer at once.
451  */
452 static pthread_cond_t emergency_malloc_wait = PTHREAD_COND_INITIALIZER;
453 
454 /**
455  * Allocates size bytes from the emergency allocation mechanism, if possible.
456  * This function will fail if size is over 1KB or if this thread already has 4
457  * emergency buffers.  If all emergency buffers are allocated, it will sleep
458  * until one becomes available.
459  */
460 static char *emergency_malloc(size_t size)
461 {
462 	if (size > 1024) { return 0; }
463 
464 	__cxa_thread_info *info = thread_info();
465 	// Only 4 emergency buffers allowed per thread!
466 	if (info->emergencyBuffersHeld > 3) { return 0; }
467 
468 	pthread_mutex_lock(&emergency_malloc_lock);
469 	int buffer = -1;
470 	while (buffer < 0)
471 	{
472 		// While we were sleeping on the lock, another thread might have free'd
473 		// enough memory for us to use, so try the allocation again - no point
474 		// using the emergency buffer if there is some real memory that we can
475 		// use...
476 		void *m = calloc(1, size);
477 		if (0 != m)
478 		{
479 			pthread_mutex_unlock(&emergency_malloc_lock);
480 			return static_cast<char*>(m);
481 		}
482 		for (int i=0 ; i<16 ; i++)
483 		{
484 			if (!buffer_allocated[i])
485 			{
486 				buffer = i;
487 				buffer_allocated[i] = true;
488 				break;
489 			}
490 		}
491 		// If there still isn't a buffer available, then sleep on the condition
492 		// variable.  This will be signalled when another thread releases one
493 		// of the emergency buffers.
494 		if (buffer < 0)
495 		{
496 			pthread_cond_wait(&emergency_malloc_wait, &emergency_malloc_lock);
497 		}
498 	}
499 	pthread_mutex_unlock(&emergency_malloc_lock);
500 	info->emergencyBuffersHeld++;
501 	return emergency_buffer + (1024 * buffer);
502 }
503 
504 /**
505  * Frees a buffer returned by emergency_malloc().
506  *
507  * Note: Neither this nor emergency_malloc() is particularly efficient.  This
508  * should not matter, because neither will be called in normal operation - they
509  * are only used when the program runs out of memory, which should not happen
510  * often.
511  */
512 static void emergency_malloc_free(char *ptr)
513 {
514 	int buffer = -1;
515 	// Find the buffer corresponding to this pointer.
516 	for (int i=0 ; i<16 ; i++)
517 	{
518 		if (ptr == static_cast<void*>(emergency_buffer + (1024 * i)))
519 		{
520 			buffer = i;
521 			break;
522 		}
523 	}
524 	assert(buffer >= 0 &&
525 	       "Trying to free something that is not an emergency buffer!");
526 	// emergency_malloc() is expected to return 0-initialized data.  We don't
527 	// zero the buffer when allocating it, because the static buffers will
528 	// begin life containing 0 values.
529 	memset(ptr, 0, 1024);
530 	// Signal the condition variable to wake up any threads that are blocking
531 	// waiting for some space in the emergency buffer
532 	pthread_mutex_lock(&emergency_malloc_lock);
533 	// In theory, we don't need to do this with the lock held.  In practice,
534 	// our array of bools will probably be updated using 32-bit or 64-bit
535 	// memory operations, so this update may clobber adjacent values.
536 	buffer_allocated[buffer] = false;
537 	pthread_cond_signal(&emergency_malloc_wait);
538 	pthread_mutex_unlock(&emergency_malloc_lock);
539 }
540 
541 static char *alloc_or_die(size_t size)
542 {
543 	char *buffer = static_cast<char*>(calloc(1, size));
544 
545 	// If calloc() doesn't want to give us any memory, try using an emergency
546 	// buffer.
547 	if (0 == buffer)
548 	{
549 		buffer = emergency_malloc(size);
550 		// This is only reached if the allocation is greater than 1KB, and
551 		// anyone throwing objects that big really should know better.
552 		if (0 == buffer)
553 		{
554 			fprintf(stderr, "Out of memory attempting to allocate exception\n");
555 			std::terminate();
556 		}
557 	}
558 	return buffer;
559 }
560 static void free_exception(char *e)
561 {
562 	// If this allocation is within the address range of the emergency buffer,
563 	// don't call free() because it was not allocated with malloc()
564 	if ((e >= emergency_buffer) &&
565 	    (e < (emergency_buffer + sizeof(emergency_buffer))))
566 	{
567 		emergency_malloc_free(e);
568 	}
569 	else
570 	{
571 		free(e);
572 	}
573 }
574 
575 #ifdef __LP64__
576 /**
577  * There's an ABI bug in __cxa_exception: unwindHeader requires 16-byte
578  * alignment but it was broken by the addition of the referenceCount.
579  * The unwindHeader is at offset 0x58 in __cxa_exception.  In order to keep
580  * compatibility with consumers of the broken __cxa_exception, explicitly add
581  * padding on allocation (and account for it on free).
582  */
583 static const int exception_alignment_padding = 8;
584 #else
585 static const int exception_alignment_padding = 0;
586 #endif
587 
588 /**
589  * Allocates an exception structure.  Returns a pointer to the space that can
590  * be used to store an object of thrown_size bytes.  This function will use an
591  * emergency buffer if malloc() fails, and may block if there are no such
592  * buffers available.
593  */
594 extern "C" void *__cxa_allocate_exception(size_t thrown_size)
595 {
596 	size_t size = exception_alignment_padding + sizeof(__cxa_exception) +
597 	    thrown_size;
598 	char *buffer = alloc_or_die(size);
599 	return buffer + exception_alignment_padding + sizeof(__cxa_exception);
600 }
601 
602 extern "C" void *__cxa_allocate_dependent_exception(void)
603 {
604 	size_t size = exception_alignment_padding +
605 	    sizeof(__cxa_dependent_exception);
606 	char *buffer = alloc_or_die(size);
607 	return buffer + exception_alignment_padding +
608 	    sizeof(__cxa_dependent_exception);
609 }
610 
611 /**
612  * __cxa_free_exception() is called when an exception was thrown in between
613  * calling __cxa_allocate_exception() and actually throwing the exception.
614  * This happens when the object's copy constructor throws an exception.
615  *
616  * In this implementation, it is also called by __cxa_end_catch() and during
617  * thread cleanup.
618  */
619 extern "C" void __cxa_free_exception(void *thrown_exception)
620 {
621 	__cxa_exception *ex = reinterpret_cast<__cxa_exception*>(thrown_exception) - 1;
622 	// Free the object that was thrown, calling its destructor
623 	if (0 != ex->exceptionDestructor)
624 	{
625 		try
626 		{
627 			ex->exceptionDestructor(thrown_exception);
628 		}
629 		catch(...)
630 		{
631 			// FIXME: Check that this is really what the spec says to do.
632 			std::terminate();
633 		}
634 	}
635 
636 	free_exception(reinterpret_cast<char*>(ex) -
637 	    exception_alignment_padding);
638 }
639 
640 static void releaseException(__cxa_exception *exception)
641 {
642 	if (isDependentException(exception->unwindHeader.exception_class))
643 	{
644 		__cxa_free_dependent_exception(exception+1);
645 		return;
646 	}
647 	if (__sync_sub_and_fetch(&exception->referenceCount, 1) == 0)
648 	{
649 		// __cxa_free_exception() expects to be passed the thrown object,
650 		// which immediately follows the exception, not the exception
651 		// itself
652 		__cxa_free_exception(exception+1);
653 	}
654 }
655 
656 void __cxa_free_dependent_exception(void *thrown_exception)
657 {
658 	__cxa_dependent_exception *ex = reinterpret_cast<__cxa_dependent_exception*>(thrown_exception) - 1;
659 	assert(isDependentException(ex->unwindHeader.exception_class));
660 	if (ex->primaryException)
661 	{
662 		releaseException(realExceptionFromException(reinterpret_cast<__cxa_exception*>(ex)));
663 	}
664 	free_exception(reinterpret_cast<char*>(ex) -
665 	    exception_alignment_padding);
666 }
667 
668 /**
669  * Callback function used with _Unwind_Backtrace().
670  *
671  * Prints a stack trace.  Used only for debugging help.
672  *
673  * Note: As of FreeBSD 8.1, dladd() still doesn't work properly, so this only
674  * correctly prints function names from public, relocatable, symbols.
675  */
676 static _Unwind_Reason_Code trace(struct _Unwind_Context *context, void *c)
677 {
678 	Dl_info myinfo;
679 	int mylookup =
680 		dladdr(reinterpret_cast<void *>(__cxa_current_exception_type), &myinfo);
681 	void *ip = reinterpret_cast<void*>(_Unwind_GetIP(context));
682 	Dl_info info;
683 	if (dladdr(ip, &info) != 0)
684 	{
685 		if (mylookup == 0 || strcmp(info.dli_fname, myinfo.dli_fname) != 0)
686 		{
687 			printf("%p:%s() in %s\n", ip, info.dli_sname, info.dli_fname);
688 		}
689 	}
690 	return _URC_CONTINUE_UNWIND;
691 }
692 
693 /**
694  * Report a failure that occurred when attempting to throw an exception.
695  *
696  * If the failure happened by falling off the end of the stack without finding
697  * a handler, prints a back trace before aborting.
698  */
699 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)
700 extern "C" void *__cxa_begin_catch(void *e) throw();
701 #else
702 extern "C" void *__cxa_begin_catch(void *e);
703 #endif
704 static void report_failure(_Unwind_Reason_Code err, __cxa_exception *thrown_exception)
705 {
706 	switch (err)
707 	{
708 		default: break;
709 		case _URC_FATAL_PHASE1_ERROR:
710 			fprintf(stderr, "Fatal error during phase 1 unwinding\n");
711 			break;
712 #if !defined(__arm__) || defined(__ARM_DWARF_EH__)
713 		case _URC_FATAL_PHASE2_ERROR:
714 			fprintf(stderr, "Fatal error during phase 2 unwinding\n");
715 			break;
716 #endif
717 		case _URC_END_OF_STACK:
718 			__cxa_begin_catch (&(thrown_exception->unwindHeader));
719  			std::terminate();
720 			fprintf(stderr, "Terminating due to uncaught exception %p",
721 					static_cast<void*>(thrown_exception));
722 			thrown_exception = realExceptionFromException(thrown_exception);
723 			static const __class_type_info *e_ti =
724 				static_cast<const __class_type_info*>(&typeid(std::exception));
725 			const __class_type_info *throw_ti =
726 				dynamic_cast<const __class_type_info*>(thrown_exception->exceptionType);
727 			if (throw_ti)
728 			{
729 				std::exception *e =
730 					static_cast<std::exception*>(e_ti->cast_to(static_cast<void*>(thrown_exception+1),
731 							throw_ti));
732 				if (e)
733 				{
734 					fprintf(stderr, " '%s'", e->what());
735 				}
736 			}
737 
738 			size_t bufferSize = 128;
739 			char *demangled = static_cast<char*>(malloc(bufferSize));
740 			const char *mangled = thrown_exception->exceptionType->name();
741 			int status;
742 			demangled = __cxa_demangle(mangled, demangled, &bufferSize, &status);
743 			fprintf(stderr, " of type %s\n",
744 				status == 0 ? demangled : mangled);
745 			if (status == 0) { free(demangled); }
746 			// Print a back trace if no handler is found.
747 			// TODO: Make this optional
748 #ifndef __arm__
749 			_Unwind_Backtrace(trace, 0);
750 #endif
751 
752 			// Just abort. No need to call std::terminate for the second time
753 			abort();
754 			break;
755 	}
756 	std::terminate();
757 }
758 
759 static void throw_exception(__cxa_exception *ex)
760 {
761 	__cxa_thread_info *info = thread_info();
762 	ex->unexpectedHandler = info->unexpectedHandler;
763 	if (0 == ex->unexpectedHandler)
764 	{
765 		ex->unexpectedHandler = unexpectedHandler;
766 	}
767 	ex->terminateHandler  = info->terminateHandler;
768 	if (0 == ex->terminateHandler)
769 	{
770 		ex->terminateHandler = terminateHandler;
771 	}
772 	info->globals.uncaughtExceptions++;
773 
774 	_Unwind_Reason_Code err = _Unwind_RaiseException(&ex->unwindHeader);
775 	// The _Unwind_RaiseException() function should not return, it should
776 	// unwind the stack past this function.  If it does return, then something
777 	// has gone wrong.
778 	report_failure(err, ex);
779 }
780 
781 
782 /**
783  * ABI function for throwing an exception.  Takes the object to be thrown (the
784  * pointer returned by __cxa_allocate_exception()), the type info for the
785  * pointee, and the destructor (if there is one) as arguments.
786  */
787 extern "C" void __cxa_throw(void *thrown_exception,
788                             std::type_info *tinfo,
789                             void(*dest)(void*))
790 {
791 	__cxa_exception *ex = reinterpret_cast<__cxa_exception*>(thrown_exception) - 1;
792 
793 	ex->referenceCount = 1;
794 	ex->exceptionType = tinfo;
795 
796 	ex->exceptionDestructor = dest;
797 
798 	ex->unwindHeader.exception_class = exception_class;
799 	ex->unwindHeader.exception_cleanup = exception_cleanup;
800 
801 	throw_exception(ex);
802 }
803 
804 extern "C" void __cxa_rethrow_primary_exception(void* thrown_exception)
805 {
806 	if (NULL == thrown_exception) { return; }
807 
808 	__cxa_exception *original = exceptionFromPointer(thrown_exception);
809 	__cxa_dependent_exception *ex = reinterpret_cast<__cxa_dependent_exception*>(__cxa_allocate_dependent_exception())-1;
810 
811 	ex->primaryException = thrown_exception;
812 	__cxa_increment_exception_refcount(thrown_exception);
813 
814 	ex->exceptionType = original->exceptionType;
815 	ex->unwindHeader.exception_class = dependent_exception_class;
816 	ex->unwindHeader.exception_cleanup = dependent_exception_cleanup;
817 
818 	throw_exception(reinterpret_cast<__cxa_exception*>(ex));
819 }
820 
821 extern "C" void *__cxa_current_primary_exception(void)
822 {
823 	__cxa_eh_globals* globals = __cxa_get_globals();
824 	__cxa_exception *ex = globals->caughtExceptions;
825 
826 	if (0 == ex) { return NULL; }
827 	ex = realExceptionFromException(ex);
828 	__sync_fetch_and_add(&ex->referenceCount, 1);
829 	return ex + 1;
830 }
831 
832 extern "C" void __cxa_increment_exception_refcount(void* thrown_exception)
833 {
834 	if (NULL == thrown_exception) { return; }
835 	__cxa_exception *ex = static_cast<__cxa_exception*>(thrown_exception) - 1;
836 	if (isDependentException(ex->unwindHeader.exception_class)) { return; }
837 	__sync_fetch_and_add(&ex->referenceCount, 1);
838 }
839 extern "C" void __cxa_decrement_exception_refcount(void* thrown_exception)
840 {
841 	if (NULL == thrown_exception) { return; }
842 	__cxa_exception *ex = static_cast<__cxa_exception*>(thrown_exception) - 1;
843 	releaseException(ex);
844 }
845 
846 /**
847  * ABI function.  Rethrows the current exception.  Does not remove the
848  * exception from the stack or decrement its handler count - the compiler is
849  * expected to set the landing pad for this function to the end of the catch
850  * block, and then call _Unwind_Resume() to continue unwinding once
851  * __cxa_end_catch() has been called and any cleanup code has been run.
852  */
853 extern "C" void __cxa_rethrow()
854 {
855 	__cxa_thread_info *ti = thread_info();
856 	__cxa_eh_globals *globals = &ti->globals;
857 	// Note: We don't remove this from the caught list here, because
858 	// __cxa_end_catch will be called when we unwind out of the try block.  We
859 	// could probably make this faster by providing an alternative rethrow
860 	// function and ensuring that all cleanup code is run before calling it, so
861 	// we can skip the top stack frame when unwinding.
862 	__cxa_exception *ex = globals->caughtExceptions;
863 
864 	if (0 == ex)
865 	{
866 		fprintf(stderr,
867 		        "Attempting to rethrow an exception that doesn't exist!\n");
868 		std::terminate();
869 	}
870 
871 	if (ti->foreign_exception_state != __cxa_thread_info::none)
872 	{
873 		ti->foreign_exception_state = __cxa_thread_info::rethrown;
874 		_Unwind_Exception *e = reinterpret_cast<_Unwind_Exception*>(ex);
875 		_Unwind_Reason_Code err = _Unwind_Resume_or_Rethrow(e);
876 		report_failure(err, ex);
877 		return;
878 	}
879 
880 	assert(ex->handlerCount > 0 && "Rethrowing uncaught exception!");
881 
882 	// `globals->uncaughtExceptions` was decremented by `__cxa_begin_catch`.
883 	// It's normally incremented by `throw_exception`, but this path invokes
884 	// `_Unwind_Resume_or_Rethrow` directly to rethrow the exception.
885 	// This path is only reachable if we're rethrowing a C++ exception -
886 	// foreign exceptions don't adjust any of this state.
887 	globals->uncaughtExceptions++;
888 
889 	// ex->handlerCount will be decremented in __cxa_end_catch in enclosing
890 	// catch block
891 
892 	// Make handler count negative. This will tell __cxa_end_catch that
893 	// exception was rethrown and exception object should not be destroyed
894 	// when handler count become zero
895 	ex->handlerCount = -ex->handlerCount;
896 
897 	// Continue unwinding the stack with this exception.  This should unwind to
898 	// the place in the caller where __cxa_end_catch() is called.  The caller
899 	// will then run cleanup code and bounce the exception back with
900 	// _Unwind_Resume().
901 	_Unwind_Reason_Code err = _Unwind_Resume_or_Rethrow(&ex->unwindHeader);
902 	report_failure(err, ex);
903 }
904 
905 /**
906  * Returns the type_info object corresponding to the filter.
907  */
908 static std::type_info *get_type_info_entry(_Unwind_Context *context,
909                                            dwarf_eh_lsda *lsda,
910                                            int filter)
911 {
912 	// Get the address of the record in the table.
913 	dw_eh_ptr_t record = lsda->type_table -
914 		dwarf_size_of_fixed_size_field(lsda->type_table_encoding)*filter;
915 	//record -= 4;
916 	dw_eh_ptr_t start = record;
917 	// Read the value, but it's probably an indirect reference...
918 	int64_t offset = read_value(lsda->type_table_encoding, &record);
919 
920 	// (If the entry is 0, don't try to dereference it.  That would be bad.)
921 	if (offset == 0) { return 0; }
922 
923 	// ...so we need to resolve it
924 	return reinterpret_cast<std::type_info*>(resolve_indirect_value(context,
925 			lsda->type_table_encoding, offset, start));
926 }
927 
928 
929 
930 /**
931  * Checks the type signature found in a handler against the type of the thrown
932  * object.  If ex is 0 then it is assumed to be a foreign exception and only
933  * matches cleanups.
934  */
935 static bool check_type_signature(__cxa_exception *ex,
936                                  const std::type_info *type,
937                                  void *&adjustedPtr)
938 {
939 	void *exception_ptr = static_cast<void*>(ex+1);
940 	const std::type_info *ex_type = ex ? ex->exceptionType : 0;
941 
942 	bool is_ptr = ex ? ex_type->__is_pointer_p() : false;
943 	if (is_ptr)
944 	{
945 		exception_ptr = *static_cast<void**>(exception_ptr);
946 	}
947 	// Always match a catchall, even with a foreign exception
948 	//
949 	// Note: A 0 here is a catchall, not a cleanup, so we return true to
950 	// indicate that we found a catch.
951 	if (0 == type)
952 	{
953 		if (ex)
954 		{
955 			adjustedPtr = exception_ptr;
956 		}
957 		return true;
958 	}
959 
960 	if (0 == ex) { return false; }
961 
962 	// If the types are the same, no casting is needed.
963 	if (*type == *ex_type)
964 	{
965 		adjustedPtr = exception_ptr;
966 		return true;
967 	}
968 
969 
970 	if (type->__do_catch(ex_type, &exception_ptr, 1))
971 	{
972 		adjustedPtr = exception_ptr;
973 		return true;
974 	}
975 
976 	return false;
977 }
978 /**
979  * Checks whether the exception matches the type specifiers in this action
980  * record.  If the exception only matches cleanups, then this returns false.
981  * If it matches a catch (including a catchall) then it returns true.
982  *
983  * The selector argument is used to return the selector that is passed in the
984  * second exception register when installing the context.
985  */
986 static handler_type check_action_record(_Unwind_Context *context,
987                                         dwarf_eh_lsda *lsda,
988                                         dw_eh_ptr_t action_record,
989                                         __cxa_exception *ex,
990                                         unsigned long *selector,
991                                         void *&adjustedPtr)
992 {
993 	if (!action_record) { return handler_cleanup; }
994 	handler_type found = handler_none;
995 	while (action_record)
996 	{
997 		int filter = read_sleb128(&action_record);
998 		dw_eh_ptr_t action_record_offset_base = action_record;
999 		int displacement = read_sleb128(&action_record);
1000 		action_record = displacement ?
1001 			action_record_offset_base + displacement : 0;
1002 		// We only check handler types for C++ exceptions - foreign exceptions
1003 		// are only allowed for cleanups and catchalls.
1004 		if (filter > 0)
1005 		{
1006 			std::type_info *handler_type = get_type_info_entry(context, lsda, filter);
1007 			if (check_type_signature(ex, handler_type, adjustedPtr))
1008 			{
1009 				*selector = filter;
1010 				return handler_catch;
1011 			}
1012 		}
1013 		else if (filter < 0 && 0 != ex)
1014 		{
1015 			bool matched = false;
1016 			*selector = filter;
1017 #if defined(__arm__) && !defined(__ARM_DWARF_EH__)
1018 			filter++;
1019 			std::type_info *handler_type = get_type_info_entry(context, lsda, filter--);
1020 			while (handler_type)
1021 			{
1022 				if (check_type_signature(ex, handler_type, adjustedPtr))
1023 				{
1024 					matched = true;
1025 					break;
1026 				}
1027 				handler_type = get_type_info_entry(context, lsda, filter--);
1028 			}
1029 #else
1030 			unsigned char *type_index = reinterpret_cast<unsigned char*>(lsda->type_table) - filter - 1;
1031 			while (*type_index)
1032 			{
1033 				std::type_info *handler_type = get_type_info_entry(context, lsda, *(type_index++));
1034 				// If the exception spec matches a permitted throw type for
1035 				// this function, don't report a handler - we are allowed to
1036 				// propagate this exception out.
1037 				if (check_type_signature(ex, handler_type, adjustedPtr))
1038 				{
1039 					matched = true;
1040 					break;
1041 				}
1042 			}
1043 #endif
1044 			if (matched) { continue; }
1045 			// If we don't find an allowed exception spec, we need to install
1046 			// the context for this action.  The landing pad will then call the
1047 			// unexpected exception function.  Treat this as a catch
1048 			return handler_catch;
1049 		}
1050 		else if (filter == 0)
1051 		{
1052 			*selector = filter;
1053 			found = handler_cleanup;
1054 		}
1055 	}
1056 	return found;
1057 }
1058 
1059 static void pushCleanupException(_Unwind_Exception *exceptionObject,
1060                                  __cxa_exception *ex)
1061 {
1062 #if defined(__arm__) && !defined(__ARM_DWARF_EH__)
1063 	__cxa_thread_info *info = thread_info_fast();
1064 	if (ex)
1065 	{
1066 		ex->cleanupCount++;
1067 		if (ex->cleanupCount > 1)
1068 		{
1069 			assert(exceptionObject == info->currentCleanup);
1070 			return;
1071 		}
1072 		ex->nextCleanup = info->currentCleanup;
1073 	}
1074 	info->currentCleanup = exceptionObject;
1075 #endif
1076 }
1077 
1078 /**
1079  * The exception personality function.  This is referenced in the unwinding
1080  * DWARF metadata and is called by the unwind library for each C++ stack frame
1081  * containing catch or cleanup code.
1082  */
1083 extern "C"
1084 BEGIN_PERSONALITY_FUNCTION(__gxx_personality_v0)
1085 	// This personality function is for version 1 of the ABI.  If you use it
1086 	// with a future version of the ABI, it won't know what to do, so it
1087 	// reports a fatal error and give up before it breaks anything.
1088 	if (1 != version)
1089 	{
1090 		return _URC_FATAL_PHASE1_ERROR;
1091 	}
1092 	__cxa_exception *ex = 0;
1093 	__cxa_exception *realEx = 0;
1094 
1095 	// If this exception is throw by something else then we can't make any
1096 	// assumptions about its layout beyond the fields declared in
1097 	// _Unwind_Exception.
1098 	bool foreignException = !isCXXException(exceptionClass);
1099 
1100 	// If this isn't a foreign exception, then we have a C++ exception structure
1101 	if (!foreignException)
1102 	{
1103 		ex = exceptionFromPointer(exceptionObject);
1104 		realEx = realExceptionFromException(ex);
1105 	}
1106 
1107 #if defined(__arm__) && !defined(__ARM_DWARF_EH__)
1108 	unsigned char *lsda_addr =
1109 		static_cast<unsigned char*>(_Unwind_GetLanguageSpecificData(context));
1110 #else
1111 	unsigned char *lsda_addr =
1112 		reinterpret_cast<unsigned char*>(static_cast<uintptr_t>(_Unwind_GetLanguageSpecificData(context)));
1113 #endif
1114 
1115 	// No LSDA implies no landing pads - try the next frame
1116 	if (0 == lsda_addr) { return continueUnwinding(exceptionObject, context); }
1117 
1118 	// These two variables define how the exception will be handled.
1119 	dwarf_eh_action action = {0};
1120 	unsigned long selector = 0;
1121 
1122 	// During the search phase, we do a complete lookup.  If we return
1123 	// _URC_HANDLER_FOUND, then the phase 2 unwind will call this function with
1124 	// a _UA_HANDLER_FRAME action, telling us to install the handler frame.  If
1125 	// we return _URC_CONTINUE_UNWIND, we may be called again later with a
1126 	// _UA_CLEANUP_PHASE action for this frame.
1127 	//
1128 	// The point of the two-stage unwind allows us to entirely avoid any stack
1129 	// unwinding if there is no handler.  If there are just cleanups found,
1130 	// then we can just panic call an abort function.
1131 	//
1132 	// Matching a handler is much more expensive than matching a cleanup,
1133 	// because we don't need to bother doing type comparisons (or looking at
1134 	// the type table at all) for a cleanup.  This means that there is no need
1135 	// to cache the result of finding a cleanup, because it's (quite) quick to
1136 	// look it up again from the action table.
1137 	if (actions & _UA_SEARCH_PHASE)
1138 	{
1139 		struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr);
1140 
1141 		if (!dwarf_eh_find_callsite(context, &lsda, &action))
1142 		{
1143 			// EH range not found. This happens if exception is thrown and not
1144 			// caught inside a cleanup (destructor).  We should call
1145 			// terminate() in this case.  The catchTemp (landing pad) field of
1146 			// exception object will contain null when personality function is
1147 			// called with _UA_HANDLER_FRAME action for phase 2 unwinding.
1148 			return _URC_HANDLER_FOUND;
1149 		}
1150 
1151 		handler_type found_handler = check_action_record(context, &lsda,
1152 				action.action_record, realEx, &selector, ex->adjustedPtr);
1153 		// If there's no action record, we've only found a cleanup, so keep
1154 		// searching for something real
1155 		if (found_handler == handler_catch)
1156 		{
1157 			// Cache the results for the phase 2 unwind, if we found a handler
1158 			// and this is not a foreign exception.
1159 			if (ex)
1160 			{
1161 				saveLandingPad(context, exceptionObject, ex, selector, action.landing_pad);
1162 				ex->languageSpecificData = reinterpret_cast<const char*>(lsda_addr);
1163 				ex->actionRecord = reinterpret_cast<const char*>(action.action_record);
1164 				// ex->adjustedPtr is set when finding the action record.
1165 			}
1166 			return _URC_HANDLER_FOUND;
1167 		}
1168 		return continueUnwinding(exceptionObject, context);
1169 	}
1170 
1171 
1172 	// If this is a foreign exception, we didn't have anywhere to cache the
1173 	// lookup stuff, so we need to do it again.  If this is either a forced
1174 	// unwind, a foreign exception, or a cleanup, then we just install the
1175 	// context for a cleanup.
1176 	if (!(actions & _UA_HANDLER_FRAME))
1177 	{
1178 		// cleanup
1179 		struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr);
1180 		dwarf_eh_find_callsite(context, &lsda, &action);
1181 		if (0 == action.landing_pad) { return continueUnwinding(exceptionObject, context); }
1182 		handler_type found_handler = check_action_record(context, &lsda,
1183 				action.action_record, realEx, &selector, ex->adjustedPtr);
1184 		// Ignore handlers this time.
1185 		if (found_handler != handler_cleanup) { return continueUnwinding(exceptionObject, context); }
1186 		pushCleanupException(exceptionObject, ex);
1187 	}
1188 	else if (foreignException)
1189 	{
1190 		struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr);
1191 		dwarf_eh_find_callsite(context, &lsda, &action);
1192 		check_action_record(context, &lsda, action.action_record, realEx,
1193 				&selector, ex->adjustedPtr);
1194 	}
1195 	else if (ex->catchTemp == 0)
1196 	{
1197 		// Uncaught exception in cleanup, calling terminate
1198 		std::terminate();
1199 	}
1200 	else
1201 	{
1202 		// Restore the saved info if we saved some last time.
1203 		loadLandingPad(context, exceptionObject, ex, &selector, &action.landing_pad);
1204 		ex->catchTemp = 0;
1205 		ex->handlerSwitchValue = 0;
1206 	}
1207 
1208 
1209 	_Unwind_SetIP(context, reinterpret_cast<unsigned long>(action.landing_pad));
1210 	_Unwind_SetGR(context, __builtin_eh_return_data_regno(0),
1211 	              reinterpret_cast<unsigned long>(exceptionObject));
1212 	_Unwind_SetGR(context, __builtin_eh_return_data_regno(1), selector);
1213 
1214 	return _URC_INSTALL_CONTEXT;
1215 }
1216 
1217 /**
1218  * ABI function called when entering a catch statement.  The argument is the
1219  * pointer passed out of the personality function.  This is always the start of
1220  * the _Unwind_Exception object.  The return value for this function is the
1221  * pointer to the caught exception, which is either the adjusted pointer (for
1222  * C++ exceptions) of the unadjusted pointer (for foreign exceptions).
1223  */
1224 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)
1225 extern "C" void *__cxa_begin_catch(void *e) throw()
1226 #else
1227 extern "C" void *__cxa_begin_catch(void *e)
1228 #endif
1229 {
1230 	// We can't call the fast version here, because if the first exception that
1231 	// we see is a foreign exception then we won't have called it yet.
1232 	__cxa_thread_info *ti = thread_info();
1233 	__cxa_eh_globals *globals = &ti->globals;
1234 	_Unwind_Exception *exceptionObject = static_cast<_Unwind_Exception*>(e);
1235 
1236 	if (isCXXException(exceptionObject->exception_class))
1237 	{
1238 		// Only exceptions thrown with a C++ exception throwing function will
1239 		// increment this, so don't decrement it here.
1240 		globals->uncaughtExceptions--;
1241 		__cxa_exception *ex =  exceptionFromPointer(exceptionObject);
1242 
1243 		if (ex->handlerCount == 0)
1244 		{
1245 			// Add this to the front of the list of exceptions being handled
1246 			// and increment its handler count so that it won't be deleted
1247 			// prematurely.
1248 			ex->nextException = globals->caughtExceptions;
1249 			globals->caughtExceptions = ex;
1250 		}
1251 
1252 		if (ex->handlerCount < 0)
1253 		{
1254 			// Rethrown exception is catched before end of catch block.
1255 			// Clear the rethrow flag (make value positive) - we are allowed
1256 			// to delete this exception at the end of the catch block, as long
1257 			// as it isn't thrown again later.
1258 
1259 			// Code pattern:
1260 			//
1261 			// try {
1262 			//     throw x;
1263 			// }
1264 			// catch() {
1265 			//     try {
1266 			//         throw;
1267 			//     }
1268 			//     catch() {
1269 			//         __cxa_begin_catch() <- we are here
1270 			//     }
1271 			// }
1272 			ex->handlerCount = -ex->handlerCount + 1;
1273 		}
1274 		else
1275 		{
1276 			ex->handlerCount++;
1277 		}
1278 		ti->foreign_exception_state = __cxa_thread_info::none;
1279 
1280 		return ex->adjustedPtr;
1281 	}
1282 	else
1283 	{
1284 		// If this is a foreign exception, then we need to be able to
1285 		// store it.  We can't chain foreign exceptions, so we give up
1286 		// if there are already some outstanding ones.
1287 		if (globals->caughtExceptions != 0)
1288 		{
1289 			std::terminate();
1290 		}
1291 		globals->caughtExceptions = reinterpret_cast<__cxa_exception*>(exceptionObject);
1292 		ti->foreign_exception_state = __cxa_thread_info::caught;
1293 	}
1294 	// exceptionObject is the pointer to the _Unwind_Exception within the
1295 	// __cxa_exception.  The throw object is after this
1296 	return (reinterpret_cast<char*>(exceptionObject) + sizeof(_Unwind_Exception));
1297 }
1298 
1299 
1300 
1301 /**
1302  * ABI function called when exiting a catch block.  This will free the current
1303  * exception if it is no longer referenced in other catch blocks.
1304  */
1305 extern "C" void __cxa_end_catch()
1306 {
1307 	// We can call the fast version here because the slow version is called in
1308 	// __cxa_throw(), which must have been called before we end a catch block
1309 	__cxa_thread_info *ti = thread_info_fast();
1310 	__cxa_eh_globals *globals = &ti->globals;
1311 	__cxa_exception *ex = globals->caughtExceptions;
1312 
1313 	assert(0 != ex && "Ending catch when no exception is on the stack!");
1314 
1315 	if (ti->foreign_exception_state != __cxa_thread_info::none)
1316 	{
1317 		if (ti->foreign_exception_state != __cxa_thread_info::rethrown)
1318 		{
1319 			_Unwind_Exception *e = reinterpret_cast<_Unwind_Exception*>(ti->globals.caughtExceptions);
1320 			if (e->exception_cleanup)
1321 				e->exception_cleanup(_URC_FOREIGN_EXCEPTION_CAUGHT, e);
1322 		}
1323 		globals->caughtExceptions = 0;
1324 		ti->foreign_exception_state = __cxa_thread_info::none;
1325 		return;
1326 	}
1327 
1328 	bool deleteException = true;
1329 
1330 	if (ex->handlerCount < 0)
1331 	{
1332 		// exception was rethrown. Exception should not be deleted even if
1333 		// handlerCount become zero.
1334 		// Code pattern:
1335 		// try {
1336 		//     throw x;
1337 		// }
1338 		// catch() {
1339 		//     {
1340 		//         throw;
1341 		//     }
1342 		//     cleanup {
1343 		//         __cxa_end_catch();   <- we are here
1344 		//     }
1345 		// }
1346 		//
1347 
1348 		ex->handlerCount++;
1349 		deleteException = false;
1350 	}
1351 	else
1352 	{
1353 		ex->handlerCount--;
1354 	}
1355 
1356 	if (ex->handlerCount == 0)
1357 	{
1358 		globals->caughtExceptions = ex->nextException;
1359 		if (deleteException)
1360 		{
1361 			releaseException(ex);
1362 		}
1363 	}
1364 }
1365 
1366 /**
1367  * ABI function.  Returns the type of the current exception.
1368  */
1369 extern "C" std::type_info *__cxa_current_exception_type()
1370 {
1371 	__cxa_eh_globals *globals = __cxa_get_globals();
1372 	__cxa_exception *ex = globals->caughtExceptions;
1373 	return ex ? ex->exceptionType : 0;
1374 }
1375 
1376 /**
1377  * Cleanup, ensures that `__cxa_end_catch` is called to balance an explicit
1378  * `__cxa_begin_catch` call.
1379  */
1380 static void end_catch(char *)
1381 {
1382 	__cxa_end_catch();
1383 }
1384 /**
1385  * ABI function, called when an exception specification is violated.
1386  *
1387  * This function does not return.
1388  */
1389 extern "C" void __cxa_call_unexpected(void*exception)
1390 {
1391 	_Unwind_Exception *exceptionObject = static_cast<_Unwind_Exception*>(exception);
1392 	// Wrap the call to the unexpected handler in calls to `__cxa_begin_catch`
1393 	// and `__cxa_end_catch` so that we correctly update exception counts if
1394 	// the unexpected handler throws an exception.
1395 	__cxa_begin_catch(exceptionObject);
1396 	__attribute__((cleanup(end_catch)))
1397 	char unused;
1398 	if (exceptionObject->exception_class == exception_class)
1399 	{
1400 		__cxa_exception *ex =  exceptionFromPointer(exceptionObject);
1401 		if (ex->unexpectedHandler)
1402 		{
1403 			ex->unexpectedHandler();
1404 			// Should not be reached.
1405 			abort();
1406 		}
1407 	}
1408 	std::unexpected();
1409 	// Should not be reached.
1410 	abort();
1411 }
1412 
1413 /**
1414  * ABI function, returns the adjusted pointer to the exception object.
1415  */
1416 extern "C" void *__cxa_get_exception_ptr(void *exceptionObject)
1417 {
1418 	return exceptionFromPointer(exceptionObject)->adjustedPtr;
1419 }
1420 
1421 /**
1422  * As an extension, we provide the ability for the unexpected and terminate
1423  * handlers to be thread-local.  We default to the standards-compliant
1424  * behaviour where they are global.
1425  */
1426 static bool thread_local_handlers = false;
1427 
1428 
1429 namespace pathscale
1430 {
1431 	/**
1432 	 * Sets whether unexpected and terminate handlers should be thread-local.
1433 	 */
1434 	void set_use_thread_local_handlers(bool flag) throw()
1435 	{
1436 		thread_local_handlers = flag;
1437 	}
1438 	/**
1439 	 * Sets a thread-local unexpected handler.
1440 	 */
1441 	unexpected_handler set_unexpected(unexpected_handler f) throw()
1442 	{
1443 		static __cxa_thread_info *info = thread_info();
1444 		unexpected_handler old = info->unexpectedHandler;
1445 		info->unexpectedHandler = f;
1446 		return old;
1447 	}
1448 	/**
1449 	 * Sets a thread-local terminate handler.
1450 	 */
1451 	terminate_handler set_terminate(terminate_handler f) throw()
1452 	{
1453 		static __cxa_thread_info *info = thread_info();
1454 		terminate_handler old = info->terminateHandler;
1455 		info->terminateHandler = f;
1456 		return old;
1457 	}
1458 }
1459 
1460 namespace std
1461 {
1462 	/**
1463 	 * Sets the function that will be called when an exception specification is
1464 	 * violated.
1465 	 */
1466 	unexpected_handler set_unexpected(unexpected_handler f) throw()
1467 	{
1468 		if (thread_local_handlers) { return pathscale::set_unexpected(f); }
1469 
1470 		return ATOMIC_SWAP(&unexpectedHandler, f);
1471 	}
1472 	/**
1473 	 * Sets the function that is called to terminate the program.
1474 	 */
1475 	terminate_handler set_terminate(terminate_handler f) throw()
1476 	{
1477 		if (thread_local_handlers) { return pathscale::set_terminate(f); }
1478 
1479 		return ATOMIC_SWAP(&terminateHandler, f);
1480 	}
1481 	/**
1482 	 * Terminates the program, calling a custom terminate implementation if
1483 	 * required.
1484 	 */
1485 	void terminate()
1486 	{
1487 		static __cxa_thread_info *info = thread_info();
1488 		if (0 != info && 0 != info->terminateHandler)
1489 		{
1490 			info->terminateHandler();
1491 			// Should not be reached - a terminate handler is not expected to
1492 			// return.
1493 			abort();
1494 		}
1495 		terminateHandler();
1496 	}
1497 	/**
1498 	 * Called when an unexpected exception is encountered (i.e. an exception
1499 	 * violates an exception specification).  This calls abort() unless a
1500 	 * custom handler has been set..
1501 	 */
1502 	void unexpected()
1503 	{
1504 		static __cxa_thread_info *info = thread_info();
1505 		if (0 != info && 0 != info->unexpectedHandler)
1506 		{
1507 			info->unexpectedHandler();
1508 			// Should not be reached - a terminate handler is not expected to
1509 			// return.
1510 			abort();
1511 		}
1512 		unexpectedHandler();
1513 	}
1514 	/**
1515 	 * Returns whether there are any exceptions currently being thrown that
1516 	 * have not been caught.  This can occur inside a nested catch statement.
1517 	 */
1518 	bool uncaught_exception() throw()
1519 	{
1520 		__cxa_thread_info *info = thread_info();
1521 		return info->globals.uncaughtExceptions != 0;
1522 	}
1523 	/**
1524 	 * Returns the number of exceptions currently being thrown that have not
1525 	 * been caught.  This can occur inside a nested catch statement.
1526 	 */
1527 	int uncaught_exceptions() throw()
1528 	{
1529 		__cxa_thread_info *info = thread_info();
1530 		return info->globals.uncaughtExceptions;
1531 	}
1532 	/**
1533 	 * Returns the current unexpected handler.
1534 	 */
1535 	unexpected_handler get_unexpected() throw()
1536 	{
1537 		__cxa_thread_info *info = thread_info();
1538 		if (info->unexpectedHandler)
1539 		{
1540 			return info->unexpectedHandler;
1541 		}
1542 		return ATOMIC_LOAD(&unexpectedHandler);
1543 	}
1544 	/**
1545 	 * Returns the current terminate handler.
1546 	 */
1547 	terminate_handler get_terminate() throw()
1548 	{
1549 		__cxa_thread_info *info = thread_info();
1550 		if (info->terminateHandler)
1551 		{
1552 			return info->terminateHandler;
1553 		}
1554 		return ATOMIC_LOAD(&terminateHandler);
1555 	}
1556 }
1557 #if defined(__arm__) && !defined(__ARM_DWARF_EH__)
1558 extern "C" _Unwind_Exception *__cxa_get_cleanup(void)
1559 {
1560 	__cxa_thread_info *info = thread_info_fast();
1561 	_Unwind_Exception *exceptionObject = info->currentCleanup;
1562 	if (isCXXException(exceptionObject->exception_class))
1563 	{
1564 		__cxa_exception *ex =  exceptionFromPointer(exceptionObject);
1565 		ex->cleanupCount--;
1566 		if (ex->cleanupCount == 0)
1567 		{
1568 			info->currentCleanup = ex->nextCleanup;
1569 			ex->nextCleanup = 0;
1570 		}
1571 	}
1572 	else
1573 	{
1574 		info->currentCleanup = 0;
1575 	}
1576 	return exceptionObject;
1577 }
1578 
1579 asm (
1580 ".pushsection .text.__cxa_end_cleanup    \n"
1581 ".global __cxa_end_cleanup               \n"
1582 ".type __cxa_end_cleanup, \"function\"   \n"
1583 "__cxa_end_cleanup:                      \n"
1584 "	push {r1, r2, r3, r4}                \n"
1585 "	bl __cxa_get_cleanup                 \n"
1586 "	push {r1, r2, r3, r4}                \n"
1587 "	b _Unwind_Resume                     \n"
1588 "	bl abort                             \n"
1589 ".popsection                             \n"
1590 );
1591 #endif
1592