msvcrt: Preserve all registers in call_ebp_func.
[wine] / dlls / msvcrt / cppexcept.c
1 /*
2  * msvcrt C++ exception handling
3  *
4  * Copyright 2002 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * NOTES
21  * A good reference is the article "How a C++ compiler implements
22  * exception handling" by Vishal Kochhar, available on
23  * www.thecodeproject.com.
24  */
25
26 #include "config.h"
27 #include "wine/port.h"
28
29 #include <stdarg.h>
30
31 #include "windef.h"
32 #include "winbase.h"
33 #include "winreg.h"
34 #include "winternl.h"
35 #include "msvcrt.h"
36 #include "wine/exception.h"
37 #include "excpt.h"
38 #include "wine/debug.h"
39
40 #include "cppexcept.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(seh);
43
44 #ifdef __i386__  /* CxxFrameHandler is not supported on non-i386 */
45
46 DWORD cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
47                          PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch,
48                          cxx_function_descr *descr, EXCEPTION_REGISTRATION_RECORD* nested_frame,
49                          int nested_trylevel );
50
51 /* call a function with a given ebp */
52 inline static void *call_ebp_func( void *func, void *ebp )
53 {
54     void *ret;
55     int dummy;
56     __asm__ __volatile__ ("pushl %%ebx\n\t"
57                           "pushl %%ebp\n\t"
58                           "movl %4,%%ebp\n\t"
59                           "call *%%eax\n\t"
60                           "popl %%ebp\n\t"
61                           "popl %%ebx"
62                           : "=a" (ret), "=S" (dummy), "=D" (dummy)
63                           : "0" (func), "1" (ebp) : "ecx", "edx", "memory" );
64     return ret;
65 }
66
67 /* call a copy constructor */
68 inline static void call_copy_ctor( void *func, void *this, void *src, int has_vbase )
69 {
70     TRACE( "calling copy ctor %p object %p src %p\n", func, this, src );
71     if (has_vbase)
72         /* in that case copy ctor takes an extra bool indicating whether to copy the base class */
73         __asm__ __volatile__("pushl $1; pushl %2; call *%0"
74                              : : "r" (func), "c" (this), "r" (src) : "eax", "edx", "memory" );
75     else
76         __asm__ __volatile__("pushl %2; call *%0"
77                              : : "r" (func), "c" (this), "r" (src) : "eax", "edx", "memory" );
78 }
79
80 /* call the destructor of the exception object */
81 inline static void call_dtor( void *func, void *object )
82 {
83     __asm__ __volatile__("call *%0" : : "r" (func), "c" (object) : "eax", "edx", "memory" );
84 }
85
86 /* continue execution to the specified address after exception is caught */
87 inline static void DECLSPEC_NORETURN continue_after_catch( cxx_exception_frame* frame, void *addr )
88 {
89     __asm__ __volatile__("movl -4(%0),%%esp; leal 12(%0),%%ebp; jmp *%1"
90                          : : "r" (frame), "a" (addr) );
91     for (;;) ; /* unreached */
92 }
93
94 static inline void dump_type( const cxx_type_info *type )
95 {
96     TRACE( "flags %x type %p %s offsets %d,%d,%d size %d copy ctor %p\n",
97              type->flags, type->type_info, dbgstr_type_info(type->type_info),
98              type->offsets.this_offset, type->offsets.vbase_descr, type->offsets.vbase_offset,
99              type->size, type->copy_ctor );
100 }
101
102 static void dump_exception_type( const cxx_exception_type *type )
103 {
104     UINT i;
105
106     TRACE( "flags %x destr %p handler %p type info %p\n",
107              type->flags, type->destructor, type->custom_handler, type->type_info_table );
108     for (i = 0; i < type->type_info_table->count; i++)
109     {
110         TRACE( "    %d: ", i );
111         dump_type( type->type_info_table->info[i] );
112     }
113 }
114
115 static void dump_function_descr( const cxx_function_descr *descr, const cxx_exception_type *info )
116 {
117     UINT i;
118     int j;
119
120     TRACE( "magic %x\n", descr->magic );
121     TRACE( "unwind table: %p %d\n", descr->unwind_table, descr->unwind_count );
122     for (i = 0; i < descr->unwind_count; i++)
123     {
124         TRACE( "    %d: prev %d func %p\n", i,
125                  descr->unwind_table[i].prev, descr->unwind_table[i].handler );
126     }
127     TRACE( "try table: %p %d\n", descr->tryblock, descr->tryblock_count );
128     for (i = 0; i < descr->tryblock_count; i++)
129     {
130         TRACE( "    %d: start %d end %d catchlevel %d catch %p %d\n", i,
131                  descr->tryblock[i].start_level, descr->tryblock[i].end_level,
132                  descr->tryblock[i].catch_level, descr->tryblock[i].catchblock,
133                  descr->tryblock[i].catchblock_count );
134         for (j = 0; j < descr->tryblock[i].catchblock_count; j++)
135         {
136             catchblock_info *ptr = &descr->tryblock[i].catchblock[j];
137             TRACE( "        %d: flags %x offset %d handler %p type %p %s\n",
138                      j, ptr->flags, ptr->offset, ptr->handler,
139                      ptr->type_info, dbgstr_type_info( ptr->type_info ) );
140         }
141     }
142 }
143
144 /* check if the exception type is caught by a given catch block, and return the type that matched */
145 static const cxx_type_info *find_caught_type( cxx_exception_type *exc_type, catchblock_info *catchblock )
146 {
147     UINT i;
148
149     for (i = 0; i < exc_type->type_info_table->count; i++)
150     {
151         const cxx_type_info *type = exc_type->type_info_table->info[i];
152
153         if (!catchblock->type_info) return type;   /* catch(...) matches any type */
154         if (catchblock->type_info != type->type_info)
155         {
156             if (strcmp( catchblock->type_info->mangled, type->type_info->mangled )) continue;
157         }
158         /* type is the same, now check the flags */
159         if ((exc_type->flags & TYPE_FLAG_CONST) &&
160             !(catchblock->flags & TYPE_FLAG_CONST)) continue;
161         if ((exc_type->flags & TYPE_FLAG_VOLATILE) &&
162             !(catchblock->flags & TYPE_FLAG_VOLATILE)) continue;
163         return type;  /* it matched */
164     }
165     return NULL;
166 }
167
168
169 /* copy the exception object where the catch block wants it */
170 static void copy_exception( void *object, cxx_exception_frame *frame,
171                             catchblock_info *catchblock, const cxx_type_info *type )
172 {
173     void **dest_ptr;
174
175     if (!catchblock->type_info || !catchblock->type_info->mangled[0]) return;
176     if (!catchblock->offset) return;
177     dest_ptr = (void **)((char *)&frame->ebp + catchblock->offset);
178
179     if (catchblock->flags & TYPE_FLAG_REFERENCE)
180     {
181         *dest_ptr = get_this_pointer( &type->offsets, object );
182     }
183     else if (type->flags & CLASS_IS_SIMPLE_TYPE)
184     {
185         memmove( dest_ptr, object, type->size );
186         /* if it is a pointer, adjust it */
187         if (type->size == sizeof(void *)) *dest_ptr = get_this_pointer( &type->offsets, *dest_ptr );
188     }
189     else  /* copy the object */
190     {
191         if (type->copy_ctor)
192             call_copy_ctor( type->copy_ctor, dest_ptr, get_this_pointer(&type->offsets,object),
193                             (type->flags & CLASS_HAS_VIRTUAL_BASE_CLASS) );
194         else
195             memmove( dest_ptr, get_this_pointer(&type->offsets,object), type->size );
196     }
197 }
198
199 /* unwind the local function up to a given trylevel */
200 static void cxx_local_unwind( cxx_exception_frame* frame, cxx_function_descr *descr, int last_level)
201 {
202     void (*handler)();
203     int trylevel = frame->trylevel;
204
205     while (trylevel != last_level)
206     {
207         if (trylevel < 0 || trylevel >= descr->unwind_count)
208         {
209             ERR( "invalid trylevel %d\n", trylevel );
210             MSVCRT_terminate();
211         }
212         handler = descr->unwind_table[trylevel].handler;
213         if (handler)
214         {
215             TRACE( "calling unwind handler %p trylevel %d last %d ebp %p\n",
216                    handler, trylevel, last_level, &frame->ebp );
217             call_ebp_func( handler, &frame->ebp );
218         }
219         trylevel = descr->unwind_table[trylevel].prev;
220     }
221     frame->trylevel = last_level;
222 }
223
224 /* exception frame for nested exceptions in catch block */
225 struct catch_func_nested_frame
226 {
227     EXCEPTION_REGISTRATION_RECORD frame;     /* standard exception frame */
228     EXCEPTION_RECORD             *prev_rec;  /* previous record to restore in thread data */
229     cxx_exception_frame          *cxx_frame; /* frame of parent exception */
230     cxx_function_descr           *descr;     /* descriptor of parent exception */
231     int                           trylevel;  /* current try level */
232 };
233
234 /* handler for exceptions happening while calling a catch function */
235 static DWORD catch_function_nested_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
236                                             CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
237 {
238     struct catch_func_nested_frame *nested_frame = (struct catch_func_nested_frame *)frame;
239
240     if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
241     {
242         msvcrt_get_thread_data()->exc_record = nested_frame->prev_rec;
243         return ExceptionContinueSearch;
244     }
245     else
246     {
247         TRACE( "got nested exception in catch function\n" );
248         return cxx_frame_handler( rec, nested_frame->cxx_frame, context,
249                                   NULL, nested_frame->descr, &nested_frame->frame,
250                                   nested_frame->trylevel );
251     }
252 }
253
254 /* find and call the appropriate catch block for an exception */
255 /* returns the address to continue execution to after the catch block was called */
256 inline static void call_catch_block( PEXCEPTION_RECORD rec, cxx_exception_frame *frame,
257                                      cxx_function_descr *descr, int nested_trylevel,
258                                      cxx_exception_type *info )
259 {
260     UINT i;
261     int j;
262     void *addr, *prev_frame, *object = (void *)rec->ExceptionInformation[1];
263     struct catch_func_nested_frame nested_frame;
264     int trylevel = frame->trylevel;
265     thread_data_t *thread_data = msvcrt_get_thread_data();
266
267     for (i = 0; i < descr->tryblock_count; i++)
268     {
269         tryblock_info *tryblock = &descr->tryblock[i];
270
271         if (trylevel < tryblock->start_level) continue;
272         if (trylevel > tryblock->end_level) continue;
273
274         /* got a try block */
275         for (j = 0; j < tryblock->catchblock_count; j++)
276         {
277             catchblock_info *catchblock = &tryblock->catchblock[j];
278             if(info)
279             {
280                 const cxx_type_info *type = find_caught_type( info, catchblock );
281                 if (!type) continue;
282
283                 TRACE( "matched type %p in tryblock %d catchblock %d\n", type, i, j );
284
285                 /* copy the exception to its destination on the stack */
286                 copy_exception( object, frame, catchblock, type );
287             }
288             else
289             {
290                 /* no CXX_EXCEPTION only proceed with a catch(...) block*/
291                 if(catchblock->type_info)
292                     continue;
293                 TRACE("found catch(...) block\n");
294             }
295
296             /* unwind the stack */
297             RtlUnwind( frame, 0, rec, 0 );
298             cxx_local_unwind( frame, descr, tryblock->start_level );
299             frame->trylevel = tryblock->end_level + 1;
300
301             /* call the catch block */
302             TRACE( "calling catch block %p addr %p ebp %p\n",
303                    catchblock, catchblock->handler, &frame->ebp );
304
305             /* setup an exception block for nested exceptions */
306
307             nested_frame.frame.Handler = catch_function_nested_handler;
308             nested_frame.prev_rec  = thread_data->exc_record;
309             nested_frame.cxx_frame = frame;
310             nested_frame.descr     = descr;
311             nested_frame.trylevel  = nested_trylevel + 1;
312
313             __wine_push_frame( &nested_frame.frame );
314             thread_data->exc_record = rec;
315             addr = call_ebp_func( catchblock->handler, &frame->ebp );
316             thread_data->exc_record = nested_frame.prev_rec;
317             __wine_pop_frame( &nested_frame.frame );
318
319             if (info && info->destructor) call_dtor( info->destructor, object );
320             TRACE( "done, continuing at %p\n", addr );
321             prev_frame = NtCurrentTeb()->Tib.ExceptionList;
322             __wine_pop_frame( prev_frame );
323             continue_after_catch( frame, addr );
324         }
325     }
326 }
327
328
329 /*********************************************************************
330  *              cxx_frame_handler
331  *
332  * Implementation of __CxxFrameHandler.
333  */
334 DWORD cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
335                          PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch,
336                          cxx_function_descr *descr, EXCEPTION_REGISTRATION_RECORD* nested_frame,
337                          int nested_trylevel )
338 {
339     cxx_exception_type *exc_type;
340
341     if (descr->magic != CXX_FRAME_MAGIC)
342     {
343         ERR( "invalid frame magic %x\n", descr->magic );
344         return ExceptionContinueSearch;
345     }
346     if (rec->ExceptionFlags & (EH_UNWINDING|EH_EXIT_UNWIND))
347     {
348         if (descr->unwind_count && !nested_trylevel) cxx_local_unwind( frame, descr, -1 );
349         return ExceptionContinueSearch;
350     }
351     if (!descr->tryblock_count) return ExceptionContinueSearch;
352
353     if(rec->ExceptionCode == CXX_EXCEPTION)
354     {
355         exc_type = (cxx_exception_type *)rec->ExceptionInformation[2];
356
357         if (rec->ExceptionInformation[0] > CXX_FRAME_MAGIC &&
358                 exc_type->custom_handler)
359         {
360             return exc_type->custom_handler( rec, frame, context, dispatch,
361                                          descr, nested_trylevel, nested_frame, 0 );
362         }
363         if (!exc_type)  /* nested exception, fetch info from original exception */
364         {
365             rec = msvcrt_get_thread_data()->exc_record;
366             exc_type = (cxx_exception_type *)rec->ExceptionInformation[2];
367         }
368         if (TRACE_ON(seh))
369         {
370             TRACE("handling C++ exception rec %p frame %p trylevel %d descr %p nested_frame %p\n",
371                   rec, frame, frame->trylevel, descr, nested_frame );
372             dump_exception_type( exc_type );
373             dump_function_descr( descr, exc_type );
374         }
375     }
376     else
377     {
378         exc_type = NULL;
379         TRACE("handling C exception code %lx  rec %p frame %p trylevel %d descr %p nested_frame %p\n",
380               rec->ExceptionCode,  rec, frame, frame->trylevel, descr, nested_frame );
381     }
382
383     call_catch_block( rec, frame, descr, frame->trylevel, exc_type );
384     return ExceptionContinueSearch;
385 }
386
387
388 /*********************************************************************
389  *              __CxxFrameHandler (MSVCRT.@)
390  */
391 extern DWORD __CxxFrameHandler( PEXCEPTION_RECORD rec, EXCEPTION_REGISTRATION_RECORD* frame,
392                                 PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch );
393 __ASM_GLOBAL_FUNC( __CxxFrameHandler,
394                    "pushl $0\n\t"        /* nested_trylevel */
395                    "pushl $0\n\t"        /* nested_frame */
396                    "pushl %eax\n\t"      /* descr */
397                    "pushl 28(%esp)\n\t"  /* dispatch */
398                    "pushl 28(%esp)\n\t"  /* context */
399                    "pushl 28(%esp)\n\t"  /* frame */
400                    "pushl 28(%esp)\n\t"  /* rec */
401                    "call " __ASM_NAME("cxx_frame_handler") "\n\t"
402                    "add $28,%esp\n\t"
403                    "ret" );
404
405 #endif  /* __i386__ */
406
407 /*********************************************************************
408  *              _CxxThrowException (MSVCRT.@)
409  */
410 void _CxxThrowException( exception *object, const cxx_exception_type *type )
411 {
412     ULONG_PTR args[3];
413
414     args[0] = CXX_FRAME_MAGIC;
415     args[1] = (ULONG_PTR)object;
416     args[2] = (ULONG_PTR)type;
417     RaiseException( CXX_EXCEPTION, EH_NONCONTINUABLE, 3, args );
418 }
419
420 /*********************************************************************
421  *              __CxxDetectRethrow (MSVCRT.@)
422  */
423 BOOL __CxxDetectRethrow(PEXCEPTION_POINTERS ptrs)
424 {
425   PEXCEPTION_RECORD rec;
426
427   if (!ptrs)
428     return FALSE;
429
430   rec = ptrs->ExceptionRecord;
431
432   if (rec->ExceptionCode == CXX_EXCEPTION &&
433       rec->NumberParameters == 3 &&
434       rec->ExceptionInformation[0] == CXX_FRAME_MAGIC &&
435       rec->ExceptionInformation[2])
436   {
437     ptrs->ExceptionRecord = msvcrt_get_thread_data()->exc_record;
438     return TRUE;
439   }
440   return (msvcrt_get_thread_data()->exc_record == rec);
441 }
442
443 /*********************************************************************
444  *              __CxxQueryExceptionSize (MSVCRT.@)
445  */
446 unsigned int __CxxQueryExceptionSize(void)
447 {
448   return sizeof(cxx_exception_type);
449 }