update for HEAD-2003091401
[reactos.git] / lib / msvcrt / misc / cpp.c
1 /* $Id$
2  *
3  * COPYRIGHT:   See COPYING in the top level directory
4  * PROJECT:     ReactOS C runtime
5  * FILE:        cpp.c
6  * PURPOSE:     C++ runtime
7  * NOTES:       Copied from Wine and slightly adapted for ReactOS
8  *              This is a derivative work compiled of work written and
9  *              copyrighted by (at least):
10  *              Alexandre Juliard <juliard@winehq.org>
11  *              Patrik Stridvall <ps@leissner.se>
12  *              Dimitrie O. Paun <dpaun@rogers.com>
13  *              Jon Griffiths <jon_p_griffiths@yahoo.com>
14  */
15
16 #include <windows.h>
17 #include <msvcrt/internal/tls.h>
18 #include <msvcrt/stddef.h>
19
20 #define CXX_FRAME_MAGIC    0x19930520
21 #define CXX_EXCEPTION      0xe06d7363
22
23 typedef void (*v_table_ptr)();
24
25 typedef struct __type_info
26 {
27   v_table_ptr *vtable;
28   void *data;
29   char name[1];
30 } type_info;
31
32 /* the exception frame used by CxxFrameHandler */
33 typedef struct __cxx_exception_frame
34 {
35     EXCEPTION_REGISTRATION frame;    /* the standard exception frame */
36     int                    trylevel;
37     DWORD                  ebp;
38 } cxx_exception_frame;
39
40 /* info about a single catch {} block */
41 typedef struct __catchblock_info
42 {
43     UINT       flags;         /* flags (see below) */
44     type_info *type_info;     /* C++ type caught by this block */
45     int        offset;        /* stack offset to copy exception object to */
46     void     (*handler)();    /* catch block handler code */
47 } catchblock_info;
48 #define TYPE_FLAG_CONST      1
49 #define TYPE_FLAG_VOLATILE   2
50 #define TYPE_FLAG_REFERENCE  8
51
52 /* info about a single try {} block */
53 typedef struct __tryblock_info
54 {
55     int              start_level;      /* start trylevel of that block */
56     int              end_level;        /* end trylevel of that block */
57     int              catch_level;      /* initial trylevel of the catch block */
58     int              catchblock_count; /* count of catch blocks in array */
59     catchblock_info *catchblock;       /* array of catch blocks */
60 } tryblock_info;
61
62 /* info about the unwind handler for a given trylevel */
63 typedef struct __unwind_info
64 {
65     int    prev;          /* prev trylevel unwind handler, to run after this one */
66     void (*handler)();    /* unwind handler */
67 } unwind_info;
68
69 /* descriptor of all try blocks of a given function */
70 typedef struct __cxx_function_descr
71 {
72     UINT           magic;          /* must be CXX_FRAME_MAGIC */
73     UINT           unwind_count;   /* number of unwind handlers */
74     unwind_info   *unwind_table;   /* array of unwind handlers */
75     UINT           tryblock_count; /* number of try blocks */
76     tryblock_info *tryblock;       /* array of try blocks */
77     UINT           unknown[3];
78 } cxx_function_descr;
79
80 /* complete information about a C++ type */
81 typedef struct __cxx_type_info
82 {
83     UINT        flags;         /* flags (see CLASS_* flags below) */
84     type_info  *type_info;     /* C++ type info */
85     int         this_offset;   /* offset of base class this pointer from start of object */
86     int         vbase_descr;   /* offset of virtual base class descriptor */
87     int         vbase_offset;  /* offset of this pointer offset in virtual base class descriptor */
88     size_t      size;          /* object size */
89     void      (*copy_ctor)();  /* copy constructor */
90 } cxx_type_info;
91 #define CLASS_IS_SIMPLE_TYPE          1
92 #define CLASS_HAS_VIRTUAL_BASE_CLASS  4
93
94 /* table of C++ types that apply for a given object */
95 typedef struct __cxx_type_info_table
96 {
97     UINT           count;     /* number of types */
98     cxx_type_info *info[1];   /* array of types */
99 } cxx_type_info_table;
100
101 typedef DWORD (*cxx_exc_custom_handler)( PEXCEPTION_RECORD, cxx_exception_frame*,
102                                          PCONTEXT, PEXCEPTION_REGISTRATION*,
103                                          cxx_function_descr*, int nested_trylevel,
104                                          PEXCEPTION_REGISTRATION nested_frame,
105                                          DWORD unknown3 );
106
107 /* type information for an exception object */
108 typedef struct __cxx_exception_type
109 {
110     UINT                   flags;            /* TYPE_FLAG flags */
111     void                 (*destructor)();    /* exception object destructor */
112     cxx_exc_custom_handler custom_handler;   /* custom handler for this exception */
113     cxx_type_info_table   *type_info_table;  /* list of types for this exception object */
114 } cxx_exception_type;
115
116 /* ??1type_info@@UAE@XZ (MSVCRT.@) */
117 void MSVCRT_type_info_dtor(type_info * _this)
118 {
119   if (_this->data)
120     {
121     free(_this->data);
122     }
123 }
124
125 static DWORD cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
126                                 PCONTEXT exc_context, PEXCEPTION_REGISTRATION* dispatch,
127                                 cxx_function_descr *descr, PEXCEPTION_REGISTRATION nested_frame,
128                                 int nested_trylevel, CONTEXT_X86 *context );
129
130 /* call a function with a given ebp */
131 inline static void *call_ebp_func( void *func, void *ebp )
132 {
133     void *ret;
134     __asm__ __volatile__ ("pushl %%ebp; movl %2,%%ebp; call *%%eax; popl %%ebp" \
135                           : "=a" (ret) : "0" (func), "g" (ebp) : "ecx", "edx", "memory" );
136     return ret;
137 }
138
139 /* call a copy constructor */
140 inline static void call_copy_ctor( void *func, void *this, void *src, int has_vbase )
141 {
142 #if 0
143     TRACE( "calling copy ctor %p object %p src %p\n", func, this, src );
144 #endif
145     if (has_vbase)
146         /* in that case copy ctor takes an extra bool indicating whether to copy the base class */
147         __asm__ __volatile__("pushl $1; pushl %2; call *%0"
148                              : : "r" (func), "c" (this), "g" (src) : "eax", "edx", "memory" );
149     else
150         __asm__ __volatile__("pushl %2; call *%0"
151                              : : "r" (func), "c" (this), "g" (src) : "eax", "edx", "memory" );
152 }
153
154 /* call the destructor of the exception object */
155 inline static void call_dtor( void *func, void *object )
156 {
157     __asm__ __volatile__("call *%0" : : "r" (func), "c" (object) : "eax", "edx", "memory" );
158 }
159
160
161 static void dump_type( cxx_type_info *type )
162 {
163 #if 0
164     DPRINTF( "flags %x type %p", type->flags, type->type_info );
165     if (type->type_info) DPRINTF( " (%p %s)", type->type_info->data, type->type_info->name );
166     DPRINTF( " offset %d vbase %d,%d size %d copy ctor %p\n", type->this_offset,
167              type->vbase_descr, type->vbase_offset, type->size, type->copy_ctor );
168 #endif
169 }
170
171 static void dump_exception_type( cxx_exception_type *type )
172 {
173 #if 0
174     int i;
175
176     DPRINTF( "exception type:\n" );
177     DPRINTF( "flags %x destr %p handler %p type info %p\n",
178              type->flags, type->destructor, type->custom_handler, type->type_info_table );
179     for (i = 0; i < type->type_info_table->count; i++)
180     {
181         DPRINTF( "    %d: ", i );
182         dump_type( type->type_info_table->info[i] );
183     }
184 #endif
185 }
186
187 static void dump_function_descr( cxx_function_descr *descr, cxx_exception_type *info )
188 {
189 #if 0
190     int i, j;
191
192     DPRINTF( "function descr:\n" );
193     DPRINTF( "magic %x\n", descr->magic );
194     DPRINTF( "unwind table: %p %d\n", descr->unwind_table, descr->unwind_count );
195     for (i = 0; i < descr->unwind_count; i++)
196     {
197         DPRINTF( "    %d: prev %d func %p\n", i,
198                  descr->unwind_table[i].prev, descr->unwind_table[i].handler );
199     }
200     DPRINTF( "try table: %p %d\n", descr->tryblock, descr->tryblock_count );
201     for (i = 0; i < descr->tryblock_count; i++)
202     {
203         DPRINTF( "    %d: start %d end %d catchlevel %d catch %p %d\n", i,
204                  descr->tryblock[i].start_level, descr->tryblock[i].end_level,
205                  descr->tryblock[i].catch_level, descr->tryblock[i].catchblock,
206                  descr->tryblock[i].catchblock_count );
207         for (j = 0; j < descr->tryblock[i].catchblock_count; j++)
208         {
209             catchblock_info *ptr = &descr->tryblock[i].catchblock[j];
210             DPRINTF( "        %d: flags %x offset %d handler %p type %p",
211                      j, ptr->flags, ptr->offset, ptr->handler, ptr->type_info );
212             if (ptr->type_info) DPRINTF( " (%p %s)", ptr->type_info->data, ptr->type_info->name );
213             DPRINTF( "\n" );
214         }
215     }
216 #endif
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             OutputDebugStringA ( "invalid trylevel\n" );
304             _exit(1);
305         }
306         handler = descr->unwind_table[trylevel].handler;
307         if (handler)
308         {
309 #if 0
310             TRACE( "calling unwind handler %p trylevel %d last %d ebp %p\n",
311                    handler, trylevel, last_level, &frame->ebp );
312 #endif
313             call_ebp_func( handler, &frame->ebp );
314         }
315         trylevel = descr->unwind_table[trylevel].prev;
316     }
317     frame->trylevel = last_level;
318 }
319
320 /* exception frame for nested exceptions in catch block */
321 struct catch_func_nested_frame
322 {
323     EXCEPTION_REGISTRATION frame;     /* standard exception frame */
324     EXCEPTION_RECORD      *prev_rec;  /* previous record to restore in thread data */
325     cxx_exception_frame   *cxx_frame; /* frame of parent exception */
326     cxx_function_descr    *descr;     /* descriptor of parent exception */
327     int                    trylevel;  /* current try level */
328 };
329
330 /* handler for exceptions happening while calling a catch function */
331 static EXCEPTION_DISPOSITION catch_function_nested_handler(PEXCEPTION_RECORD rec,
332                                                            PEXCEPTION_REGISTRATION frame,
333                                                            PCONTEXT context,
334                                                            PVOID DispatcherContext)
335 {
336     struct catch_func_nested_frame *nested_frame = (struct catch_func_nested_frame *)frame;
337
338     if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
339     {
340         GetThreadData()->exc_record = nested_frame->prev_rec;
341         return ExceptionContinueSearch;
342     }
343     else
344     {
345 #if 0
346         TRACE( "got nested exception in catch function\n" );
347 #endif
348         return cxx_frame_handler( rec, nested_frame->cxx_frame, context,
349                                   NULL, nested_frame->descr, &nested_frame->frame,
350                                   nested_frame->trylevel, context );
351     }
352 }
353
354 static inline PEXCEPTION_REGISTRATION __wine_push_frame( PEXCEPTION_REGISTRATION frame )
355 {
356 #if defined(__GNUC__) && defined(__i386__)
357     PEXCEPTION_REGISTRATION prev;
358     __asm__ __volatile__(".byte 0x64\n\tmovl (0),%0"
359                          "\n\tmovl %0,(%1)"
360                          "\n\t.byte 0x64\n\tmovl %1,(0)"
361                          : "=&r" (prev) : "r" (frame) : "memory" );
362     return prev;
363 #else
364     NT_TIB *teb = (NT_TIB *)NtCurrentTeb();
365     frame->prev = (void *)teb->ExceptionList;
366     teb->ExceptionList = (void *)frame;
367     return frame->prev;
368 #endif
369 }
370
371 static inline PEXCEPTION_REGISTRATION __wine_pop_frame( PEXCEPTION_REGISTRATION frame )
372 {
373 #if defined(__GNUC__) && defined(__i386__)
374     __asm__ __volatile__(".byte 0x64\n\tmovl %0,(0)"
375                          : : "r" (frame->prev) : "memory" );
376     return frame->prev;
377
378 #else
379     NT_TIB *teb = (NT_TIB *)NtCurrentTeb();
380     teb->ExceptionList = (void *)frame->prev;
381     return frame->prev;
382 #endif
383 }
384
385 /* find and call the appropriate catch block for an exception */
386 /* returns the address to continue execution to after the catch block was called */
387 inline static void *call_catch_block( PEXCEPTION_RECORD rec, cxx_exception_frame *frame,
388                                       cxx_function_descr *descr, int nested_trylevel,
389                                       cxx_exception_type *info )
390 {
391     int i, j;
392     void *addr, *object = (void *)rec->ExceptionInformation[1];
393     struct catch_func_nested_frame nested_frame;
394     int trylevel = frame->trylevel;
395     PTHREADDATA thread_data = GetThreadData();
396
397     for (i = 0; i < descr->tryblock_count; i++)
398     {
399         tryblock_info *tryblock = &descr->tryblock[i];
400
401         if (trylevel < tryblock->start_level) continue;
402         if (trylevel > tryblock->end_level) continue;
403
404         /* got a try block */
405         for (j = 0; j < tryblock->catchblock_count; j++)
406         {
407             catchblock_info *catchblock = &tryblock->catchblock[j];
408             cxx_type_info *type = find_caught_type( info, catchblock );
409             if (!type) continue;
410
411 #if 0
412             TRACE( "matched type %p in tryblock %d catchblock %d\n", type, i, j );
413 #endif
414
415             /* copy the exception to its destination on the stack */
416             copy_exception( object, frame, catchblock, type );
417
418             /* unwind the stack */
419             RtlUnwind( &(frame->frame), 0, rec, 0 );
420             cxx_local_unwind( frame, descr, tryblock->start_level );
421             frame->trylevel = tryblock->end_level + 1;
422
423             /* call the catch block */
424 #if 0
425             TRACE( "calling catch block %p for type %p addr %p ebp %p\n",
426                    catchblock, type, catchblock->handler, &frame->ebp );
427 #endif
428
429             /* setup an exception block for nested exceptions */
430
431             nested_frame.frame.handler = catch_function_nested_handler;
432             nested_frame.prev_rec  = thread_data->exc_record;
433             nested_frame.cxx_frame = frame;
434             nested_frame.descr     = descr;
435             nested_frame.trylevel  = nested_trylevel + 1;
436
437             __wine_push_frame( &nested_frame.frame );
438             thread_data->exc_record = rec;
439             addr = call_ebp_func( catchblock->handler, &frame->ebp );
440             thread_data->exc_record = nested_frame.prev_rec;
441             __wine_pop_frame( &nested_frame.frame );
442
443             if (info->destructor) call_dtor( info->destructor, object );
444 #if 0
445             TRACE( "done, continuing at %p\n", addr );
446 #endif
447             return addr;
448         }
449     }
450     return NULL;
451 }
452
453
454 /*********************************************************************
455  *              cxx_frame_handler
456  *
457  * Implementation of __CxxFrameHandler.
458  */
459 static DWORD cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
460                                 PCONTEXT exc_context, PEXCEPTION_REGISTRATION* dispatch,
461                                 cxx_function_descr *descr, PEXCEPTION_REGISTRATION nested_frame,
462                                 int nested_trylevel, CONTEXT_X86 *context )
463 {
464     cxx_exception_type *exc_type;
465     void *next_ip;
466
467     if (descr->magic != CXX_FRAME_MAGIC)
468     {
469         OutputDebugStringA ( "invalid frame magic\n" );
470         return ExceptionContinueSearch;
471     }
472     if (rec->ExceptionFlags & (EH_UNWINDING|EH_EXIT_UNWIND))
473     {
474         if (descr->unwind_count && !nested_trylevel) cxx_local_unwind( frame, descr, -1 );
475         return ExceptionContinueSearch;
476     }
477     if (!descr->tryblock_count) return ExceptionContinueSearch;
478
479     exc_type = (cxx_exception_type *)rec->ExceptionInformation[2];
480     if (rec->ExceptionCode == CXX_EXCEPTION &&
481         rec->ExceptionInformation[0] > CXX_FRAME_MAGIC &&
482         exc_type->custom_handler)
483     {
484         return exc_type->custom_handler( rec, frame, exc_context, dispatch,
485                                          descr, nested_trylevel, nested_frame, 0 );
486     }
487
488     if (!exc_type)  /* nested exception, fetch info from original exception */
489     {
490         rec = GetThreadData()->exc_record;
491         exc_type = (cxx_exception_type *)rec->ExceptionInformation[2];
492     }
493
494 #if 0
495     if (TRACE_ON(seh))
496     {
497         TRACE("handling C++ exception rec %p frame %p trylevel %d descr %p nested_frame %p\n",
498               rec, frame, frame->trylevel, descr, nested_frame );
499         dump_exception_type( exc_type );
500         dump_function_descr( descr, exc_type );
501     }
502 #endif
503
504     next_ip = call_catch_block( rec, frame, descr, frame->trylevel, exc_type );
505
506     if (!next_ip) return ExceptionContinueSearch;
507     rec->ExceptionFlags &= ~EH_NONCONTINUABLE;
508     context->Eip = (DWORD)next_ip;
509     context->Ebp = (DWORD)&frame->ebp;
510     context->Esp = ((DWORD*)frame)[-1];
511     return ExceptionContinueExecution;
512 }
513
514
515 /*********************************************************************
516  *              __CxxFrameHandler (MSVCRT.@)
517  */
518 void __CxxFrameHandler( PEXCEPTION_RECORD rec, PEXCEPTION_REGISTRATION frame,
519                         PCONTEXT exc_context, PEXCEPTION_REGISTRATION* dispatch,
520                         CONTEXT_X86 *context )
521 {
522     cxx_function_descr *descr = (cxx_function_descr *)context->Eax;
523     context->Eax = cxx_frame_handler( rec, (cxx_exception_frame *)frame,
524                                       exc_context, dispatch, descr, NULL, 0, context );
525 }
526
527 /*********************************************************************
528  *              _CxxThrowException (MSVCRT.@)
529  */
530 void _CxxThrowException( void *object, cxx_exception_type *type )
531 {
532     DWORD args[3];
533
534     args[0] = CXX_FRAME_MAGIC;
535     args[1] = (DWORD)object;
536     args[2] = (DWORD)type;
537     RaiseException( CXX_EXCEPTION, EH_NONCONTINUABLE, 3, args );
538 }