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