cccb4a8e0329d920d0f969bda5382b853ddf7e25
[oota-llvm.git] / runtime / GCCLibraries / crtend / C++-Exception.cpp
1 //===- C++-Exception.cpp - Exception handling support for C++ exceptions --===//
2 //
3 // This file defines the methods used to implement C++ exception handling in
4 // terms of the invoke and %llvm.unwind intrinsic.  These primitives implement
5 // an exception handling ABI similar (but simpler and more efficient than) the
6 // Itanium C++ ABI exception handling standard.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "C++-Exception.h"
11 #include <cstdlib>
12 #include <cstdarg>
13
14 //#define DEBUG
15
16 #ifdef DEBUG
17 #include <stdio.h>
18 #endif
19
20 //===----------------------------------------------------------------------===//
21 // Generic exception support
22 //
23
24 // Thread local state for exception handling.
25 // FIXME: This should really be made thread-local!
26 //
27
28 // LastCaughtException - The last exception caught by this handler.  This is for
29 // implementation of _rethrow and _get_last_caught.
30 //
31 static llvm_exception *LastCaughtException = 0;
32
33 // UncaughtExceptionStack - The stack of exceptions currently being thrown.
34 static llvm_exception *UncaughtExceptionStack = 0;
35
36 // __llvm_eh_has_uncaught_exception - This is used to implement
37 // std::uncaught_exception.
38 //
39 bool __llvm_eh_has_uncaught_exception() throw() {
40   return UncaughtExceptionStack != 0;
41 }
42
43 // __llvm_eh_current_uncaught_exception - This function checks to see if the
44 // current uncaught exception is of the specified language type.  If so, it
45 // returns a pointer to the exception area data.
46 //
47 void *__llvm_eh_current_uncaught_exception_type(unsigned HandlerType) throw() {
48   assert(UncaughtExceptionStack && "No uncaught exception!");
49   if (UncaughtExceptionStack->ExceptionType == HandlerType)
50     return UncaughtExceptionStack+1;
51   return 0;
52 }
53
54
55 //===----------------------------------------------------------------------===//
56 // C++ Specific exception handling support...
57 //
58 using namespace __cxxabiv1;
59
60 // __llvm_cxxeh_allocate_exception - This function allocates space for the
61 // specified number of bytes, plus a C++ exception object header.
62 //
63 void *__llvm_cxxeh_allocate_exception(unsigned NumBytes) throw() {
64   // FIXME: This should eventually have back-up buffers for out-of-memory
65   // situations.
66   //
67   llvm_cxx_exception *E =
68     (llvm_cxx_exception *)malloc(NumBytes+sizeof(llvm_cxx_exception));
69   E->BaseException.ExceptionType = 0; // intialize to invalid
70
71   return E+1;   // return the pointer after the header
72 }
73
74 // __llvm_cxxeh_free_exception - Low-level function to free an exception.  This
75 // is called directly from generated C++ code if evaluating the exception value
76 // into the exception location throws.  Otherwise it is called from the C++
77 // exception object destructor.
78 //
79 void __llvm_cxxeh_free_exception(void *ObjectPtr) throw() {
80   llvm_cxx_exception *E = (llvm_cxx_exception *)ObjectPtr - 1;
81   free(E);
82 }
83
84 // cxx_destructor - This function is called through the generic
85 // exception->ExceptionDestructor function pointer to destroy a caught
86 // exception.
87 //
88 static void cxx_destructor(llvm_exception *LE) /* might throw */{
89   assert(LE->Next == 0 && "On the uncaught stack??");
90   llvm_cxx_exception *E = get_cxx_exception(LE);
91
92   struct ExceptionFreer {
93     void *Ptr;
94     ExceptionFreer(void *P) : Ptr(P) {}
95     ~ExceptionFreer() {
96       // Free the memory for the exception, when the function is left, even if
97       // the exception object dtor throws its own exception!
98       __llvm_cxxeh_free_exception(Ptr);
99     }
100   } EF(E+1);
101   
102   // Run the exception object dtor if it exists. */
103   if (E->ExceptionObjectDestructor)
104     E->ExceptionObjectDestructor(E);
105 }
106
107 // __llvm_cxxeh_throw - Given a pointer to memory which has an exception object
108 // evaluated into it, this sets up all of the fields of the exception allowing
109 // it to be thrown.  After calling this, the code should call %llvm.unwind
110 //
111 void __llvm_cxxeh_throw(void *ObjectPtr, void *TypeInfoPtr,
112                         void (*DtorPtr)(void*)) throw() {
113   llvm_cxx_exception *E = (llvm_cxx_exception *)ObjectPtr - 1;
114   E->BaseException.ExceptionDestructor = cxx_destructor;
115   E->BaseException.ExceptionType = CXXException;
116   E->BaseException.Next = UncaughtExceptionStack;
117   UncaughtExceptionStack = &E->BaseException;
118   E->BaseException.HandlerCount = 0;
119   E->BaseException.isRethrown = 0;
120
121   E->TypeInfo = (const std::type_info*)TypeInfoPtr;
122   E->ExceptionObjectDestructor = DtorPtr;
123   E->UnexpectedHandler = __unexpected_handler;
124   E->TerminateHandler = __terminate_handler;
125 }
126
127
128 // CXXExceptionISA - use the type info object stored in the exception to see if
129 // TypeID matches and, if so, to adjust the exception object pointer.
130 //
131 static void *CXXExceptionISA(llvm_cxx_exception *E,
132                              const std::type_info *Type) throw() {
133   // ThrownPtr is a pointer to the object being thrown...
134   void *ThrownPtr = E+1;
135   const std::type_info *ThrownType = E->TypeInfo;
136
137 #if 0
138   // FIXME: this code exists in the GCC exception handling library: I haven't
139   // thought about this yet, so it should be verified at some point!
140
141   // Pointer types need to adjust the actual pointer, not
142   // the pointer to pointer that is the exception object.
143   // This also has the effect of passing pointer types
144   // "by value" through the __cxa_begin_catch return value.
145   if (ThrownType->__is_pointer_p())
146     ThrownPtr = *(void **)ThrownPtr;
147 #endif
148
149   if (Type->__do_catch(ThrownType, &ThrownPtr, 1)) {
150 #ifdef DEBUG
151     printf("isa<%s>(%s):  0x%p -> 0x%p\n", Type->name(), ThrownType->name(),
152            E+1, ThrownPtr);
153 #endif
154     return ThrownPtr;
155   }
156
157   return 0;
158 }
159
160 // __llvm_cxxeh_current_uncaught_exception_isa - This function checks to see if
161 // the current uncaught exception is a C++ exception, and if it is of the
162 // specified type id.  If so, it returns a pointer to the object adjusted as
163 // appropriate, otherwise it returns null.
164 //
165 void *__llvm_cxxeh_current_uncaught_exception_isa(void *CatchType) throw() {
166   assert(UncaughtExceptionStack && "No uncaught exception!");
167   if (UncaughtExceptionStack->ExceptionType != CXXException)
168     return 0;     // If it's not a c++ exception, it doesn't match!
169
170   // If it is a C++ exception, use the type info object stored in the exception
171   // to see if TypeID matches and, if so, to adjust the exception object
172   // pointer.
173   //
174   const std::type_info *Info = (const std::type_info *)CatchType;
175   return CXXExceptionISA(get_cxx_exception(UncaughtExceptionStack), Info);
176 }
177
178
179 // __llvm_cxxeh_begin_catch - This function is called by "exception handlers",
180 // which transition an exception from being uncaught to being caught.  It
181 // returns a pointer to the exception object portion of the exception.  This
182 // function must work with foreign exceptions.
183 //
184 void *__llvm_cxxeh_begin_catch() throw() {
185   llvm_exception *E = UncaughtExceptionStack;
186   assert(UncaughtExceptionStack && "There are no uncaught exceptions!?!?");
187
188   // The exception is now no longer uncaught.
189   UncaughtExceptionStack = E->Next;
190   
191   // The exception is now caught.
192   LastCaughtException = E;
193   E->Next = 0;
194   E->isRethrown = 0;
195
196   // Increment the handler count for this exception.
197   E->HandlerCount++;
198
199 #ifdef DEBUG
200   printf("Exiting begin_catch Ex=0x%p HandlerCount=%d!\n", E+1,
201          E->HandlerCount);
202 #endif
203   
204   // Return a pointer to the raw exception object.
205   return E+1;
206 }
207
208 // __llvm_cxxeh_begin_catch_if_isa - This function checks to see if the current
209 // uncaught exception is of the specified type.  If not, it returns a null
210 // pointer, otherwise it 'catches' the exception and returns a pointer to the
211 // object of the specified type.  This function does never succeeds with foreign
212 // exceptions (because they can never be of type CatchType).
213 //
214 void *__llvm_cxxeh_begin_catch_if_isa(void *CatchType) throw() {
215   void *ObjPtr = __llvm_cxxeh_current_uncaught_exception_isa(CatchType);
216   if (!ObjPtr) return 0;
217   
218   // begin_catch, meaning that the object is now "caught", not "uncaught"
219   __llvm_cxxeh_begin_catch();
220   return ObjPtr;
221 }
222
223 // __llvm_cxxeh_get_last_caught - Return the last exception that was caught by
224 // ...begin_catch.
225 //
226 void *__llvm_cxxeh_get_last_caught() throw() {
227   assert(LastCaughtException && "No exception caught!!");
228   return LastCaughtException+1;
229 }
230
231 // __llvm_cxxeh_end_catch - This function decrements the HandlerCount of the
232 // top-level caught exception, destroying it if this is the last handler for the
233 // exception.
234 //
235 void __llvm_cxxeh_end_catch(void *Ex) /* might throw */ {
236   llvm_exception *E = (llvm_exception*)Ex - 1;
237   assert(E && "There are no caught exceptions!");
238   
239   // If this is the last handler using the exception, destroy it now!
240   if (--E->HandlerCount == 0 && !E->isRethrown) {
241 #ifdef DEBUG
242     printf("Destroying exception!\n");
243 #endif
244     E->ExceptionDestructor(E);        // Release memory for the exception
245   }
246 #ifdef DEBUG
247   printf("Exiting end_catch Ex=0x%p HandlerCount=%d!\n", Ex, E->HandlerCount);
248 #endif
249 }
250
251 // __llvm_cxxeh_call_terminate - This function is called when the dtor for an
252 // object being destroyed due to an exception throw throws an exception.  This
253 // is illegal because it would cause multiple exceptions to be active at one
254 // time.
255 void __llvm_cxxeh_call_terminate() throw() {
256   void (*Handler)(void) = __terminate_handler;
257   if (UncaughtExceptionStack)
258     if (UncaughtExceptionStack->ExceptionType == CXXException)
259       Handler = get_cxx_exception(UncaughtExceptionStack)->TerminateHandler;
260   __terminate(Handler);
261 }
262
263
264 // __llvm_cxxeh_rethrow - This function turns the top-level caught exception
265 // into an uncaught exception, in preparation for an llvm.unwind, which should
266 // follow immediately after the call to this function.  This function must be
267 // prepared to deal with foreign exceptions.
268 //
269 void __llvm_cxxeh_rethrow() throw() {
270   llvm_exception *E = LastCaughtException;
271   if (E == 0)
272     // 15.1.8 - If there are no exceptions being thrown, 'throw;' should call
273     // terminate.
274     //
275     __terminate(__terminate_handler);
276
277   // Otherwise we have an exception to rethrow.  Mark the exception as such.
278   E->isRethrown = 1;
279
280   // Add the exception to the top of the uncaught stack, to preserve the
281   // invariant that the top of the uncaught stack is the current exception.
282   E->Next = UncaughtExceptionStack;
283   UncaughtExceptionStack = E;
284
285   // Return to the caller, which should perform the unwind now.
286 }
287
288 static bool ExceptionSpecificationPermitsException(llvm_exception *E,
289                                                    const std::type_info *Info,
290                                                    va_list Args) {
291   // The only way it could match one of the types is if it is a C++ exception.
292   if (E->ExceptionType != CXXException) return false;
293
294   llvm_cxx_exception *Ex = get_cxx_exception(E);
295   
296   // Scan the list of accepted types, checking to see if the uncaught
297   // exception is any of them.
298   do {
299     // Check to see if the exception matches one of the types allowed by the
300     // exception specification.  If so, return to the caller to have the
301     // exception rethrown.
302     if (CXXExceptionISA(Ex, Info))
303       return true;
304     
305     Info = va_arg(Args, std::type_info *);
306   } while (Info);
307   return false;
308 }
309
310
311 // __llvm_cxxeh_check_eh_spec - If a function with an exception specification is
312 // throwing an exception, this function gets called with the list of type_info
313 // objects that it is allowing to propagate.  Check to see if the current
314 // uncaught exception is one of these types, and if so, allow it to be thrown by
315 // returning to the caller, which should immediately follow this call with
316 // llvm.unwind.
317 //
318 // Note that this function does not throw any exceptions, but we can't put an
319 // exception specification on it or else we'll get infinite loops!
320 //
321 void __llvm_cxxeh_check_eh_spec(void *Info, ...) {
322   const std::type_info *TypeInfo = (const std::type_info *)Info;
323   llvm_exception *E = UncaughtExceptionStack;
324   assert(E && "No uncaught exceptions!");
325
326   if (TypeInfo == 0) {   // Empty exception specification
327     // Whatever exception this is, it is not allowed by the (empty) spec, call
328     // unexpected, according to 15.4.8.
329     try {
330       void *Ex = __llvm_cxxeh_begin_catch();   // Start the catch
331       __llvm_cxxeh_end_catch(Ex);              // Free the exception
332       __unexpected(__unexpected_handler);
333     } catch (...) {
334       // Any exception thrown by unexpected cannot match the ehspec.  Call
335       // terminate, according to 15.4.9.
336       __terminate(__terminate_handler);
337     }
338   }
339
340   // Check to see if the exception matches one of the types allowed by the
341   // exception specification.  If so, return to the caller to have the
342   // exception rethrown.
343
344   va_list Args;
345   va_start(Args, Info);
346   bool Ok = ExceptionSpecificationPermitsException(E, TypeInfo, Args);
347   va_end(Args);
348   if (Ok) return;
349
350   // Ok, now we know that the exception is either not a C++ exception (thus not
351   // permitted to pass through) or not a C++ exception that is allowed.  Kill
352   // the exception and call the unexpected handler.
353   try {
354     void *Ex = __llvm_cxxeh_begin_catch();   // Start the catch
355     __llvm_cxxeh_end_catch(Ex);              // Free the exception
356   } catch (...) {
357     __terminate(__terminate_handler);        // Exception dtor threw
358   }
359
360   try {
361     __unexpected(__unexpected_handler);
362   } catch (...) {
363     // If the unexpected handler threw an exception, we will get here.  Since
364     // entering the try block calls ..._begin_catch, we need to "rethrow" the
365     // exception to make it uncaught again.  Exiting the catch will then leave
366     // it in the uncaught state.
367     __llvm_cxxeh_rethrow();
368   }
369   
370   // Grab the newly caught exception.  If this exception is permitted by the
371   // specification, allow it to be thrown.
372   E = UncaughtExceptionStack;
373   assert(E && "No uncaught exceptions!");
374
375   va_start(Args, Info);
376   Ok = ExceptionSpecificationPermitsException(E, TypeInfo, Args);
377   va_end(Args);
378   if (Ok) return;
379
380   // Final case, check to see if we can throw an std::bad_exception.
381   try {
382     throw std::bad_exception();
383   } catch (...) {
384     __llvm_cxxeh_rethrow();
385   }
386
387   // Grab the new bad_exception...
388   E = UncaughtExceptionStack;
389   assert(E && "No uncaught exceptions!");
390
391   // If it's permitted, allow it to be thrown instead.
392   va_start(Args, Info);
393   Ok = ExceptionSpecificationPermitsException(E, TypeInfo, Args);
394   va_end(Args);
395   if (Ok) return;
396
397   // Otherwise, we are out of options, terminate, according to 15.5.2.2.
398   __terminate(__terminate_handler);
399 }