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