msvcrt: Call _wsopen_s function in _sopen_s.
[wine] / dlls / msvcrt / except_i386.c
1 /*
2  * msvcrt C++ exception handling
3  *
4  * Copyright 2000 Jon Griffiths
5  * Copyright 2002 Alexandre Julliard
6  * Copyright 2005 Juan Lang
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  *
22  * NOTES
23  * A good reference is the article "How a C++ compiler implements
24  * exception handling" by Vishal Kochhar, available on
25  * www.thecodeproject.com.
26  */
27
28 #include "config.h"
29 #include "wine/port.h"
30
31 #ifdef __i386__
32
33 #include <stdarg.h>
34
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winternl.h"
38 #include "msvcrt.h"
39 #include "wine/exception.h"
40 #include "excpt.h"
41 #include "wine/debug.h"
42
43 #include "cppexcept.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(seh);
46
47
48 /* the exception frame used by CxxFrameHandler */
49 typedef struct __cxx_exception_frame
50 {
51     EXCEPTION_REGISTRATION_RECORD  frame;    /* the standard exception frame */
52     int                            trylevel;
53     DWORD                          ebp;
54 } cxx_exception_frame;
55
56 /* info about a single catch {} block */
57 typedef struct __catchblock_info
58 {
59     UINT             flags;         /* flags (see below) */
60     const type_info *type_info;     /* C++ type caught by this block */
61     int              offset;        /* stack offset to copy exception object to */
62     void           (*handler)(void);/* catch block handler code */
63 } catchblock_info;
64 #define TYPE_FLAG_CONST      1
65 #define TYPE_FLAG_VOLATILE   2
66 #define TYPE_FLAG_REFERENCE  8
67
68 /* info about a single try {} block */
69 typedef struct __tryblock_info
70 {
71     int                    start_level;      /* start trylevel of that block */
72     int                    end_level;        /* end trylevel of that block */
73     int                    catch_level;      /* initial trylevel of the catch block */
74     int                    catchblock_count; /* count of catch blocks in array */
75     const catchblock_info *catchblock;       /* array of catch blocks */
76 } tryblock_info;
77
78 /* info about the unwind handler for a given trylevel */
79 typedef struct __unwind_info
80 {
81     int    prev;          /* prev trylevel unwind handler, to run after this one */
82     void (*handler)(void);/* unwind handler */
83 } unwind_info;
84
85 /* descriptor of all try blocks of a given function */
86 typedef struct __cxx_function_descr
87 {
88     UINT                 magic;          /* must be CXX_FRAME_MAGIC */
89     UINT                 unwind_count;   /* number of unwind handlers */
90     const unwind_info   *unwind_table;   /* array of unwind handlers */
91     UINT                 tryblock_count; /* number of try blocks */
92     const tryblock_info *tryblock;       /* array of try blocks */
93     UINT                 ipmap_count;
94     const void          *ipmap;
95     const void          *expect_list;    /* expected exceptions list when magic >= VC7 */
96     UINT                 flags;          /* flags when magic >= VC8 */
97 } cxx_function_descr;
98
99 #define FUNC_DESCR_SYNCHRONOUS  1        /* synchronous exceptions only (built with /EHs) */
100
101 typedef struct _SCOPETABLE
102 {
103   int previousTryLevel;
104   int (*lpfnFilter)(PEXCEPTION_POINTERS);
105   int (*lpfnHandler)(void);
106 } SCOPETABLE, *PSCOPETABLE;
107
108 typedef struct _MSVCRT_EXCEPTION_FRAME
109 {
110   EXCEPTION_REGISTRATION_RECORD *prev;
111   void (*handler)(PEXCEPTION_RECORD, EXCEPTION_REGISTRATION_RECORD*,
112                   PCONTEXT, PEXCEPTION_RECORD);
113   PSCOPETABLE scopetable;
114   int trylevel;
115   int _ebp;
116   PEXCEPTION_POINTERS xpointers;
117 } MSVCRT_EXCEPTION_FRAME;
118
119 typedef struct
120 {
121   int   gs_cookie_offset;
122   ULONG gs_cookie_xor;
123   int   eh_cookie_offset;
124   ULONG eh_cookie_xor;
125   SCOPETABLE entries[1];
126 } SCOPETABLE_V4;
127
128 #define TRYLEVEL_END (-1) /* End of trylevel list */
129
130 DWORD CDECL cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
131                                PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch,
132                                const cxx_function_descr *descr,
133                                EXCEPTION_REGISTRATION_RECORD* nested_frame, int nested_trylevel );
134
135 /* call a function with a given ebp */
136 static inline void *call_ebp_func( void *func, void *ebp )
137 {
138     void *ret;
139     int dummy;
140     __asm__ __volatile__ ("pushl %%ebx\n\t"
141                           "pushl %%ebp\n\t"
142                           "movl %4,%%ebp\n\t"
143                           "call *%%eax\n\t"
144                           "popl %%ebp\n\t"
145                           "popl %%ebx"
146                           : "=a" (ret), "=S" (dummy), "=D" (dummy)
147                           : "0" (func), "1" (ebp) : "ecx", "edx", "memory" );
148     return ret;
149 }
150
151 /* call a copy constructor */
152 static inline void call_copy_ctor( void *func, void *this, void *src, int has_vbase )
153 {
154     TRACE( "calling copy ctor %p object %p src %p\n", func, this, src );
155     if (has_vbase)
156         /* in that case copy ctor takes an extra bool indicating whether to copy the base class */
157         __asm__ __volatile__("pushl $1; pushl %2; call *%0"
158                              : : "r" (func), "c" (this), "r" (src) : "eax", "edx", "memory" );
159     else
160         __asm__ __volatile__("pushl %2; call *%0"
161                              : : "r" (func), "c" (this), "r" (src) : "eax", "edx", "memory" );
162 }
163
164 /* call the destructor of the exception object */
165 static inline void call_dtor( void *func, void *object )
166 {
167     __asm__ __volatile__("call *%0" : : "r" (func), "c" (object) : "eax", "edx", "memory" );
168 }
169
170 /* continue execution to the specified address after exception is caught */
171 static inline void DECLSPEC_NORETURN continue_after_catch( cxx_exception_frame* frame, void *addr )
172 {
173     __asm__ __volatile__("movl -4(%0),%%esp; leal 12(%0),%%ebp; jmp *%1"
174                          : : "r" (frame), "a" (addr) );
175     for (;;) ; /* unreached */
176 }
177
178 static inline void call_finally_block( void *code_block, void *base_ptr )
179 {
180     __asm__ __volatile__ ("movl %1,%%ebp; call *%%eax"
181                           : : "a" (code_block), "g" (base_ptr));
182 }
183
184 static inline int call_filter( int (*func)(PEXCEPTION_POINTERS), void *arg, void *ebp )
185 {
186     int ret;
187     __asm__ __volatile__ ("pushl %%ebp; pushl %3; movl %2,%%ebp; call *%%eax; popl %%ebp; popl %%ebp"
188                           : "=a" (ret)
189                           : "0" (func), "r" (ebp), "r" (arg)
190                           : "ecx", "edx", "memory" );
191     return ret;
192 }
193
194 static inline int call_unwind_func( int (*func)(void), void *ebp )
195 {
196     int ret;
197     __asm__ __volatile__ ("pushl %%ebp\n\t"
198                           "pushl %%ebx\n\t"
199                           "pushl %%esi\n\t"
200                           "pushl %%edi\n\t"
201                           "movl %2,%%ebp\n\t"
202                           "call *%0\n\t"
203                           "popl %%edi\n\t"
204                           "popl %%esi\n\t"
205                           "popl %%ebx\n\t"
206                           "popl %%ebp"
207                           : "=a" (ret)
208                           : "0" (func), "r" (ebp)
209                           : "ecx", "edx", "memory" );
210     return ret;
211 }
212
213 static inline void dump_type( const cxx_type_info *type )
214 {
215     TRACE( "flags %x type %p %s offsets %d,%d,%d size %d copy ctor %p\n",
216              type->flags, type->type_info, dbgstr_type_info(type->type_info),
217              type->offsets.this_offset, type->offsets.vbase_descr, type->offsets.vbase_offset,
218              type->size, type->copy_ctor );
219 }
220
221 static void dump_exception_type( const cxx_exception_type *type )
222 {
223     UINT i;
224
225     TRACE( "flags %x destr %p handler %p type info %p\n",
226              type->flags, type->destructor, type->custom_handler, type->type_info_table );
227     for (i = 0; i < type->type_info_table->count; i++)
228     {
229         TRACE( "    %d: ", i );
230         dump_type( type->type_info_table->info[i] );
231     }
232 }
233
234 static void dump_function_descr( const cxx_function_descr *descr )
235 {
236     UINT i;
237     int j;
238
239     TRACE( "magic %x\n", descr->magic );
240     TRACE( "unwind table: %p %d\n", descr->unwind_table, descr->unwind_count );
241     for (i = 0; i < descr->unwind_count; i++)
242     {
243         TRACE( "    %d: prev %d func %p\n", i,
244                  descr->unwind_table[i].prev, descr->unwind_table[i].handler );
245     }
246     TRACE( "try table: %p %d\n", descr->tryblock, descr->tryblock_count );
247     for (i = 0; i < descr->tryblock_count; i++)
248     {
249         TRACE( "    %d: start %d end %d catchlevel %d catch %p %d\n", i,
250                  descr->tryblock[i].start_level, descr->tryblock[i].end_level,
251                  descr->tryblock[i].catch_level, descr->tryblock[i].catchblock,
252                  descr->tryblock[i].catchblock_count );
253         for (j = 0; j < descr->tryblock[i].catchblock_count; j++)
254         {
255             const catchblock_info *ptr = &descr->tryblock[i].catchblock[j];
256             TRACE( "        %d: flags %x offset %d handler %p type %p %s\n",
257                      j, ptr->flags, ptr->offset, ptr->handler,
258                      ptr->type_info, dbgstr_type_info( ptr->type_info ) );
259         }
260     }
261     if (descr->magic <= CXX_FRAME_MAGIC_VC6) return;
262     TRACE( "expect list: %p\n", descr->expect_list );
263     if (descr->magic <= CXX_FRAME_MAGIC_VC7) return;
264     TRACE( "flags: %08x\n", descr->flags );
265 }
266
267 /* check if the exception type is caught by a given catch block, and return the type that matched */
268 static const cxx_type_info *find_caught_type( cxx_exception_type *exc_type,
269                                               const catchblock_info *catchblock )
270 {
271     UINT i;
272
273     for (i = 0; i < exc_type->type_info_table->count; i++)
274     {
275         const cxx_type_info *type = exc_type->type_info_table->info[i];
276
277         if (!catchblock->type_info) return type;   /* catch(...) matches any type */
278         if (catchblock->type_info != type->type_info)
279         {
280             if (strcmp( catchblock->type_info->mangled, type->type_info->mangled )) continue;
281         }
282         /* type is the same, now check the flags */
283         if ((exc_type->flags & TYPE_FLAG_CONST) &&
284             !(catchblock->flags & TYPE_FLAG_CONST)) continue;
285         if ((exc_type->flags & TYPE_FLAG_VOLATILE) &&
286             !(catchblock->flags & TYPE_FLAG_VOLATILE)) continue;
287         return type;  /* it matched */
288     }
289     return NULL;
290 }
291
292
293 /* copy the exception object where the catch block wants it */
294 static void copy_exception( void *object, cxx_exception_frame *frame,
295                             const catchblock_info *catchblock, const cxx_type_info *type )
296 {
297     void **dest_ptr;
298
299     if (!catchblock->type_info || !catchblock->type_info->mangled[0]) return;
300     if (!catchblock->offset) return;
301     dest_ptr = (void **)((char *)&frame->ebp + catchblock->offset);
302
303     if (catchblock->flags & TYPE_FLAG_REFERENCE)
304     {
305         *dest_ptr = get_this_pointer( &type->offsets, object );
306     }
307     else if (type->flags & CLASS_IS_SIMPLE_TYPE)
308     {
309         memmove( dest_ptr, object, type->size );
310         /* if it is a pointer, adjust it */
311         if (type->size == sizeof(void *)) *dest_ptr = get_this_pointer( &type->offsets, *dest_ptr );
312     }
313     else  /* copy the object */
314     {
315         if (type->copy_ctor)
316             call_copy_ctor( type->copy_ctor, dest_ptr, get_this_pointer(&type->offsets,object),
317                             (type->flags & CLASS_HAS_VIRTUAL_BASE_CLASS) );
318         else
319             memmove( dest_ptr, get_this_pointer(&type->offsets,object), type->size );
320     }
321 }
322
323 /* unwind the local function up to a given trylevel */
324 static void cxx_local_unwind( cxx_exception_frame* frame, const cxx_function_descr *descr, int last_level)
325 {
326     void (*handler)(void);
327     int trylevel = frame->trylevel;
328
329     while (trylevel != last_level)
330     {
331         if (trylevel < 0 || trylevel >= descr->unwind_count)
332         {
333             ERR( "invalid trylevel %d\n", trylevel );
334             MSVCRT_terminate();
335         }
336         handler = descr->unwind_table[trylevel].handler;
337         if (handler)
338         {
339             TRACE( "calling unwind handler %p trylevel %d last %d ebp %p\n",
340                    handler, trylevel, last_level, &frame->ebp );
341             call_ebp_func( handler, &frame->ebp );
342         }
343         trylevel = descr->unwind_table[trylevel].prev;
344     }
345     frame->trylevel = last_level;
346 }
347
348 /* exception frame for nested exceptions in catch block */
349 struct catch_func_nested_frame
350 {
351     EXCEPTION_REGISTRATION_RECORD frame;     /* standard exception frame */
352     EXCEPTION_RECORD             *prev_rec;  /* previous record to restore in thread data */
353     cxx_exception_frame          *cxx_frame; /* frame of parent exception */
354     const cxx_function_descr     *descr;     /* descriptor of parent exception */
355     int                           trylevel;  /* current try level */
356     EXCEPTION_RECORD             *rec;       /* rec associated with frame */
357 };
358
359 /* handler for exceptions happening while calling a catch function */
360 static DWORD catch_function_nested_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
361                                             CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
362 {
363     struct catch_func_nested_frame *nested_frame = (struct catch_func_nested_frame *)frame;
364
365     if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
366     {
367         msvcrt_get_thread_data()->exc_record = nested_frame->prev_rec;
368         return ExceptionContinueSearch;
369     }
370
371     TRACE( "got nested exception in catch function\n" );
372
373     if(rec->ExceptionCode == CXX_EXCEPTION)
374     {
375         PEXCEPTION_RECORD prev_rec = nested_frame->rec;
376         if((rec->ExceptionInformation[1] == 0 && rec->ExceptionInformation[2] == 0) ||
377                 (rec->ExceptionInformation[1] == prev_rec->ExceptionInformation[1] &&
378                  rec->ExceptionInformation[2] == prev_rec->ExceptionInformation[2]))
379         {
380             /* exception was rethrown */
381             rec->ExceptionInformation[1] = prev_rec->ExceptionInformation[1];
382             rec->ExceptionInformation[2] = prev_rec->ExceptionInformation[2];
383             TRACE("detect rethrow: re-propagate: obj: %lx, type: %lx\n",
384                     rec->ExceptionInformation[1], rec->ExceptionInformation[2]);
385         }
386         else if (nested_frame->prev_rec &&
387                 nested_frame->prev_rec->ExceptionInformation[1] == prev_rec->ExceptionInformation[1] &&
388                 nested_frame->prev_rec->ExceptionInformation[2] == prev_rec->ExceptionInformation[2])
389         {
390             TRACE("detect threw new exception in catch block - not owning old(obj: %lx type: %lx)\n",
391                     prev_rec->ExceptionInformation[1], prev_rec->ExceptionInformation[2]);
392         }
393         else {
394             /* new exception in exception handler, destroy old */
395             void *object = (void*)prev_rec->ExceptionInformation[1];
396             cxx_exception_type *info = (cxx_exception_type*) prev_rec->ExceptionInformation[2];
397             TRACE("detect threw new exception in catch block - destroy old(obj: %p type: %p)\n",
398                     object, info);
399             if(info && info->destructor)
400                 call_dtor( info->destructor, object );
401         }
402     }
403
404     return cxx_frame_handler( rec, nested_frame->cxx_frame, context,
405                               NULL, nested_frame->descr, &nested_frame->frame,
406                               nested_frame->trylevel );
407 }
408
409 /* find and call the appropriate catch block for an exception */
410 /* returns the address to continue execution to after the catch block was called */
411 static inline void call_catch_block( PEXCEPTION_RECORD rec, cxx_exception_frame *frame,
412                                      const cxx_function_descr *descr, int nested_trylevel,
413                                      cxx_exception_type *info )
414 {
415     UINT i;
416     int j;
417     void *addr, *object = (void *)rec->ExceptionInformation[1];
418     struct catch_func_nested_frame nested_frame;
419     int trylevel = frame->trylevel;
420     thread_data_t *thread_data = msvcrt_get_thread_data();
421     DWORD save_esp = ((DWORD*)frame)[-1];
422
423     for (i = 0; i < descr->tryblock_count; i++)
424     {
425         const tryblock_info *tryblock = &descr->tryblock[i];
426
427         if (trylevel < tryblock->start_level) continue;
428         if (trylevel > tryblock->end_level) continue;
429
430         /* got a try block */
431         for (j = 0; j < tryblock->catchblock_count; j++)
432         {
433             const catchblock_info *catchblock = &tryblock->catchblock[j];
434             if(info)
435             {
436                 const cxx_type_info *type = find_caught_type( info, catchblock );
437                 if (!type) continue;
438
439                 TRACE( "matched type %p in tryblock %d catchblock %d\n", type, i, j );
440
441                 /* copy the exception to its destination on the stack */
442                 copy_exception( object, frame, catchblock, type );
443             }
444             else
445             {
446                 /* no CXX_EXCEPTION only proceed with a catch(...) block*/
447                 if(catchblock->type_info)
448                     continue;
449                 TRACE("found catch(...) block\n");
450             }
451
452             /* unwind the stack */
453             RtlUnwind( frame, 0, rec, 0 );
454             cxx_local_unwind( frame, descr, tryblock->start_level );
455             frame->trylevel = tryblock->end_level + 1;
456
457             /* call the catch block */
458             TRACE( "calling catch block %p addr %p ebp %p\n",
459                    catchblock, catchblock->handler, &frame->ebp );
460
461             /* setup an exception block for nested exceptions */
462
463             nested_frame.frame.Handler = catch_function_nested_handler;
464             nested_frame.prev_rec  = thread_data->exc_record;
465             nested_frame.cxx_frame = frame;
466             nested_frame.descr     = descr;
467             nested_frame.trylevel  = nested_trylevel + 1;
468             nested_frame.rec = rec;
469
470             __wine_push_frame( &nested_frame.frame );
471             thread_data->exc_record = rec;
472             addr = call_ebp_func( catchblock->handler, &frame->ebp );
473             thread_data->exc_record = nested_frame.prev_rec;
474             __wine_pop_frame( &nested_frame.frame );
475
476             ((DWORD*)frame)[-1] = save_esp;
477             if (info && info->destructor) call_dtor( info->destructor, object );
478             TRACE( "done, continuing at %p\n", addr );
479
480             continue_after_catch( frame, addr );
481         }
482     }
483 }
484
485
486 /*********************************************************************
487  *              cxx_frame_handler
488  *
489  * Implementation of __CxxFrameHandler.
490  */
491 DWORD CDECL cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
492                                PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch,
493                                const cxx_function_descr *descr,
494                                EXCEPTION_REGISTRATION_RECORD* nested_frame,
495                                int nested_trylevel )
496 {
497     cxx_exception_type *exc_type;
498
499     if (descr->magic < CXX_FRAME_MAGIC_VC6 || descr->magic > CXX_FRAME_MAGIC_VC8)
500     {
501         ERR( "invalid frame magic %x\n", descr->magic );
502         return ExceptionContinueSearch;
503     }
504     if (descr->magic >= CXX_FRAME_MAGIC_VC8 &&
505         (descr->flags & FUNC_DESCR_SYNCHRONOUS) &&
506         (rec->ExceptionCode != CXX_EXCEPTION))
507         return ExceptionContinueSearch;  /* handle only c++ exceptions */
508
509     if (rec->ExceptionFlags & (EH_UNWINDING|EH_EXIT_UNWIND))
510     {
511         if (descr->unwind_count && !nested_trylevel) cxx_local_unwind( frame, descr, -1 );
512         return ExceptionContinueSearch;
513     }
514     if (!descr->tryblock_count) return ExceptionContinueSearch;
515
516     if(rec->ExceptionCode == CXX_EXCEPTION)
517     {
518         if (rec->ExceptionInformation[1] == 0 && rec->ExceptionInformation[2] == 0)
519         {
520             EXCEPTION_RECORD *exc_record = msvcrt_get_thread_data()->exc_record;
521             rec->ExceptionInformation[1] = exc_record->ExceptionInformation[1];
522             rec->ExceptionInformation[2] = exc_record->ExceptionInformation[2];
523             TRACE("detect rethrow: obj: %lx, type: %lx\n",
524                     rec->ExceptionInformation[1], rec->ExceptionInformation[2]);
525         }
526
527         exc_type = (cxx_exception_type *)rec->ExceptionInformation[2];
528
529         if (rec->ExceptionInformation[0] > CXX_FRAME_MAGIC_VC8 &&
530                 exc_type->custom_handler)
531         {
532             return exc_type->custom_handler( rec, frame, context, dispatch,
533                                          descr, nested_trylevel, nested_frame, 0 );
534         }
535
536         if (TRACE_ON(seh))
537         {
538             TRACE("handling C++ exception rec %p frame %p trylevel %d descr %p nested_frame %p\n",
539                   rec, frame, frame->trylevel, descr, nested_frame );
540             dump_exception_type( exc_type );
541             dump_function_descr( descr );
542         }
543     }
544     else
545     {
546         exc_type = NULL;
547         TRACE("handling C exception code %x  rec %p frame %p trylevel %d descr %p nested_frame %p\n",
548               rec->ExceptionCode,  rec, frame, frame->trylevel, descr, nested_frame );
549     }
550
551     call_catch_block( rec, frame, descr, frame->trylevel, exc_type );
552     return ExceptionContinueSearch;
553 }
554
555
556 /*********************************************************************
557  *              __CxxFrameHandler (MSVCRT.@)
558  */
559 extern DWORD CDECL __CxxFrameHandler( PEXCEPTION_RECORD rec, EXCEPTION_REGISTRATION_RECORD* frame,
560                                       PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch );
561 __ASM_GLOBAL_FUNC( __CxxFrameHandler,
562                    "pushl $0\n\t"        /* nested_trylevel */
563                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
564                    "pushl $0\n\t"        /* nested_frame */
565                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
566                    "pushl %eax\n\t"      /* descr */
567                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
568                    "pushl 28(%esp)\n\t"  /* dispatch */
569                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
570                    "pushl 28(%esp)\n\t"  /* context */
571                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
572                    "pushl 28(%esp)\n\t"  /* frame */
573                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
574                    "pushl 28(%esp)\n\t"  /* rec */
575                    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
576                    "call " __ASM_NAME("cxx_frame_handler") "\n\t"
577                    "add $28,%esp\n\t"
578                    __ASM_CFI(".cfi_adjust_cfa_offset -28\n\t")
579                    "ret" )
580
581
582 /*********************************************************************
583  *              __CxxLongjmpUnwind (MSVCRT.@)
584  *
585  * Callback meant to be used as UnwindFunc for setjmp/longjmp.
586  */
587 void __stdcall __CxxLongjmpUnwind( const struct MSVCRT___JUMP_BUFFER *buf )
588 {
589     cxx_exception_frame *frame = (cxx_exception_frame *)buf->Registration;
590     const cxx_function_descr *descr = (const cxx_function_descr *)buf->UnwindData[0];
591
592     TRACE( "unwinding frame %p descr %p trylevel %ld\n", frame, descr, buf->TryLevel );
593     cxx_local_unwind( frame, descr, buf->TryLevel );
594 }
595
596 /*********************************************************************
597  *              __CppXcptFilter (MSVCRT.@)
598  */
599 int CDECL __CppXcptFilter(NTSTATUS ex, PEXCEPTION_POINTERS ptr)
600 {
601     /* only filter c++ exceptions */
602     if (ex != CXX_EXCEPTION) return EXCEPTION_CONTINUE_SEARCH;
603     return _XcptFilter( ex, ptr );
604 }
605
606 /*********************************************************************
607  *              __CxxDetectRethrow (MSVCRT.@)
608  */
609 BOOL CDECL __CxxDetectRethrow(PEXCEPTION_POINTERS ptrs)
610 {
611   PEXCEPTION_RECORD rec;
612
613   if (!ptrs)
614     return FALSE;
615
616   rec = ptrs->ExceptionRecord;
617
618   if (rec->ExceptionCode == CXX_EXCEPTION &&
619       rec->NumberParameters == 3 &&
620       rec->ExceptionInformation[0] == CXX_FRAME_MAGIC_VC6 &&
621       rec->ExceptionInformation[2])
622   {
623     ptrs->ExceptionRecord = msvcrt_get_thread_data()->exc_record;
624     return TRUE;
625   }
626   return (msvcrt_get_thread_data()->exc_record == rec);
627 }
628
629 /*********************************************************************
630  *              __CxxQueryExceptionSize (MSVCRT.@)
631  */
632 unsigned int CDECL __CxxQueryExceptionSize(void)
633 {
634   return sizeof(cxx_exception_type);
635 }
636
637
638 /*********************************************************************
639  *              _EH_prolog (MSVCRT.@)
640  */
641
642 /* Provided for VC++ binary compatibility only */
643 __ASM_GLOBAL_FUNC(_EH_prolog,
644                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")  /* skip ret addr */
645                   "pushl $-1\n\t"
646                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
647                   "pushl %eax\n\t"
648                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
649                   "pushl %fs:0\n\t"
650                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
651                   "movl  %esp, %fs:0\n\t"
652                   "movl  12(%esp), %eax\n\t"
653                   "movl  %ebp, 12(%esp)\n\t"
654                   "leal  12(%esp), %ebp\n\t"
655                   "pushl %eax\n\t"
656                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
657                   "ret")
658
659 static const SCOPETABLE_V4 *get_scopetable_v4( MSVCRT_EXCEPTION_FRAME *frame, ULONG_PTR cookie )
660 {
661     return (const SCOPETABLE_V4 *)((ULONG_PTR)frame->scopetable ^ cookie);
662 }
663
664 static DWORD MSVCRT_nested_handler(PEXCEPTION_RECORD rec,
665                                    EXCEPTION_REGISTRATION_RECORD* frame,
666                                    PCONTEXT context,
667                                    EXCEPTION_REGISTRATION_RECORD** dispatch)
668 {
669   if (!(rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))
670     return ExceptionContinueSearch;
671   *dispatch = frame;
672   return ExceptionCollidedUnwind;
673 }
674
675 static void msvcrt_local_unwind2(MSVCRT_EXCEPTION_FRAME* frame, int trylevel, void *ebp)
676 {
677   EXCEPTION_REGISTRATION_RECORD reg;
678
679   TRACE("(%p,%d,%d)\n",frame, frame->trylevel, trylevel);
680
681   /* Register a handler in case of a nested exception */
682   reg.Handler = MSVCRT_nested_handler;
683   reg.Prev = NtCurrentTeb()->Tib.ExceptionList;
684   __wine_push_frame(&reg);
685
686   while (frame->trylevel != TRYLEVEL_END && frame->trylevel != trylevel)
687   {
688       int level = frame->trylevel;
689       frame->trylevel = frame->scopetable[level].previousTryLevel;
690       if (!frame->scopetable[level].lpfnFilter)
691       {
692           TRACE( "__try block cleanup level %d handler %p ebp %p\n",
693                  level, frame->scopetable[level].lpfnHandler, ebp );
694           call_unwind_func( frame->scopetable[level].lpfnHandler, ebp );
695       }
696   }
697   __wine_pop_frame(&reg);
698   TRACE("unwound OK\n");
699 }
700
701 static void msvcrt_local_unwind4( ULONG *cookie, MSVCRT_EXCEPTION_FRAME* frame, int trylevel, void *ebp )
702 {
703     EXCEPTION_REGISTRATION_RECORD reg;
704     const SCOPETABLE_V4 *scopetable = get_scopetable_v4( frame, *cookie );
705
706     TRACE("(%p,%d,%d)\n",frame, frame->trylevel, trylevel);
707
708     /* Register a handler in case of a nested exception */
709     reg.Handler = MSVCRT_nested_handler;
710     reg.Prev = NtCurrentTeb()->Tib.ExceptionList;
711     __wine_push_frame(&reg);
712
713     while (frame->trylevel != -2 && frame->trylevel != trylevel)
714     {
715         int level = frame->trylevel;
716         frame->trylevel = scopetable->entries[level].previousTryLevel;
717         if (!scopetable->entries[level].lpfnFilter)
718         {
719             TRACE( "__try block cleanup level %d handler %p ebp %p\n",
720                    level, scopetable->entries[level].lpfnHandler, ebp );
721             call_unwind_func( scopetable->entries[level].lpfnHandler, ebp );
722         }
723     }
724     __wine_pop_frame(&reg);
725     TRACE("unwound OK\n");
726 }
727
728 /*******************************************************************
729  *              _local_unwind2 (MSVCRT.@)
730  */
731 void CDECL _local_unwind2(MSVCRT_EXCEPTION_FRAME* frame, int trylevel)
732 {
733     msvcrt_local_unwind2( frame, trylevel, &frame->_ebp );
734 }
735
736 /*******************************************************************
737  *              _local_unwind4 (MSVCRT.@)
738  */
739 void CDECL _local_unwind4( ULONG *cookie, MSVCRT_EXCEPTION_FRAME* frame, int trylevel )
740 {
741     msvcrt_local_unwind4( cookie, frame, trylevel, &frame->_ebp );
742 }
743
744 /*******************************************************************
745  *              _global_unwind2 (MSVCRT.@)
746  */
747 void CDECL _global_unwind2(EXCEPTION_REGISTRATION_RECORD* frame)
748 {
749     TRACE("(%p)\n",frame);
750     RtlUnwind( frame, 0, 0, 0 );
751 }
752
753 /*********************************************************************
754  *              _except_handler2 (MSVCRT.@)
755  */
756 int CDECL _except_handler2(PEXCEPTION_RECORD rec,
757                            EXCEPTION_REGISTRATION_RECORD* frame,
758                            PCONTEXT context,
759                            EXCEPTION_REGISTRATION_RECORD** dispatcher)
760 {
761   FIXME("exception %x flags=%x at %p handler=%p %p %p stub\n",
762         rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
763         frame->Handler, context, dispatcher);
764   return ExceptionContinueSearch;
765 }
766
767 /*********************************************************************
768  *              _except_handler3 (MSVCRT.@)
769  */
770 int CDECL _except_handler3(PEXCEPTION_RECORD rec,
771                            MSVCRT_EXCEPTION_FRAME* frame,
772                            PCONTEXT context, void* dispatcher)
773 {
774   int retval, trylevel;
775   EXCEPTION_POINTERS exceptPtrs;
776   PSCOPETABLE pScopeTable;
777
778   TRACE("exception %x flags=%x at %p handler=%p %p %p semi-stub\n",
779         rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
780         frame->handler, context, dispatcher);
781
782   __asm__ __volatile__ ("cld");
783
784   if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
785   {
786     /* Unwinding the current frame */
787     msvcrt_local_unwind2(frame, TRYLEVEL_END, &frame->_ebp);
788     TRACE("unwound current frame, returning ExceptionContinueSearch\n");
789     return ExceptionContinueSearch;
790   }
791   else
792   {
793     /* Hunting for handler */
794     exceptPtrs.ExceptionRecord = rec;
795     exceptPtrs.ContextRecord = context;
796     *((DWORD *)frame-1) = (DWORD)&exceptPtrs;
797     trylevel = frame->trylevel;
798     pScopeTable = frame->scopetable;
799
800     while (trylevel != TRYLEVEL_END)
801     {
802       TRACE( "level %d prev %d filter %p\n", trylevel, pScopeTable[trylevel].previousTryLevel,
803              pScopeTable[trylevel].lpfnFilter );
804       if (pScopeTable[trylevel].lpfnFilter)
805       {
806         retval = call_filter( pScopeTable[trylevel].lpfnFilter, &exceptPtrs, &frame->_ebp );
807
808         TRACE("filter returned %s\n", retval == EXCEPTION_CONTINUE_EXECUTION ?
809               "CONTINUE_EXECUTION" : retval == EXCEPTION_EXECUTE_HANDLER ?
810               "EXECUTE_HANDLER" : "CONTINUE_SEARCH");
811
812         if (retval == EXCEPTION_CONTINUE_EXECUTION)
813           return ExceptionContinueExecution;
814
815         if (retval == EXCEPTION_EXECUTE_HANDLER)
816         {
817           /* Unwind all higher frames, this one will handle the exception */
818           _global_unwind2((EXCEPTION_REGISTRATION_RECORD*)frame);
819           msvcrt_local_unwind2(frame, trylevel, &frame->_ebp);
820
821           /* Set our trylevel to the enclosing block, and call the __finally
822            * code, which won't return
823            */
824           frame->trylevel = pScopeTable[trylevel].previousTryLevel;
825           TRACE("__finally block %p\n",pScopeTable[trylevel].lpfnHandler);
826           call_finally_block(pScopeTable[trylevel].lpfnHandler, &frame->_ebp);
827           ERR("Returned from __finally block - expect crash!\n");
828        }
829       }
830       trylevel = pScopeTable[trylevel].previousTryLevel;
831     }
832   }
833   TRACE("reached TRYLEVEL_END, returning ExceptionContinueSearch\n");
834   return ExceptionContinueSearch;
835 }
836
837 /*********************************************************************
838  *              _except_handler4_common (MSVCRT.@)
839  */
840 int CDECL _except_handler4_common( ULONG *cookie, void (*check_cookie)(void),
841                                    EXCEPTION_RECORD *rec, MSVCRT_EXCEPTION_FRAME *frame,
842                                    CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
843 {
844     int retval, trylevel;
845     EXCEPTION_POINTERS exceptPtrs;
846     const SCOPETABLE_V4 *scope_table = get_scopetable_v4( frame, *cookie );
847
848     TRACE( "exception %x flags=%x at %p handler=%p %p %p cookie=%x scope table=%p cookies=%d/%x,%d/%x\n",
849            rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
850            frame->handler, context, dispatcher, *cookie, scope_table,
851            scope_table->gs_cookie_offset, scope_table->gs_cookie_xor,
852            scope_table->eh_cookie_offset, scope_table->eh_cookie_xor );
853
854     /* FIXME: no cookie validation yet */
855
856     if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
857     {
858         /* Unwinding the current frame */
859         msvcrt_local_unwind4( cookie, frame, -2, &frame->_ebp );
860         TRACE("unwound current frame, returning ExceptionContinueSearch\n");
861         return ExceptionContinueSearch;
862     }
863     else
864     {
865         /* Hunting for handler */
866         exceptPtrs.ExceptionRecord = rec;
867         exceptPtrs.ContextRecord = context;
868         *((DWORD *)frame-1) = (DWORD)&exceptPtrs;
869         trylevel = frame->trylevel;
870
871         while (trylevel != -2)
872         {
873             TRACE( "level %d prev %d filter %p\n", trylevel,
874                    scope_table->entries[trylevel].previousTryLevel,
875                    scope_table->entries[trylevel].lpfnFilter );
876             if (scope_table->entries[trylevel].lpfnFilter)
877             {
878                 retval = call_filter( scope_table->entries[trylevel].lpfnFilter, &exceptPtrs, &frame->_ebp );
879
880                 TRACE("filter returned %s\n", retval == EXCEPTION_CONTINUE_EXECUTION ?
881                       "CONTINUE_EXECUTION" : retval == EXCEPTION_EXECUTE_HANDLER ?
882                       "EXECUTE_HANDLER" : "CONTINUE_SEARCH");
883
884                 if (retval == EXCEPTION_CONTINUE_EXECUTION)
885                     return ExceptionContinueExecution;
886
887                 if (retval == EXCEPTION_EXECUTE_HANDLER)
888                 {
889                     /* Unwind all higher frames, this one will handle the exception */
890                     _global_unwind2((EXCEPTION_REGISTRATION_RECORD*)frame);
891                     msvcrt_local_unwind4( cookie, frame, trylevel, &frame->_ebp );
892
893                     /* Set our trylevel to the enclosing block, and call the __finally
894                      * code, which won't return
895                      */
896                     frame->trylevel = scope_table->entries[trylevel].previousTryLevel;
897                     TRACE("__finally block %p\n",scope_table->entries[trylevel].lpfnHandler);
898                     call_finally_block(scope_table->entries[trylevel].lpfnHandler, &frame->_ebp);
899                     ERR("Returned from __finally block - expect crash!\n");
900                 }
901             }
902             trylevel = scope_table->entries[trylevel].previousTryLevel;
903         }
904     }
905     TRACE("reached -2, returning ExceptionContinueSearch\n");
906     return ExceptionContinueSearch;
907 }
908
909
910 /*
911  * setjmp/longjmp implementation
912  */
913
914 #define MSVCRT_JMP_MAGIC 0x56433230 /* ID value for new jump structure */
915 typedef void (__stdcall *MSVCRT_unwind_function)(const struct MSVCRT___JUMP_BUFFER *);
916
917 /* define an entrypoint for setjmp/setjmp3 that stores the registers in the jmp buf */
918 /* and then jumps to the C backend function */
919 #define DEFINE_SETJMP_ENTRYPOINT(name) \
920     __ASM_GLOBAL_FUNC( name, \
921                        "movl 4(%esp),%ecx\n\t"   /* jmp_buf */      \
922                        "movl %ebp,0(%ecx)\n\t"   /* jmp_buf.Ebp */  \
923                        "movl %ebx,4(%ecx)\n\t"   /* jmp_buf.Ebx */  \
924                        "movl %edi,8(%ecx)\n\t"   /* jmp_buf.Edi */  \
925                        "movl %esi,12(%ecx)\n\t"  /* jmp_buf.Esi */  \
926                        "movl %esp,16(%ecx)\n\t"  /* jmp_buf.Esp */  \
927                        "movl 0(%esp),%eax\n\t"                      \
928                        "movl %eax,20(%ecx)\n\t"  /* jmp_buf.Eip */  \
929                        "jmp " __ASM_NAME("__regs_") # name )
930
931 /* restore the registers from the jmp buf upon longjmp */
932 extern void DECLSPEC_NORETURN longjmp_set_regs( struct MSVCRT___JUMP_BUFFER *jmp, int retval );
933 __ASM_GLOBAL_FUNC( longjmp_set_regs,
934                    "movl 4(%esp),%ecx\n\t"   /* jmp_buf */
935                    "movl 8(%esp),%eax\n\t"   /* retval */
936                    "movl 0(%ecx),%ebp\n\t"   /* jmp_buf.Ebp */
937                    "movl 4(%ecx),%ebx\n\t"   /* jmp_buf.Ebx */
938                    "movl 8(%ecx),%edi\n\t"   /* jmp_buf.Edi */
939                    "movl 12(%ecx),%esi\n\t"  /* jmp_buf.Esi */
940                    "movl 16(%ecx),%esp\n\t"  /* jmp_buf.Esp */
941                    "addl $4,%esp\n\t"        /* get rid of return address */
942                    "jmp *20(%ecx)\n\t"       /* jmp_buf.Eip */ )
943
944 /*
945  * The signatures of the setjmp/longjmp functions do not match that
946  * declared in the setjmp header so they don't follow the regular naming
947  * convention to avoid conflicts.
948  */
949
950 /*******************************************************************
951  *              _setjmp (MSVCRT.@)
952  */
953 DEFINE_SETJMP_ENTRYPOINT(MSVCRT__setjmp)
954 int CDECL __regs_MSVCRT__setjmp(struct MSVCRT___JUMP_BUFFER *jmp)
955 {
956     jmp->Registration = (unsigned long)NtCurrentTeb()->Tib.ExceptionList;
957     if (jmp->Registration == ~0UL)
958         jmp->TryLevel = TRYLEVEL_END;
959     else
960         jmp->TryLevel = ((MSVCRT_EXCEPTION_FRAME*)jmp->Registration)->trylevel;
961
962     TRACE("buf=%p ebx=%08lx esi=%08lx edi=%08lx ebp=%08lx esp=%08lx eip=%08lx frame=%08lx\n",
963           jmp, jmp->Ebx, jmp->Esi, jmp->Edi, jmp->Ebp, jmp->Esp, jmp->Eip, jmp->Registration );
964     return 0;
965 }
966
967 /*******************************************************************
968  *              _setjmp3 (MSVCRT.@)
969  */
970 DEFINE_SETJMP_ENTRYPOINT( MSVCRT__setjmp3 )
971 int CDECL __regs_MSVCRT__setjmp3(struct MSVCRT___JUMP_BUFFER *jmp, int nb_args, ...)
972 {
973     jmp->Cookie = MSVCRT_JMP_MAGIC;
974     jmp->UnwindFunc = 0;
975     jmp->Registration = (unsigned long)NtCurrentTeb()->Tib.ExceptionList;
976     if (jmp->Registration == ~0UL)
977     {
978         jmp->TryLevel = TRYLEVEL_END;
979     }
980     else
981     {
982         int i;
983         va_list args;
984
985         va_start( args, nb_args );
986         if (nb_args > 0) jmp->UnwindFunc = va_arg( args, unsigned long );
987         if (nb_args > 1) jmp->TryLevel = va_arg( args, unsigned long );
988         else jmp->TryLevel = ((MSVCRT_EXCEPTION_FRAME*)jmp->Registration)->trylevel;
989         for (i = 0; i < 6 && i < nb_args - 2; i++)
990             jmp->UnwindData[i] = va_arg( args, unsigned long );
991         va_end( args );
992     }
993
994     TRACE("buf=%p ebx=%08lx esi=%08lx edi=%08lx ebp=%08lx esp=%08lx eip=%08lx frame=%08lx\n",
995           jmp, jmp->Ebx, jmp->Esi, jmp->Edi, jmp->Ebp, jmp->Esp, jmp->Eip, jmp->Registration );
996     return 0;
997 }
998
999 /*********************************************************************
1000  *              longjmp (MSVCRT.@)
1001  */
1002 void CDECL MSVCRT_longjmp(struct MSVCRT___JUMP_BUFFER *jmp, int retval)
1003 {
1004     unsigned long cur_frame = 0;
1005
1006     TRACE("buf=%p ebx=%08lx esi=%08lx edi=%08lx ebp=%08lx esp=%08lx eip=%08lx frame=%08lx retval=%08x\n",
1007           jmp, jmp->Ebx, jmp->Esi, jmp->Edi, jmp->Ebp, jmp->Esp, jmp->Eip, jmp->Registration, retval );
1008
1009     cur_frame=(unsigned long)NtCurrentTeb()->Tib.ExceptionList;
1010     TRACE("cur_frame=%lx\n",cur_frame);
1011
1012     if (cur_frame != jmp->Registration)
1013         _global_unwind2((EXCEPTION_REGISTRATION_RECORD*)jmp->Registration);
1014
1015     if (jmp->Registration)
1016     {
1017         if (IsBadReadPtr(&jmp->Cookie, sizeof(long)) || jmp->Cookie != MSVCRT_JMP_MAGIC)
1018         {
1019             msvcrt_local_unwind2((MSVCRT_EXCEPTION_FRAME*)jmp->Registration,
1020                                  jmp->TryLevel, (void *)jmp->Ebp);
1021         }
1022         else if(jmp->UnwindFunc)
1023         {
1024             MSVCRT_unwind_function unwind_func;
1025
1026             unwind_func=(MSVCRT_unwind_function)jmp->UnwindFunc;
1027             unwind_func(jmp);
1028         }
1029     }
1030
1031     if (!retval)
1032         retval = 1;
1033
1034     longjmp_set_regs( jmp, retval );
1035 }
1036
1037 /*********************************************************************
1038  *              _seh_longjmp_unwind (MSVCRT.@)
1039  */
1040 void __stdcall _seh_longjmp_unwind(struct MSVCRT___JUMP_BUFFER *jmp)
1041 {
1042     msvcrt_local_unwind2( (MSVCRT_EXCEPTION_FRAME *)jmp->Registration, jmp->TryLevel, (void *)jmp->Ebp );
1043 }
1044
1045 /*********************************************************************
1046  *              _seh_longjmp_unwind4 (MSVCRT.@)
1047  */
1048 void __stdcall _seh_longjmp_unwind4(struct MSVCRT___JUMP_BUFFER *jmp)
1049 {
1050     msvcrt_local_unwind4( (void *)jmp->Cookie, (MSVCRT_EXCEPTION_FRAME *)jmp->Registration,
1051                           jmp->TryLevel, (void *)jmp->Ebp );
1052 }
1053
1054 #endif  /* __i386__ */