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