exception.cc revision 227825
1309466Sngie#include <stdlib.h>
2272343Sngie#include <dlfcn.h>
3272343Sngie#include <stdio.h>
4272343Sngie#include <string.h>
5272343Sngie#include <pthread.h>
6272343Sngie#include "typeinfo.h"
7272343Sngie#include "dwarf_eh.h"
8272343Sngie#include "cxxabi.h"
9272343Sngie
10272343Sngieusing namespace ABI_NAMESPACE;
11272343Sngie
12272343Sngieextern "C" void __cxa_free_exception(void *thrown_exception);
13272343Sngieextern "C" void __cxa_free_dependent_exception(void *thrown_exception);
14272343Sngieextern "C" void* __dynamic_cast(const void *sub,
15272343Sngie                                const __class_type_info *src,
16272343Sngie                                const __class_type_info *dst,
17272343Sngie                                ptrdiff_t src2dst_offset);
18272343Sngie
19272343Sngie/**
20272343Sngie * The type of a handler that has been found.
21272343Sngie */
22272343Sngietypedef enum
23272343Sngie{
24272343Sngie	/** No handler. */
25272343Sngie	handler_none,
26272343Sngie	/**
27272343Sngie	 * A cleanup - the exception will propagate through this frame, but code
28272343Sngie	 * must be run when this happens.
29272343Sngie	 */
30272343Sngie	handler_cleanup,
31272343Sngie	/**
32309466Sngie	 * A catch statement.  The exception will not propagate past this frame
33272343Sngie	 * (without an explicit rethrow).
34272343Sngie	 */
35272343Sngie	handler_catch
36272343Sngie} handler_type;
37272343Sngie
38272343Sngie/**
39272343Sngie * Per-thread info required by the runtime.  We store a single structure
40272343Sngie * pointer in thread-local storage, because this tends to be a scarce resource
41272343Sngie * and it's impolite to steal all of it and not leave any for the rest of the
42272343Sngie * program.
43272343Sngie *
44272343Sngie * Instances of this structure are allocated lazily - at most one per thread -
45272343Sngie * and are destroyed on thread termination.
46272343Sngie */
47273540Sngiestruct __cxa_thread_info
48272343Sngie{
49273540Sngie	/** The termination handler for this thread. */
50272343Sngie	terminate_handler terminateHandler;
51272343Sngie	/** The unexpected exception handler for this thread. */
52272343Sngie	unexpected_handler unexpectedHandler;
53272343Sngie	/**
54272343Sngie	 * The number of emergency buffers held by this thread.  This is 0 in
55272343Sngie	 * normal operation - the emergency buffers are only used when malloc()
56272343Sngie	 * fails to return memory for allocating an exception.  Threads are not
57272343Sngie	 * permitted to hold more than 4 emergency buffers (as per recommendation
58272343Sngie	 * in ABI spec [3.3.1]).
59272343Sngie	 */
60272343Sngie	int emergencyBuffersHeld;
61272343Sngie	/**
62272343Sngie	 * The public part of this structure, accessible from outside of this
63272343Sngie	 * module.
64272343Sngie	 */
65272343Sngie	__cxa_eh_globals globals;
66272343Sngie};
67272343Sngie/**
68272343Sngie * Dependent exception.  This
69272343Sngie */
70272343Sngiestruct __cxa_dependent_exception
71272343Sngie{
72272343Sngie#if __LP64__
73272343Sngie	void *primaryException;
74272343Sngie#endif
75272343Sngie	std::type_info *exceptionType;
76272343Sngie	void (*exceptionDestructor) (void *);
77272343Sngie	unexpected_handler unexpectedHandler;
78272343Sngie	terminate_handler terminateHandler;
79272343Sngie	__cxa_exception *nextException;
80272343Sngie	int handlerCount;
81309466Sngie	int handlerSwitchValue;
82272343Sngie	const char *actionRecord;
83272343Sngie	const char *languageSpecificData;
84272343Sngie	void *catchTemp;
85272343Sngie	void *adjustedPtr;
86272343Sngie#if !__LP64__
87272343Sngie	void *primaryException;
88272343Sngie#endif
89272343Sngie	_Unwind_Exception unwindHeader;
90272343Sngie};
91272343Sngie
92272343Sngie
93272343Sngienamespace std
94272343Sngie{
95272343Sngie	void unexpected();
96272343Sngie	class exception
97272343Sngie	{
98272343Sngie		public:
99272343Sngie			virtual ~exception() throw();
100272343Sngie			virtual const char* what() const throw();
101272343Sngie	};
102272343Sngie
103272343Sngie}
104272343Sngie
105272343Sngieextern "C" std::type_info *__cxa_current_exception_type();
106272343Sngie
107272343Sngie/**
108272343Sngie * Class of exceptions to distinguish between this and other exception types.
109272343Sngie *
110272343Sngie * The first four characters are the vendor ID.  Currently, we use GNUC,
111272343Sngie * because we aim for ABI-compatibility with the GNU implementation, and
112272343Sngie * various checks may test for equality of the class, which is incorrect.
113272343Sngie */
114272343Sngiestatic const uint64_t exception_class =
115272343Sngie	EXCEPTION_CLASS('G', 'N', 'U', 'C', 'C', '+', '+', '\0');
116272343Sngie/**
117272343Sngie * Class used for dependent exceptions.
118272343Sngie */
119350328Sbrooksstatic const uint64_t dependent_exception_class =
120272343Sngie	EXCEPTION_CLASS('G', 'N', 'U', 'C', 'C', '+', '+', '\x01');
121272343Sngie/**
122272343Sngie * The low four bytes of the exception class, indicating that we conform to the
123272343Sngie * Itanium C++ ABI.  This is currently unused, but should be used in the future
124272343Sngie * if we change our exception class, to allow this library and libsupc++ to be
125272343Sngie * linked to the same executable and both to interoperate.
126272343Sngie */
127272343Sngiestatic const uint32_t abi_exception_class =
128272343Sngie	GENERIC_EXCEPTION_CLASS('C', '+', '+', '\0');
129272343Sngie
130272343Sngiestatic bool isCXXException(uint64_t cls)
131272343Sngie{
132272343Sngie	return (cls == exception_class) || (cls == dependent_exception_class);
133272343Sngie}
134272343Sngie
135272343Sngiestatic bool isDependentException(uint64_t cls)
136272343Sngie{
137272343Sngie	return cls == dependent_exception_class;
138272343Sngie}
139272343Sngie
140272343Sngiestatic __cxa_exception *exceptionFromPointer(void *ex)
141272343Sngie{
142272343Sngie	return (__cxa_exception*)((char*)ex -
143272343Sngie			offsetof(struct __cxa_exception, unwindHeader));
144272343Sngie}
145272343Sngiestatic __cxa_exception *realExceptionFromException(__cxa_exception *ex)
146272343Sngie{
147272343Sngie	if (!isDependentException(ex->unwindHeader.exception_class)) { return ex; }
148272343Sngie	return ((__cxa_exception*)(((__cxa_dependent_exception*)ex)->primaryException))-1;
149272343Sngie}
150272343Sngie
151272343Sngie
152272343Sngienamespace std
153272343Sngie{
154272343Sngie	// Forward declaration of standard library terminate() function used to
155272343Sngie	// abort execution.
156272343Sngie	void terminate(void);
157272343Sngie}
158272343Sngie
159272343Sngieusing namespace ABI_NAMESPACE;
160272343Sngie
161272343Sngie
162273540Sngie
163272343Sngie/** The global termination handler. */
164272343Sngiestatic terminate_handler terminateHandler = abort;
165272343Sngie/** The global unexpected exception handler. */
166272343Sngiestatic unexpected_handler unexpectedHandler = std::terminate;
167272343Sngie
168272343Sngie/** Key used for thread-local data. */
169272343Sngiestatic pthread_key_t eh_key;
170272343Sngie
171272343Sngie
172272343Sngie/**
173272343Sngie * Cleanup function, allowing foreign exception handlers to correctly destroy
174272343Sngie * this exception if they catch it.
175272343Sngie */
176272343Sngiestatic void exception_cleanup(_Unwind_Reason_Code reason,
177272343Sngie                              struct _Unwind_Exception *ex)
178272343Sngie{
179272343Sngie	__cxa_free_exception((void*)ex);
180272343Sngie}
181272343Sngiestatic void dependent_exception_cleanup(_Unwind_Reason_Code reason,
182272343Sngie                              struct _Unwind_Exception *ex)
183272343Sngie{
184272343Sngie
185272343Sngie	__cxa_free_dependent_exception((void*)ex);
186272343Sngie}
187272343Sngie
188272343Sngie/**
189272343Sngie * Recursively walk a list of exceptions and delete them all in post-order.
190272343Sngie */
191272343Sngiestatic void free_exception_list(__cxa_exception *ex)
192272343Sngie{
193272343Sngie	if (0 != ex->nextException)
194309466Sngie	{
195309466Sngie		free_exception_list(ex->nextException);
196309466Sngie	}
197309466Sngie	// __cxa_free_exception() expects to be passed the thrown object, which
198309466Sngie	// immediately follows the exception, not the exception itself
199309466Sngie	__cxa_free_exception(ex+1);
200272343Sngie}
201272343Sngie
202272343Sngie/**
203272343Sngie * Cleanup function called when a thread exists to make certain that all of the
204272343Sngie * per-thread data is deleted.
205272343Sngie */
206272343Sngiestatic void thread_cleanup(void* thread_info)
207272343Sngie{
208272343Sngie	__cxa_thread_info *info = (__cxa_thread_info*)thread_info;
209272343Sngie	if (info->globals.caughtExceptions)
210272343Sngie	{
211272343Sngie		free_exception_list(info->globals.caughtExceptions);
212272343Sngie	}
213272343Sngie	free(thread_info);
214272343Sngie}
215272343Sngie
216272343Sngie
217272343Sngie/**
218272343Sngie * Once control used to protect the key creation.
219272343Sngie */
220272343Sngiestatic pthread_once_t once_control = PTHREAD_ONCE_INIT;
221272343Sngie
222272343Sngie/**
223272343Sngie * Initialise eh_key.
224272343Sngie */
225272343Sngiestatic void init_key(void)
226272343Sngie{
227272343Sngie	pthread_key_create(&eh_key, thread_cleanup);
228272343Sngie}
229272343Sngie
230272343Sngie/**
231272343Sngie * Returns the thread info structure, creating it if it is not already created.
232272343Sngie */
233272343Sngiestatic __cxa_thread_info *thread_info()
234272343Sngie{
235272343Sngie	pthread_once(&once_control, init_key);
236272343Sngie	__cxa_thread_info *info = (__cxa_thread_info*)pthread_getspecific(eh_key);
237272343Sngie	if (0 == info)
238272343Sngie	{
239272343Sngie		info = (__cxa_thread_info*)calloc(1, sizeof(__cxa_thread_info));
240272343Sngie		pthread_setspecific(eh_key, info);
241272343Sngie	}
242272343Sngie	return info;
243272343Sngie}
244272343Sngie/**
245272343Sngie * Fast version of thread_info().  May fail if thread_info() is not called on
246272343Sngie * this thread at least once already.
247272343Sngie */
248272343Sngiestatic __cxa_thread_info *thread_info_fast()
249272343Sngie{
250272343Sngie	return (__cxa_thread_info*)pthread_getspecific(eh_key);
251273540Sngie}
252272343Sngie/**
253272343Sngie * ABI function returning the __cxa_eh_globals structure.
254272343Sngie */
255272343Sngieextern "C" __cxa_eh_globals *ABI_NAMESPACE::__cxa_get_globals(void)
256272343Sngie{
257272343Sngie	return &(thread_info()->globals);
258272343Sngie}
259272343Sngie/**
260272343Sngie * Version of __cxa_get_globals() assuming that __cxa_get_globals() has already
261272343Sngie * been called at least once by this thread.
262272343Sngie */
263272343Sngieextern "C" __cxa_eh_globals *ABI_NAMESPACE::__cxa_get_globals_fast(void)
264272343Sngie{
265272343Sngie	return &(thread_info_fast()->globals);
266272343Sngie}
267272343Sngie
268309466Sngie/**
269272343Sngie * An emergency allocation reserved for when malloc fails.  This is treated as
270272343Sngie * 16 buffers of 1KB each.
271272343Sngie */
272272343Sngiestatic char emergency_buffer[16384];
273272343Sngie/**
274272343Sngie * Flag indicating whether each buffer is allocated.
275272343Sngie */
276272343Sngiestatic bool buffer_allocated[16];
277272343Sngie/**
278272343Sngie * Lock used to protect emergency allocation.
279272343Sngie */
280272343Sngiestatic pthread_mutex_t emergency_malloc_lock = PTHREAD_MUTEX_INITIALIZER;
281272343Sngie/**
282272343Sngie * Condition variable used to wait when two threads are both trying to use the
283272343Sngie * emergency malloc() buffer at once.
284272343Sngie */
285272343Sngiestatic pthread_cond_t emergency_malloc_wait = PTHREAD_COND_INITIALIZER;
286272343Sngie
287272343Sngie/**
288272343Sngie * Allocates size bytes from the emergency allocation mechanism, if possible.
289272343Sngie * This function will fail if size is over 1KB or if this thread already has 4
290272343Sngie * emergency buffers.  If all emergency buffers are allocated, it will sleep
291272343Sngie * until one becomes available.
292272343Sngie */
293272343Sngiestatic char *emergency_malloc(size_t size)
294272343Sngie{
295272343Sngie	if (size > 1024) { return 0; }
296272343Sngie
297272343Sngie	__cxa_thread_info *info = thread_info();
298272343Sngie	// Only 4 emergency buffers allowed per thread!
299272343Sngie	if (info->emergencyBuffersHeld > 3) { return 0; }
300272343Sngie
301272343Sngie	pthread_mutex_lock(&emergency_malloc_lock);
302272343Sngie	int buffer = -1;
303272343Sngie	while (buffer < 0)
304272343Sngie	{
305272343Sngie		// While we were sleeping on the lock, another thread might have free'd
306272343Sngie		// enough memory for us to use, so try the allocation again - no point
307272343Sngie		// using the emergency buffer if there is some real memory that we can
308272343Sngie		// use...
309272343Sngie		void *m = calloc(1, size);
310272343Sngie		if (0 != m)
311272343Sngie		{
312272343Sngie			pthread_mutex_unlock(&emergency_malloc_lock);
313272343Sngie			return (char*)m;
314272343Sngie		}
315272343Sngie		for (int i=0 ; i<16 ; i++)
316272343Sngie		{
317272343Sngie			if (!buffer_allocated[i])
318272343Sngie			{
319272343Sngie				buffer = i;
320272343Sngie				buffer_allocated[i] = true;
321272343Sngie				break;
322272343Sngie			}
323272343Sngie		}
324272343Sngie		// If there still isn't a buffer available, then sleep on the condition
325272343Sngie		// variable.  This will be signalled when another thread releases one
326272343Sngie		// of the emergency buffers.
327272343Sngie		if (buffer < 0)
328272343Sngie		{
329272343Sngie			pthread_cond_wait(&emergency_malloc_wait, &emergency_malloc_lock);
330272343Sngie		}
331272343Sngie	}
332272343Sngie	pthread_mutex_unlock(&emergency_malloc_lock);
333272343Sngie	info->emergencyBuffersHeld++;
334272343Sngie	return emergency_buffer + (1024 * buffer);
335272343Sngie}
336272343Sngie
337272343Sngie/**
338272343Sngie * Frees a buffer returned by emergency_malloc().
339272343Sngie *
340272343Sngie * Note: Neither this nor emergency_malloc() is particularly efficient.  This
341272343Sngie * should not matter, because neither will be called in normal operation - they
342272343Sngie * are only used when the program runs out of memory, which should not happen
343272343Sngie * often.
344272343Sngie */
345272343Sngiestatic void emergency_malloc_free(char *ptr)
346272343Sngie{
347272343Sngie	int buffer = -1;
348272343Sngie	// Find the buffer corresponding to this pointer.
349272343Sngie	for (int i=0 ; i<16 ; i++)
350272343Sngie	{
351272343Sngie		if (ptr == (void*)(emergency_buffer + (1024 * i)))
352272343Sngie		{
353272343Sngie			buffer = i;
354272343Sngie			break;
355272343Sngie		}
356272343Sngie	}
357272343Sngie	assert(buffer > 0 &&
358272343Sngie	       "Trying to free something that is not an emergency buffer!");
359272343Sngie	// emergency_malloc() is expected to return 0-initialized data.  We don't
360272343Sngie	// zero the buffer when allocating it, because the static buffers will
361273540Sngie	// begin life containing 0 values.
362272343Sngie	memset((void*)ptr, 0, 1024);
363273540Sngie	// Signal the condition variable to wake up any threads that are blocking
364272343Sngie	// waiting for some space in the emergency buffer
365272343Sngie	pthread_mutex_lock(&emergency_malloc_lock);
366272343Sngie	// In theory, we don't need to do this with the lock held.  In practice,
367272343Sngie	// our array of bools will probably be updated using 32-bit or 64-bit
368272343Sngie	// 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