Move excpt.h out of include/msvcrt/ as it does not conflict with any
[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 "winternl.h"
30 #include "msvcrt.h"
31 #include "wine/exception.h"
32 #include "excpt.h"
33 #include "wine/debug.h"
34
35 WINE_DEFAULT_DEBUG_CHANNEL(seh);
36
37 #define CXX_FRAME_MAGIC    0x19930520
38 #define CXX_EXCEPTION      0xe06d7363
39
40 typedef struct __type_info
41 {
42   void *vtable;
43   void *data;
44   char name[1];
45 } type_info;
46
47 /* the exception frame used by CxxFrameHandler */
48 typedef struct __cxx_exception_frame
49 {
50     EXCEPTION_FRAME  frame;    /* the standard exception frame */
51     int              trylevel;
52     DWORD            ebp;
53 } cxx_exception_frame;
54
55 /* info about a single catch {} block */
56 typedef struct __catchblock_info
57 {
58     UINT       flags;         /* flags (see below) */
59     type_info *type_info;     /* C++ type caught by this block */
60     int        offset;        /* stack offset to copy exception object to */
61     void     (*handler)();    /* catch block handler code */
62 } catchblock_info;
63 #define TYPE_FLAG_CONST      1
64 #define TYPE_FLAG_VOLATILE   2
65 #define TYPE_FLAG_REFERENCE  8
66
67 /* info about a single try {} block */
68 typedef struct __tryblock_info
69 {
70     int              start_level;      /* start trylevel of that block */
71     int              end_level;        /* end trylevel of that block */
72     int              catch_level;      /* initial trylevel of the catch block */
73     int              catchblock_count; /* count of catch blocks in array */
74     catchblock_info *catchblock;       /* array of catch blocks */
75 } tryblock_info;
76
77 /* info about the unwind handler for a given trylevel */
78 typedef struct __unwind_info
79 {
80     int    prev;          /* prev trylevel unwind handler, to run after this one */
81     void (*handler)();    /* unwind handler */
82 } unwind_info;
83
84 /* descriptor of all try blocks of a given function */
85 typedef struct __cxx_function_descr
86 {
87     UINT           magic;          /* must be CXX_FRAME_MAGIC */
88     UINT           unwind_count;   /* number of unwind handlers */
89     unwind_info   *unwind_table;   /* array of unwind handlers */
90     UINT           tryblock_count; /* number of try blocks */
91     tryblock_info *tryblock;       /* array of try blocks */
92     UINT           unknown[3];
93 } cxx_function_descr;
94
95 /* complete information about a C++ type */
96 typedef struct __cxx_type_info
97 {
98     UINT        flags;         /* flags (see CLASS_* flags below) */
99     type_info  *type_info;     /* C++ type info */
100     int         this_offset;   /* offset of base class this pointer from start of object */
101     int         vbase_descr;   /* offset of virtual base class descriptor */
102     int         vbase_offset;  /* offset of this pointer offset in virtual base class descriptor */
103     size_t      size;          /* object size */
104     void      (*copy_ctor)();  /* copy constructor */
105 } cxx_type_info;
106 #define CLASS_IS_SIMPLE_TYPE          1
107 #define CLASS_HAS_VIRTUAL_BASE_CLASS  4
108
109 /* table of C++ types that apply for a given object */
110 typedef struct __cxx_type_info_table
111 {
112     UINT           count;     /* number of types */
113     cxx_type_info *info[1];   /* array of types */
114 } cxx_type_info_table;
115
116 typedef DWORD (*cxx_exc_custom_handler)( PEXCEPTION_RECORD, cxx_exception_frame*,
117                                          PCONTEXT, struct __EXCEPTION_FRAME**,
118                                          cxx_function_descr*, int nested_trylevel,
119                                          EXCEPTION_FRAME *nested_frame, DWORD unknown3 );
120
121 /* type information for an exception object */
122 typedef struct __cxx_exception_type
123 {
124     UINT                   flags;            /* TYPE_FLAG flags */
125     void                 (*destructor)();    /* exception object destructor */
126     cxx_exc_custom_handler custom_handler;   /* custom handler for this exception */
127     cxx_type_info_table   *type_info_table;  /* list of types for this exception object */
128 } cxx_exception_type;
129
130
131 #ifdef __i386__  /* CxxFrameHandler is not supported on non-i386 */
132
133 static DWORD cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
134                                 PCONTEXT exc_context, EXCEPTION_FRAME** dispatch,
135                                 cxx_function_descr *descr, EXCEPTION_FRAME* nested_frame,
136                                 int nested_trylevel, CONTEXT86 *context );
137
138 /* call a function with a given ebp */
139 inline static void *call_ebp_func( void *func, void *ebp )
140 {
141     void *ret;
142     __asm__ __volatile__ ("pushl %%ebp; movl %2,%%ebp; call *%%eax; popl %%ebp" \
143                           : "=a" (ret) : "0" (func), "g" (ebp) : "ecx", "edx", "memory" );
144     return ret;
145 }
146
147 /* call a copy constructor */
148 inline static void call_copy_ctor( void *func, void *this, void *src, int has_vbase )
149 {
150     TRACE( "calling copy ctor %p object %p src %p\n", func, this, src );
151     if (has_vbase)
152         /* in that case copy ctor takes an extra bool indicating whether to copy the base class */
153         __asm__ __volatile__("pushl $1; pushl %2; call *%0"
154                              : : "r" (func), "c" (this), "g" (src) : "eax", "edx", "memory" );
155     else
156         __asm__ __volatile__("pushl %2; call *%0"
157                              : : "r" (func), "c" (this), "g" (src) : "eax", "edx", "memory" );
158 }
159
160 /* call the destructor of the exception object */
161 inline static void call_dtor( void *func, void *object )
162 {
163     __asm__ __volatile__("call *%0" : : "r" (func), "c" (object) : "eax", "edx", "memory" );
164 }
165
166
167 static void dump_type( cxx_type_info *type )
168 {
169     DPRINTF( "flags %x type %p", type->flags, type->type_info );
170     if (type->type_info) DPRINTF( " (%p %s)", type->type_info->data, type->type_info->name );
171     DPRINTF( " offset %d vbase %d,%d size %d copy ctor %p\n", type->this_offset,
172              type->vbase_descr, type->vbase_offset, type->size, type->copy_ctor );
173 }
174
175 static void dump_exception_type( cxx_exception_type *type )
176 {
177     int i;
178
179     DPRINTF( "exception type:\n" );
180     DPRINTF( "flags %x destr %p handler %p type info %p\n",
181              type->flags, type->destructor, type->custom_handler, type->type_info_table );
182     for (i = 0; i < type->type_info_table->count; i++)
183     {
184         DPRINTF( "    %d: ", i );
185         dump_type( type->type_info_table->info[i] );
186     }
187 }
188
189 static void dump_function_descr( cxx_function_descr *descr, cxx_exception_type *info )
190 {
191     int i, j;
192
193     DPRINTF( "function descr:\n" );
194     DPRINTF( "magic %x\n", descr->magic );
195     DPRINTF( "unwind table: %p %d\n", descr->unwind_table, descr->unwind_count );
196     for (i = 0; i < descr->unwind_count; i++)
197     {
198         DPRINTF( "    %d: prev %d func %p\n", i,
199                  descr->unwind_table[i].prev, descr->unwind_table[i].handler );
200     }
201     DPRINTF( "try table: %p %d\n", descr->tryblock, descr->tryblock_count );
202     for (i = 0; i < descr->tryblock_count; i++)
203     {
204         DPRINTF( "    %d: start %d end %d catchlevel %d catch %p %d\n", i,
205                  descr->tryblock[i].start_level, descr->tryblock[i].end_level,
206                  descr->tryblock[i].catch_level, descr->tryblock[i].catchblock,
207                  descr->tryblock[i].catchblock_count );
208         for (j = 0; j < descr->tryblock[i].catchblock_count; j++)
209         {
210             catchblock_info *ptr = &descr->tryblock[i].catchblock[j];
211             DPRINTF( "        %d: flags %x offset %d handler %p type %p",
212                      j, ptr->flags, ptr->offset, ptr->handler, ptr->type_info );
213             if (ptr->type_info) DPRINTF( " (%p %s)", ptr->type_info->data, ptr->type_info->name );
214             DPRINTF( "\n" );
215         }
216     }
217 }
218
219 /* compute the this pointer for a base class of a given type */
220 static void *get_this_pointer( cxx_type_info *type, void *object )
221 {
222     void *this_ptr;
223     int *offset_ptr;
224
225     if (!object) return NULL;
226     this_ptr = (char *)object + type->this_offset;
227     if (type->vbase_descr >= 0)
228     {
229         /* move this ptr to vbase descriptor */
230         this_ptr = (char *)this_ptr + type->vbase_descr;
231         /* and fetch additional offset from vbase descriptor */
232         offset_ptr = (int *)(*(char **)this_ptr + type->vbase_offset);
233         this_ptr = (char *)this_ptr + *offset_ptr;
234     }
235     return this_ptr;
236 }
237
238 /* check if the exception type is caught by a given catch block, and return the type that matched */
239 static cxx_type_info *find_caught_type( cxx_exception_type *exc_type, catchblock_info *catchblock )
240 {
241     UINT i;
242
243     for (i = 0; i < exc_type->type_info_table->count; i++)
244     {
245         cxx_type_info *type = exc_type->type_info_table->info[i];
246
247         if (!catchblock->type_info) return type;   /* catch(...) matches any type */
248         if (catchblock->type_info != type->type_info)
249         {
250             if (strcmp( catchblock->type_info->name, type->type_info->name )) continue;
251         }
252         /* type is the same, now check the flags */
253         if ((exc_type->flags & TYPE_FLAG_CONST) &&
254             !(catchblock->flags & TYPE_FLAG_CONST)) continue;
255         if ((exc_type->flags & TYPE_FLAG_VOLATILE) &&
256             !(catchblock->flags & TYPE_FLAG_VOLATILE)) continue;
257         return type;  /* it matched */
258     }
259     return NULL;
260 }
261
262
263 /* copy the exception object where the catch block wants it */
264 static void copy_exception( void *object, cxx_exception_frame *frame,
265                             catchblock_info *catchblock, cxx_type_info *type )
266 {
267     void **dest_ptr;
268
269     if (!catchblock->type_info || !catchblock->type_info->name[0]) return;
270     if (!catchblock->offset) return;
271     dest_ptr = (void **)((char *)&frame->ebp + catchblock->offset);
272
273     if (catchblock->flags & TYPE_FLAG_REFERENCE)
274     {
275         *dest_ptr = get_this_pointer( type, object );
276     }
277     else if (type->flags & CLASS_IS_SIMPLE_TYPE)
278     {
279         memmove( dest_ptr, object, type->size );
280         /* if it is a pointer, adjust it */
281         if (type->size == sizeof(void *)) *dest_ptr = get_this_pointer( type, *dest_ptr );
282     }
283     else  /* copy the object */
284     {
285         if (type->copy_ctor)
286             call_copy_ctor( type->copy_ctor, dest_ptr, get_this_pointer(type,object),
287                             (type->flags & CLASS_HAS_VIRTUAL_BASE_CLASS) );
288         else
289             memmove( dest_ptr, get_this_pointer(type,object), type->size );
290     }
291 }
292
293 /* unwind the local function up to a given trylevel */
294 static void cxx_local_unwind( cxx_exception_frame* frame, cxx_function_descr *descr, int last_level)
295 {
296     void (*handler)();
297     int trylevel = frame->trylevel;
298
299     while (trylevel != last_level)
300     {
301         if (trylevel < 0 || trylevel >= descr->unwind_count)
302         {
303             ERR( "invalid trylevel %d\n", trylevel );
304             MSVCRT_terminate();
305         }
306         handler = descr->unwind_table[trylevel].handler;
307         if (handler)
308         {
309             TRACE( "calling unwind handler %p trylevel %d last %d ebp %p\n",
310                    handler, trylevel, last_level, &frame->ebp );
311             call_ebp_func( handler, &frame->ebp );
312         }
313         trylevel = descr->unwind_table[trylevel].prev;
314     }
315     frame->trylevel = last_level;
316 }
317
318 /* exception frame for nested exceptions in catch block */
319 struct catch_func_nested_frame
320 {
321     EXCEPTION_FRAME      frame;     /* standard exception frame */
322     EXCEPTION_RECORD    *prev_rec;  /* previous record to restore in thread data */
323     cxx_exception_frame *cxx_frame; /* frame of parent exception */
324     cxx_function_descr  *descr;     /* descriptor of parent exception */
325     int                  trylevel;  /* current try level */
326 };
327
328 /* handler for exceptions happening while calling a catch function */
329 static DWORD catch_function_nested_handler( EXCEPTION_RECORD *rec, EXCEPTION_FRAME *frame,
330                                             CONTEXT *context, EXCEPTION_FRAME **dispatcher )
331 {
332     struct catch_func_nested_frame *nested_frame = (struct catch_func_nested_frame *)frame;
333
334     if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
335     {
336         msvcrt_get_thread_data()->exc_record = nested_frame->prev_rec;
337         return ExceptionContinueSearch;
338     }
339     else
340     {
341         TRACE( "got nested exception in catch function\n" );
342         return cxx_frame_handler( rec, nested_frame->cxx_frame, context,
343                                   NULL, nested_frame->descr, &nested_frame->frame,
344                                   nested_frame->trylevel, context );
345     }
346 }
347
348 /* find and call the appropriate catch block for an exception */
349 /* returns the address to continue execution to after the catch block was called */
350 inline static void *call_catch_block( PEXCEPTION_RECORD rec, cxx_exception_frame *frame,
351                                       cxx_function_descr *descr, int nested_trylevel,
352                                       cxx_exception_type *info )
353 {
354     int i, j;
355     void *addr, *object = (void *)rec->ExceptionInformation[1];
356     struct catch_func_nested_frame nested_frame;
357     int trylevel = frame->trylevel;
358     MSVCRT_thread_data *thread_data = msvcrt_get_thread_data();
359
360     for (i = 0; i < descr->tryblock_count; i++)
361     {
362         tryblock_info *tryblock = &descr->tryblock[i];
363
364         if (trylevel < tryblock->start_level) continue;
365         if (trylevel > tryblock->end_level) continue;
366
367         /* got a try block */
368         for (j = 0; j < tryblock->catchblock_count; j++)
369         {
370             catchblock_info *catchblock = &tryblock->catchblock[j];
371             cxx_type_info *type = find_caught_type( info, catchblock );
372             if (!type) continue;
373
374             TRACE( "matched type %p in tryblock %d catchblock %d\n", type, i, j );
375
376             /* copy the exception to its destination on the stack */
377             copy_exception( object, frame, catchblock, type );
378
379             /* unwind the stack */
380             RtlUnwind( frame, 0, rec, 0 );
381             cxx_local_unwind( frame, descr, tryblock->start_level );
382             frame->trylevel = tryblock->end_level + 1;
383
384             /* call the catch block */
385             TRACE( "calling catch block %p for type %p addr %p ebp %p\n",
386                    catchblock, type, catchblock->handler, &frame->ebp );
387
388             /* setup an exception block for nested exceptions */
389
390             nested_frame.frame.Handler = catch_function_nested_handler;
391             nested_frame.prev_rec  = thread_data->exc_record;
392             nested_frame.cxx_frame = frame;
393             nested_frame.descr     = descr;
394             nested_frame.trylevel  = nested_trylevel + 1;
395
396             __wine_push_frame( &nested_frame.frame );
397             thread_data->exc_record = rec;
398             addr = call_ebp_func( catchblock->handler, &frame->ebp );
399             thread_data->exc_record = nested_frame.prev_rec;
400             __wine_pop_frame( &nested_frame.frame );
401
402             if (info->destructor) call_dtor( info->destructor, object );
403             TRACE( "done, continuing at %p\n", addr );
404             return addr;
405         }
406     }
407     return NULL;
408 }
409
410
411 /*********************************************************************
412  *              cxx_frame_handler
413  *
414  * Implementation of __CxxFrameHandler.
415  */
416 static DWORD cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
417                                 PCONTEXT exc_context, EXCEPTION_FRAME** dispatch,
418                                 cxx_function_descr *descr, EXCEPTION_FRAME* nested_frame,
419                                 int nested_trylevel, CONTEXT86 *context )
420 {
421     cxx_exception_type *exc_type;
422     void *next_ip;
423
424     if (descr->magic != CXX_FRAME_MAGIC)
425     {
426         ERR( "invalid frame magic %x\n", descr->magic );
427         return ExceptionContinueSearch;
428     }
429     if (rec->ExceptionFlags & (EH_UNWINDING|EH_EXIT_UNWIND))
430     {
431         if (descr->unwind_count && !nested_trylevel) cxx_local_unwind( frame, descr, -1 );
432         return ExceptionContinueSearch;
433     }
434     if (!descr->tryblock_count) return ExceptionContinueSearch;
435
436     exc_type = (cxx_exception_type *)rec->ExceptionInformation[2];
437     if (rec->ExceptionCode == CXX_EXCEPTION &&
438         rec->ExceptionInformation[0] > CXX_FRAME_MAGIC &&
439         exc_type->custom_handler)
440     {
441         return exc_type->custom_handler( rec, frame, exc_context, dispatch,
442                                          descr, nested_trylevel, nested_frame, 0 );
443     }
444
445     if (!exc_type)  /* nested exception, fetch info from original exception */
446     {
447         rec = msvcrt_get_thread_data()->exc_record;
448         exc_type = (cxx_exception_type *)rec->ExceptionInformation[2];
449     }
450
451     if (TRACE_ON(seh))
452     {
453         TRACE("handling C++ exception rec %p frame %p trylevel %d descr %p nested_frame %p\n",
454               rec, frame, frame->trylevel, descr, nested_frame );
455         dump_exception_type( exc_type );
456         dump_function_descr( descr, exc_type );
457     }
458
459     next_ip = call_catch_block( rec, frame, descr, frame->trylevel, exc_type );
460
461     if (!next_ip) return ExceptionContinueSearch;
462     rec->ExceptionFlags &= ~EH_NONCONTINUABLE;
463     context->Eip = (DWORD)next_ip;
464     context->Ebp = (DWORD)&frame->ebp;
465     context->Esp = ((DWORD*)frame)[-1];
466     return ExceptionContinueExecution;
467 }
468
469
470 /*********************************************************************
471  *              __CxxFrameHandler (MSVCRT.@)
472  */
473 void __CxxFrameHandler( PEXCEPTION_RECORD rec, EXCEPTION_FRAME* frame,
474                         PCONTEXT exc_context, EXCEPTION_FRAME** dispatch,
475                         CONTEXT86 *context )
476 {
477     cxx_function_descr *descr = (cxx_function_descr *)context->Eax;
478     context->Eax = cxx_frame_handler( rec, (cxx_exception_frame *)frame,
479                                       exc_context, dispatch, descr, NULL, 0, context );
480 }
481
482 #endif  /* __i386__ */
483
484 /*********************************************************************
485  *              _CxxThrowException (MSVCRT.@)
486  */
487 void _CxxThrowException( void *object, cxx_exception_type *type )
488 {
489     DWORD args[3];
490
491     args[0] = CXX_FRAME_MAGIC;
492     args[1] = (DWORD)object;
493     args[2] = (DWORD)type;
494     RaiseException( CXX_EXCEPTION, EH_NONCONTINUABLE, 3, args );
495 }