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