msvcrt: Make _flsbuf thread safe.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 "winternl.h"
34 #include "msvcrt.h"
35 #include "wine/exception.h"
36 #include "excpt.h"
37 #include "wine/debug.h"
38
39 #include "cppexcept.h"
40
41 #ifdef __i386__  /* CxxFrameHandler is not supported on non-i386 */
42
43 WINE_DEFAULT_DEBUG_CHANNEL(seh);
44
45 DWORD CDECL cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
46                                PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch,
47                                const cxx_function_descr *descr,
48                                EXCEPTION_REGISTRATION_RECORD* nested_frame, int nested_trylevel );
49
50 /* call a function with a given ebp */
51 static inline void *call_ebp_func( void *func, void *ebp )
52 {
53     void *ret;
54     int dummy;
55     __asm__ __volatile__ ("pushl %%ebx\n\t"
56                           "pushl %%ebp\n\t"
57                           "movl %4,%%ebp\n\t"
58                           "call *%%eax\n\t"
59                           "popl %%ebp\n\t"
60                           "popl %%ebx"
61                           : "=a" (ret), "=S" (dummy), "=D" (dummy)
62                           : "0" (func), "1" (ebp) : "ecx", "edx", "memory" );
63     return ret;
64 }
65
66 /* call a copy constructor */
67 static inline void call_copy_ctor( void *func, void *this, void *src, int has_vbase )
68 {
69     TRACE( "calling copy ctor %p object %p src %p\n", func, this, src );
70     if (has_vbase)
71         /* in that case copy ctor takes an extra bool indicating whether to copy the base class */
72         __asm__ __volatile__("pushl $1; pushl %2; call *%0"
73                              : : "r" (func), "c" (this), "r" (src) : "eax", "edx", "memory" );
74     else
75         __asm__ __volatile__("pushl %2; call *%0"
76                              : : "r" (func), "c" (this), "r" (src) : "eax", "edx", "memory" );
77 }
78
79 /* call the destructor of the exception object */
80 static inline void call_dtor( void *func, void *object )
81 {
82     __asm__ __volatile__("call *%0" : : "r" (func), "c" (object) : "eax", "edx", "memory" );
83 }
84
85 /* continue execution to the specified address after exception is caught */
86 static inline void DECLSPEC_NORETURN continue_after_catch( cxx_exception_frame* frame, void *addr )
87 {
88     __asm__ __volatile__("movl -4(%0),%%esp; leal 12(%0),%%ebp; jmp *%1"
89                          : : "r" (frame), "a" (addr) );
90     for (;;) ; /* unreached */
91 }
92
93 static inline void dump_type( const cxx_type_info *type )
94 {
95     TRACE( "flags %x type %p %s offsets %d,%d,%d size %d copy ctor %p\n",
96              type->flags, type->type_info, dbgstr_type_info(type->type_info),
97              type->offsets.this_offset, type->offsets.vbase_descr, type->offsets.vbase_offset,
98              type->size, type->copy_ctor );
99 }
100
101 static void dump_exception_type( const cxx_exception_type *type )
102 {
103     UINT i;
104
105     TRACE( "flags %x destr %p handler %p type info %p\n",
106              type->flags, type->destructor, type->custom_handler, type->type_info_table );
107     for (i = 0; i < type->type_info_table->count; i++)
108     {
109         TRACE( "    %d: ", i );
110         dump_type( type->type_info_table->info[i] );
111     }
112 }
113
114 static void dump_function_descr( const cxx_function_descr *descr )
115 {
116     UINT i;
117     int j;
118
119     TRACE( "magic %x\n", descr->magic );
120     TRACE( "unwind table: %p %d\n", descr->unwind_table, descr->unwind_count );
121     for (i = 0; i < descr->unwind_count; i++)
122     {
123         TRACE( "    %d: prev %d func %p\n", i,
124                  descr->unwind_table[i].prev, descr->unwind_table[i].handler );
125     }
126     TRACE( "try table: %p %d\n", descr->tryblock, descr->tryblock_count );
127     for (i = 0; i < descr->tryblock_count; i++)
128     {
129         TRACE( "    %d: start %d end %d catchlevel %d catch %p %d\n", i,
130                  descr->tryblock[i].start_level, descr->tryblock[i].end_level,
131                  descr->tryblock[i].catch_level, descr->tryblock[i].catchblock,
132                  descr->tryblock[i].catchblock_count );
133         for (j = 0; j < descr->tryblock[i].catchblock_count; j++)
134         {
135             const catchblock_info *ptr = &descr->tryblock[i].catchblock[j];
136             TRACE( "        %d: flags %x offset %d handler %p type %p %s\n",
137                      j, ptr->flags, ptr->offset, ptr->handler,
138                      ptr->type_info, dbgstr_type_info( ptr->type_info ) );
139         }
140     }
141     if (descr->magic <= CXX_FRAME_MAGIC_VC6) return;
142     TRACE( "expect list: %p\n", descr->expect_list );
143     if (descr->magic <= CXX_FRAME_MAGIC_VC7) return;
144     TRACE( "flags: %08x\n", descr->flags );
145 }
146
147 /* check if the exception type is caught by a given catch block, and return the type that matched */
148 static const cxx_type_info *find_caught_type( cxx_exception_type *exc_type,
149                                               const catchblock_info *catchblock )
150 {
151     UINT i;
152
153     for (i = 0; i < exc_type->type_info_table->count; i++)
154     {
155         const cxx_type_info *type = exc_type->type_info_table->info[i];
156
157         if (!catchblock->type_info) return type;   /* catch(...) matches any type */
158         if (catchblock->type_info != type->type_info)
159         {
160             if (strcmp( catchblock->type_info->mangled, type->type_info->mangled )) continue;
161         }
162         /* type is the same, now check the flags */
163         if ((exc_type->flags & TYPE_FLAG_CONST) &&
164             !(catchblock->flags & TYPE_FLAG_CONST)) continue;
165         if ((exc_type->flags & TYPE_FLAG_VOLATILE) &&
166             !(catchblock->flags & TYPE_FLAG_VOLATILE)) continue;
167         return type;  /* it matched */
168     }
169     return NULL;
170 }
171
172
173 /* copy the exception object where the catch block wants it */
174 static void copy_exception( void *object, cxx_exception_frame *frame,
175                             const catchblock_info *catchblock, const cxx_type_info *type )
176 {
177     void **dest_ptr;
178
179     if (!catchblock->type_info || !catchblock->type_info->mangled[0]) return;
180     if (!catchblock->offset) return;
181     dest_ptr = (void **)((char *)&frame->ebp + catchblock->offset);
182
183     if (catchblock->flags & TYPE_FLAG_REFERENCE)
184     {
185         *dest_ptr = get_this_pointer( &type->offsets, object );
186     }
187     else if (type->flags & CLASS_IS_SIMPLE_TYPE)
188     {
189         memmove( dest_ptr, object, type->size );
190         /* if it is a pointer, adjust it */
191         if (type->size == sizeof(void *)) *dest_ptr = get_this_pointer( &type->offsets, *dest_ptr );
192     }
193     else  /* copy the object */
194     {
195         if (type->copy_ctor)
196             call_copy_ctor( type->copy_ctor, dest_ptr, get_this_pointer(&type->offsets,object),
197                             (type->flags & CLASS_HAS_VIRTUAL_BASE_CLASS) );
198         else
199             memmove( dest_ptr, get_this_pointer(&type->offsets,object), type->size );
200     }
201 }
202
203 /* unwind the local function up to a given trylevel */
204 static void cxx_local_unwind( cxx_exception_frame* frame, const cxx_function_descr *descr, int last_level)
205 {
206     void (*handler)(void);
207     int trylevel = frame->trylevel;
208
209     while (trylevel != last_level)
210     {
211         if (trylevel < 0 || trylevel >= descr->unwind_count)
212         {
213             ERR( "invalid trylevel %d\n", trylevel );
214             MSVCRT_terminate();
215         }
216         handler = descr->unwind_table[trylevel].handler;
217         if (handler)
218         {
219             TRACE( "calling unwind handler %p trylevel %d last %d ebp %p\n",
220                    handler, trylevel, last_level, &frame->ebp );
221             call_ebp_func( handler, &frame->ebp );
222         }
223         trylevel = descr->unwind_table[trylevel].prev;
224     }
225     frame->trylevel = last_level;
226 }
227
228 /* exception frame for nested exceptions in catch block */
229 struct catch_func_nested_frame
230 {
231     EXCEPTION_REGISTRATION_RECORD frame;     /* standard exception frame */
232     EXCEPTION_RECORD             *prev_rec;  /* previous record to restore in thread data */
233     cxx_exception_frame          *cxx_frame; /* frame of parent exception */
234     const cxx_function_descr     *descr;     /* descriptor of parent exception */
235     int                           trylevel;  /* current try level */
236     EXCEPTION_RECORD             *rec;       /* rec associated with frame */
237 };
238
239 /* handler for exceptions happening while calling a catch function */
240 static DWORD catch_function_nested_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
241                                             CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
242 {
243     struct catch_func_nested_frame *nested_frame = (struct catch_func_nested_frame *)frame;
244
245     if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
246     {
247         msvcrt_get_thread_data()->exc_record = nested_frame->prev_rec;
248         return ExceptionContinueSearch;
249     }
250
251     TRACE( "got nested exception in catch function\n" );
252
253     if(rec->ExceptionCode == CXX_EXCEPTION)
254     {
255         PEXCEPTION_RECORD prev_rec = nested_frame->rec;
256         if(rec->ExceptionInformation[1] == 0 && rec->ExceptionInformation[2] == 0)
257         {
258             /* exception was rethrown */
259             rec->ExceptionInformation[1] = prev_rec->ExceptionInformation[1];
260             rec->ExceptionInformation[2] = prev_rec->ExceptionInformation[2];
261             TRACE("detect rethrow: re-propagate: obj: %lx, type: %lx\n",
262                     rec->ExceptionInformation[1], rec->ExceptionInformation[2]);
263         }
264         else {
265             /* new exception in exception handler, destroy old */
266             void *object = (void*)prev_rec->ExceptionInformation[1];
267             cxx_exception_type *info = (cxx_exception_type*) prev_rec->ExceptionInformation[2];
268             TRACE("detect threw new exception in catch block - destroy old(obj: %p type: %p)\n",
269                     object, info);
270             if(info && info->destructor)
271                 call_dtor( info->destructor, object );
272         }
273     }
274
275     return cxx_frame_handler( rec, nested_frame->cxx_frame, context,
276                               NULL, nested_frame->descr, &nested_frame->frame,
277                               nested_frame->trylevel );
278 }
279
280 /* find and call the appropriate catch block for an exception */
281 /* returns the address to continue execution to after the catch block was called */
282 static inline void call_catch_block( PEXCEPTION_RECORD rec, cxx_exception_frame *frame,
283                                      const cxx_function_descr *descr, int nested_trylevel,
284                                      cxx_exception_type *info )
285 {
286     UINT i;
287     int j;
288     void *addr, *object = (void *)rec->ExceptionInformation[1];
289     struct catch_func_nested_frame nested_frame;
290     int trylevel = frame->trylevel;
291     thread_data_t *thread_data = msvcrt_get_thread_data();
292     DWORD save_esp = ((DWORD*)frame)[-1];
293
294     for (i = 0; i < descr->tryblock_count; i++)
295     {
296         const tryblock_info *tryblock = &descr->tryblock[i];
297
298         if (trylevel < tryblock->start_level) continue;
299         if (trylevel > tryblock->end_level) continue;
300
301         /* got a try block */
302         for (j = 0; j < tryblock->catchblock_count; j++)
303         {
304             const catchblock_info *catchblock = &tryblock->catchblock[j];
305             if(info)
306             {
307                 const cxx_type_info *type = find_caught_type( info, catchblock );
308                 if (!type) continue;
309
310                 TRACE( "matched type %p in tryblock %d catchblock %d\n", type, i, j );
311
312                 /* copy the exception to its destination on the stack */
313                 copy_exception( object, frame, catchblock, type );
314             }
315             else
316             {
317                 /* no CXX_EXCEPTION only proceed with a catch(...) block*/
318                 if(catchblock->type_info)
319                     continue;
320                 TRACE("found catch(...) block\n");
321             }
322
323             /* unwind the stack */
324             RtlUnwind( frame, 0, rec, 0 );
325             cxx_local_unwind( frame, descr, tryblock->start_level );
326             frame->trylevel = tryblock->end_level + 1;
327
328             /* call the catch block */
329             TRACE( "calling catch block %p addr %p ebp %p\n",
330                    catchblock, catchblock->handler, &frame->ebp );
331
332             /* setup an exception block for nested exceptions */
333
334             nested_frame.frame.Handler = catch_function_nested_handler;
335             nested_frame.prev_rec  = thread_data->exc_record;
336             nested_frame.cxx_frame = frame;
337             nested_frame.descr     = descr;
338             nested_frame.trylevel  = nested_trylevel + 1;
339             nested_frame.rec = rec;
340
341             __wine_push_frame( &nested_frame.frame );
342             thread_data->exc_record = rec;
343             addr = call_ebp_func( catchblock->handler, &frame->ebp );
344             thread_data->exc_record = nested_frame.prev_rec;
345             __wine_pop_frame( &nested_frame.frame );
346
347             ((DWORD*)frame)[-1] = save_esp;
348             if (info && info->destructor) call_dtor( info->destructor, object );
349             TRACE( "done, continuing at %p\n", addr );
350
351             continue_after_catch( frame, addr );
352         }
353     }
354 }
355
356
357 /*********************************************************************
358  *              cxx_frame_handler
359  *
360  * Implementation of __CxxFrameHandler.
361  */
362 DWORD CDECL cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
363                                PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch,
364                                const cxx_function_descr *descr,
365                                EXCEPTION_REGISTRATION_RECORD* nested_frame,
366                                int nested_trylevel )
367 {
368     cxx_exception_type *exc_type;
369
370     if (descr->magic < CXX_FRAME_MAGIC_VC6 || descr->magic > CXX_FRAME_MAGIC_VC8)
371     {
372         ERR( "invalid frame magic %x\n", descr->magic );
373         return ExceptionContinueSearch;
374     }
375     if (descr->magic >= CXX_FRAME_MAGIC_VC8 &&
376         (descr->flags & FUNC_DESCR_SYNCHRONOUS) &&
377         (rec->ExceptionCode != CXX_EXCEPTION))
378         return ExceptionContinueSearch;  /* handle only c++ exceptions */
379
380     if (rec->ExceptionFlags & (EH_UNWINDING|EH_EXIT_UNWIND))
381     {
382         if (descr->unwind_count && !nested_trylevel) cxx_local_unwind( frame, descr, -1 );
383         return ExceptionContinueSearch;
384     }
385     if (!descr->tryblock_count) return ExceptionContinueSearch;
386
387     if(rec->ExceptionCode == CXX_EXCEPTION)
388     {
389         exc_type = (cxx_exception_type *)rec->ExceptionInformation[2];
390
391         if (rec->ExceptionInformation[0] > CXX_FRAME_MAGIC_VC8 &&
392                 exc_type->custom_handler)
393         {
394             return exc_type->custom_handler( rec, frame, context, dispatch,
395                                          descr, nested_trylevel, nested_frame, 0 );
396         }
397
398         if (TRACE_ON(seh))
399         {
400             TRACE("handling C++ exception rec %p frame %p trylevel %d descr %p nested_frame %p\n",
401                   rec, frame, frame->trylevel, descr, nested_frame );
402             dump_exception_type( exc_type );
403             dump_function_descr( descr );
404         }
405     }
406     else
407     {
408         exc_type = NULL;
409         TRACE("handling C exception code %x  rec %p frame %p trylevel %d descr %p nested_frame %p\n",
410               rec->ExceptionCode,  rec, frame, frame->trylevel, descr, nested_frame );
411     }
412
413     call_catch_block( rec, frame, descr, frame->trylevel, exc_type );
414     return ExceptionContinueSearch;
415 }
416
417
418 /*********************************************************************
419  *              __CxxFrameHandler (MSVCRT.@)
420  */
421 extern DWORD CDECL __CxxFrameHandler( PEXCEPTION_RECORD rec, EXCEPTION_REGISTRATION_RECORD* frame,
422                                       PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch );
423 __ASM_GLOBAL_FUNC( __CxxFrameHandler,
424                    "pushl $0\n\t"        /* nested_trylevel */
425                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
426                    "pushl $0\n\t"        /* nested_frame */
427                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
428                    "pushl %eax\n\t"      /* descr */
429                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
430                    "pushl 28(%esp)\n\t"  /* dispatch */
431                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
432                    "pushl 28(%esp)\n\t"  /* context */
433                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
434                    "pushl 28(%esp)\n\t"  /* frame */
435                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
436                    "pushl 28(%esp)\n\t"  /* rec */
437                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
438                    "call " __ASM_NAME("cxx_frame_handler") "\n\t"
439                    "add $28,%esp\n\t"
440                    __ASM_CFI(".cfi_adjust_cfa_offset -28\n\t")
441                    "ret" )
442
443
444 /*********************************************************************
445  *              __CxxLongjmpUnwind (MSVCRT.@)
446  *
447  * Callback meant to be used as UnwindFunc for setjmp/longjmp.
448  */
449 void __stdcall __CxxLongjmpUnwind( const struct MSVCRT___JUMP_BUFFER *buf )
450 {
451     cxx_exception_frame *frame = (cxx_exception_frame *)buf->Registration;
452     const cxx_function_descr *descr = (const cxx_function_descr *)buf->UnwindData[0];
453
454     TRACE( "unwinding frame %p descr %p trylevel %ld\n", frame, descr, buf->TryLevel );
455     cxx_local_unwind( frame, descr, buf->TryLevel );
456 }
457
458 #endif  /* __i386__ */
459
460
461 /*********************************************************************
462  *              __CppXcptFilter (MSVCRT.@)
463  */
464 int CDECL __CppXcptFilter(NTSTATUS ex, PEXCEPTION_POINTERS ptr)
465 {
466     /* only filter c++ exceptions */
467     if (ex != CXX_EXCEPTION) return EXCEPTION_CONTINUE_SEARCH;
468     return _XcptFilter( ex, ptr );
469 }
470
471 /*********************************************************************
472  *              _CxxThrowException (MSVCRT.@)
473  */
474 void WINAPI _CxxThrowException( exception *object, const cxx_exception_type *type )
475 {
476     ULONG_PTR args[3];
477
478     args[0] = CXX_FRAME_MAGIC_VC6;
479     args[1] = (ULONG_PTR)object;
480     args[2] = (ULONG_PTR)type;
481     RaiseException( CXX_EXCEPTION, EH_NONCONTINUABLE, 3, args );
482 }
483
484 /*********************************************************************
485  *              __CxxDetectRethrow (MSVCRT.@)
486  */
487 BOOL CDECL __CxxDetectRethrow(PEXCEPTION_POINTERS ptrs)
488 {
489   PEXCEPTION_RECORD rec;
490
491   if (!ptrs)
492     return FALSE;
493
494   rec = ptrs->ExceptionRecord;
495
496   if (rec->ExceptionCode == CXX_EXCEPTION &&
497       rec->NumberParameters == 3 &&
498       rec->ExceptionInformation[0] == CXX_FRAME_MAGIC_VC6 &&
499       rec->ExceptionInformation[2])
500   {
501     ptrs->ExceptionRecord = msvcrt_get_thread_data()->exc_record;
502     return TRUE;
503   }
504   return (msvcrt_get_thread_data()->exc_record == rec);
505 }
506
507 /*********************************************************************
508  *              __CxxQueryExceptionSize (MSVCRT.@)
509  */
510 unsigned int CDECL __CxxQueryExceptionSize(void)
511 {
512   return sizeof(cxx_exception_type);
513 }