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