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