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