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