shell32: Comitted a Tango icon for the control panel.
[wine] / dlls / msvcrt / except.c
1 /*
2  * msvcrt.dll exception handling
3  *
4  * Copyright 2000 Jon Griffiths
5  * Copyright 2005 Juan Lang
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  *
21  * FIXME: Incomplete support for nested exceptions/try block cleanup.
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <stdarg.h>
28
29 #include "windef.h"
30 #include "winbase.h"
31 #include "winternl.h"
32 #include "wine/exception.h"
33 #include "msvcrt.h"
34 #include "excpt.h"
35 #include "wincon.h"
36 #include "wine/debug.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(seh);
39
40 /* VC++ extensions to Win32 SEH */
41 typedef struct _SCOPETABLE
42 {
43   int previousTryLevel;
44   int (*lpfnFilter)(PEXCEPTION_POINTERS);
45   int (*lpfnHandler)(void);
46 } SCOPETABLE, *PSCOPETABLE;
47
48 typedef struct _MSVCRT_EXCEPTION_FRAME
49 {
50   EXCEPTION_REGISTRATION_RECORD *prev;
51   void (*handler)(PEXCEPTION_RECORD, EXCEPTION_REGISTRATION_RECORD*,
52                   PCONTEXT, PEXCEPTION_RECORD);
53   PSCOPETABLE scopetable;
54   int trylevel;
55   int _ebp;
56   PEXCEPTION_POINTERS xpointers;
57 } MSVCRT_EXCEPTION_FRAME;
58
59 typedef struct
60 {
61   int   gs_cookie_offset;
62   ULONG gs_cookie_xor;
63   int   eh_cookie_offset;
64   ULONG eh_cookie_xor;
65   SCOPETABLE entries[1];
66 } SCOPETABLE_V4;
67
68 #define TRYLEVEL_END (-1) /* End of trylevel list */
69
70 #if defined(__GNUC__) && defined(__i386__)
71 static inline void call_finally_block( void *code_block, void *base_ptr )
72 {
73     __asm__ __volatile__ ("movl %1,%%ebp; call *%%eax"
74                           : : "a" (code_block), "g" (base_ptr));
75 }
76
77 static inline int call_filter( int (*func)(PEXCEPTION_POINTERS), void *arg, void *ebp )
78 {
79     int ret;
80     __asm__ __volatile__ ("pushl %%ebp; pushl %3; movl %2,%%ebp; call *%%eax; popl %%ebp; popl %%ebp"
81                           : "=a" (ret)
82                           : "0" (func), "r" (ebp), "r" (arg)
83                           : "ecx", "edx", "memory" );
84     return ret;
85 }
86
87 static inline int call_unwind_func( int (*func)(void), void *ebp )
88 {
89     int ret;
90     __asm__ __volatile__ ("pushl %%ebp\n\t"
91                           "pushl %%ebx\n\t"
92                           "pushl %%esi\n\t"
93                           "pushl %%edi\n\t"
94                           "movl %2,%%ebp\n\t"
95                           "call *%0\n\t"
96                           "popl %%edi\n\t"
97                           "popl %%esi\n\t"
98                           "popl %%ebx\n\t"
99                           "popl %%ebp"
100                           : "=a" (ret)
101                           : "0" (func), "r" (ebp)
102                           : "ecx", "edx", "memory" );
103     return ret;
104 }
105
106 #endif
107
108
109 #ifdef __i386__
110
111 static const SCOPETABLE_V4 *get_scopetable_v4( MSVCRT_EXCEPTION_FRAME *frame, ULONG_PTR cookie )
112 {
113     return (const SCOPETABLE_V4 *)((ULONG_PTR)frame->scopetable ^ cookie);
114 }
115
116 static DWORD MSVCRT_nested_handler(PEXCEPTION_RECORD rec,
117                                    EXCEPTION_REGISTRATION_RECORD* frame,
118                                    PCONTEXT context,
119                                    EXCEPTION_REGISTRATION_RECORD** dispatch)
120 {
121   if (!(rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))
122     return ExceptionContinueSearch;
123   *dispatch = frame;
124   return ExceptionCollidedUnwind;
125 }
126
127
128 /*********************************************************************
129  *              _EH_prolog (MSVCRT.@)
130  */
131
132 /* Provided for VC++ binary compatibility only */
133 __ASM_GLOBAL_FUNC(_EH_prolog,
134                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")  /* skip ret addr */
135                   "pushl $-1\n\t"
136                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
137                   "pushl %eax\n\t"
138                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
139                   "pushl %fs:0\n\t"
140                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
141                   "movl  %esp, %fs:0\n\t"
142                   "movl  12(%esp), %eax\n\t"
143                   "movl  %ebp, 12(%esp)\n\t"
144                   "leal  12(%esp), %ebp\n\t"
145                   "pushl %eax\n\t"
146                   __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
147                   "ret")
148
149 static void msvcrt_local_unwind2(MSVCRT_EXCEPTION_FRAME* frame, int trylevel, void *ebp)
150 {
151   EXCEPTION_REGISTRATION_RECORD reg;
152
153   TRACE("(%p,%d,%d)\n",frame, frame->trylevel, trylevel);
154
155   /* Register a handler in case of a nested exception */
156   reg.Handler = MSVCRT_nested_handler;
157   reg.Prev = NtCurrentTeb()->Tib.ExceptionList;
158   __wine_push_frame(&reg);
159
160   while (frame->trylevel != TRYLEVEL_END && frame->trylevel != trylevel)
161   {
162       int level = frame->trylevel;
163       frame->trylevel = frame->scopetable[level].previousTryLevel;
164       if (!frame->scopetable[level].lpfnFilter)
165       {
166           TRACE( "__try block cleanup level %d handler %p ebp %p\n",
167                  level, frame->scopetable[level].lpfnHandler, ebp );
168           call_unwind_func( frame->scopetable[level].lpfnHandler, ebp );
169       }
170   }
171   __wine_pop_frame(&reg);
172   TRACE("unwound OK\n");
173 }
174
175 static void msvcrt_local_unwind4( ULONG *cookie, MSVCRT_EXCEPTION_FRAME* frame, int trylevel, void *ebp )
176 {
177     EXCEPTION_REGISTRATION_RECORD reg;
178     const SCOPETABLE_V4 *scopetable = get_scopetable_v4( frame, *cookie );
179
180     TRACE("(%p,%d,%d)\n",frame, frame->trylevel, trylevel);
181
182     /* Register a handler in case of a nested exception */
183     reg.Handler = MSVCRT_nested_handler;
184     reg.Prev = NtCurrentTeb()->Tib.ExceptionList;
185     __wine_push_frame(&reg);
186
187     while (frame->trylevel != -2 && frame->trylevel != trylevel)
188     {
189         int level = frame->trylevel;
190         frame->trylevel = scopetable->entries[level].previousTryLevel;
191         if (!scopetable->entries[level].lpfnFilter)
192         {
193             TRACE( "__try block cleanup level %d handler %p ebp %p\n",
194                    level, scopetable->entries[level].lpfnHandler, ebp );
195             call_unwind_func( scopetable->entries[level].lpfnHandler, ebp );
196         }
197     }
198     __wine_pop_frame(&reg);
199     TRACE("unwound OK\n");
200 }
201
202 /*******************************************************************
203  *              _local_unwind2 (MSVCRT.@)
204  */
205 void CDECL _local_unwind2(MSVCRT_EXCEPTION_FRAME* frame, int trylevel)
206 {
207     msvcrt_local_unwind2( frame, trylevel, &frame->_ebp );
208 }
209
210 /*******************************************************************
211  *              _local_unwind4 (MSVCRT.@)
212  */
213 void CDECL _local_unwind4( ULONG *cookie, MSVCRT_EXCEPTION_FRAME* frame, int trylevel )
214 {
215     msvcrt_local_unwind4( cookie, frame, trylevel, &frame->_ebp );
216 }
217
218 /*******************************************************************
219  *              _global_unwind2 (MSVCRT.@)
220  */
221 void CDECL _global_unwind2(EXCEPTION_REGISTRATION_RECORD* frame)
222 {
223     TRACE("(%p)\n",frame);
224     RtlUnwind( frame, 0, 0, 0 );
225 }
226
227 /*********************************************************************
228  *              _except_handler2 (MSVCRT.@)
229  */
230 int CDECL _except_handler2(PEXCEPTION_RECORD rec,
231                            EXCEPTION_REGISTRATION_RECORD* frame,
232                            PCONTEXT context,
233                            EXCEPTION_REGISTRATION_RECORD** dispatcher)
234 {
235   FIXME("exception %x flags=%x at %p handler=%p %p %p stub\n",
236         rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
237         frame->Handler, context, dispatcher);
238   return ExceptionContinueSearch;
239 }
240
241 /*********************************************************************
242  *              _except_handler3 (MSVCRT.@)
243  */
244 int CDECL _except_handler3(PEXCEPTION_RECORD rec,
245                            MSVCRT_EXCEPTION_FRAME* frame,
246                            PCONTEXT context, void* dispatcher)
247 {
248   int retval, trylevel;
249   EXCEPTION_POINTERS exceptPtrs;
250   PSCOPETABLE pScopeTable;
251
252   TRACE("exception %x flags=%x at %p handler=%p %p %p semi-stub\n",
253         rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
254         frame->handler, context, dispatcher);
255
256   __asm__ __volatile__ ("cld");
257
258   if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
259   {
260     /* Unwinding the current frame */
261     msvcrt_local_unwind2(frame, TRYLEVEL_END, &frame->_ebp);
262     TRACE("unwound current frame, returning ExceptionContinueSearch\n");
263     return ExceptionContinueSearch;
264   }
265   else
266   {
267     /* Hunting for handler */
268     exceptPtrs.ExceptionRecord = rec;
269     exceptPtrs.ContextRecord = context;
270     *((DWORD *)frame-1) = (DWORD)&exceptPtrs;
271     trylevel = frame->trylevel;
272     pScopeTable = frame->scopetable;
273
274     while (trylevel != TRYLEVEL_END)
275     {
276       TRACE( "level %d prev %d filter %p\n", trylevel, pScopeTable[trylevel].previousTryLevel,
277              pScopeTable[trylevel].lpfnFilter );
278       if (pScopeTable[trylevel].lpfnFilter)
279       {
280         retval = call_filter( pScopeTable[trylevel].lpfnFilter, &exceptPtrs, &frame->_ebp );
281
282         TRACE("filter returned %s\n", retval == EXCEPTION_CONTINUE_EXECUTION ?
283               "CONTINUE_EXECUTION" : retval == EXCEPTION_EXECUTE_HANDLER ?
284               "EXECUTE_HANDLER" : "CONTINUE_SEARCH");
285
286         if (retval == EXCEPTION_CONTINUE_EXECUTION)
287           return ExceptionContinueExecution;
288
289         if (retval == EXCEPTION_EXECUTE_HANDLER)
290         {
291           /* Unwind all higher frames, this one will handle the exception */
292           _global_unwind2((EXCEPTION_REGISTRATION_RECORD*)frame);
293           msvcrt_local_unwind2(frame, trylevel, &frame->_ebp);
294
295           /* Set our trylevel to the enclosing block, and call the __finally
296            * code, which won't return
297            */
298           frame->trylevel = pScopeTable[trylevel].previousTryLevel;
299           TRACE("__finally block %p\n",pScopeTable[trylevel].lpfnHandler);
300           call_finally_block(pScopeTable[trylevel].lpfnHandler, &frame->_ebp);
301           ERR("Returned from __finally block - expect crash!\n");
302        }
303       }
304       trylevel = pScopeTable[trylevel].previousTryLevel;
305     }
306   }
307   TRACE("reached TRYLEVEL_END, returning ExceptionContinueSearch\n");
308   return ExceptionContinueSearch;
309 }
310
311 /*********************************************************************
312  *              _except_handler4_common (MSVCRT.@)
313  */
314 int CDECL _except_handler4_common( ULONG *cookie, void (*check_cookie)(void),
315                                    EXCEPTION_RECORD *rec, MSVCRT_EXCEPTION_FRAME *frame,
316                                    CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
317 {
318     int retval, trylevel;
319     EXCEPTION_POINTERS exceptPtrs;
320     const SCOPETABLE_V4 *scope_table = get_scopetable_v4( frame, *cookie );
321
322     TRACE( "exception %x flags=%x at %p handler=%p %p %p cookie=%x scope table=%p cookies=%d/%x,%d/%x\n",
323            rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
324            frame->handler, context, dispatcher, *cookie, scope_table,
325            scope_table->gs_cookie_offset, scope_table->gs_cookie_xor,
326            scope_table->eh_cookie_offset, scope_table->eh_cookie_xor );
327
328     /* FIXME: no cookie validation yet */
329
330     if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
331     {
332         /* Unwinding the current frame */
333         msvcrt_local_unwind4( cookie, frame, -2, &frame->_ebp );
334         TRACE("unwound current frame, returning ExceptionContinueSearch\n");
335         return ExceptionContinueSearch;
336     }
337     else
338     {
339         /* Hunting for handler */
340         exceptPtrs.ExceptionRecord = rec;
341         exceptPtrs.ContextRecord = context;
342         *((DWORD *)frame-1) = (DWORD)&exceptPtrs;
343         trylevel = frame->trylevel;
344
345         while (trylevel != -2)
346         {
347             TRACE( "level %d prev %d filter %p\n", trylevel,
348                    scope_table->entries[trylevel].previousTryLevel,
349                    scope_table->entries[trylevel].lpfnFilter );
350             if (scope_table->entries[trylevel].lpfnFilter)
351             {
352                 retval = call_filter( scope_table->entries[trylevel].lpfnFilter, &exceptPtrs, &frame->_ebp );
353
354                 TRACE("filter returned %s\n", retval == EXCEPTION_CONTINUE_EXECUTION ?
355                       "CONTINUE_EXECUTION" : retval == EXCEPTION_EXECUTE_HANDLER ?
356                       "EXECUTE_HANDLER" : "CONTINUE_SEARCH");
357
358                 if (retval == EXCEPTION_CONTINUE_EXECUTION)
359                     return ExceptionContinueExecution;
360
361                 if (retval == EXCEPTION_EXECUTE_HANDLER)
362                 {
363                     /* Unwind all higher frames, this one will handle the exception */
364                     _global_unwind2((EXCEPTION_REGISTRATION_RECORD*)frame);
365                     msvcrt_local_unwind4( cookie, frame, trylevel, &frame->_ebp );
366
367                     /* Set our trylevel to the enclosing block, and call the __finally
368                      * code, which won't return
369                      */
370                     frame->trylevel = scope_table->entries[trylevel].previousTryLevel;
371                     TRACE("__finally block %p\n",scope_table->entries[trylevel].lpfnHandler);
372                     call_finally_block(scope_table->entries[trylevel].lpfnHandler, &frame->_ebp);
373                     ERR("Returned from __finally block - expect crash!\n");
374                 }
375             }
376             trylevel = scope_table->entries[trylevel].previousTryLevel;
377         }
378     }
379     TRACE("reached -2, returning ExceptionContinueSearch\n");
380     return ExceptionContinueSearch;
381 }
382
383
384 /*
385  * setjmp/longjmp implementation
386  */
387
388 #define MSVCRT_JMP_MAGIC 0x56433230 /* ID value for new jump structure */
389 typedef void (__stdcall *MSVCRT_unwind_function)(const struct MSVCRT___JUMP_BUFFER *);
390
391 /* define an entrypoint for setjmp/setjmp3 that stores the registers in the jmp buf */
392 /* and then jumps to the C backend function */
393 #define DEFINE_SETJMP_ENTRYPOINT(name) \
394     __ASM_GLOBAL_FUNC( name, \
395                        "movl 4(%esp),%ecx\n\t"   /* jmp_buf */      \
396                        "movl %ebp,0(%ecx)\n\t"   /* jmp_buf.Ebp */  \
397                        "movl %ebx,4(%ecx)\n\t"   /* jmp_buf.Ebx */  \
398                        "movl %edi,8(%ecx)\n\t"   /* jmp_buf.Edi */  \
399                        "movl %esi,12(%ecx)\n\t"  /* jmp_buf.Esi */  \
400                        "movl %esp,16(%ecx)\n\t"  /* jmp_buf.Esp */  \
401                        "movl 0(%esp),%eax\n\t"                      \
402                        "movl %eax,20(%ecx)\n\t"  /* jmp_buf.Eip */  \
403                        "jmp " __ASM_NAME("__regs_") # name )
404
405 /* restore the registers from the jmp buf upon longjmp */
406 extern void DECLSPEC_NORETURN longjmp_set_regs( struct MSVCRT___JUMP_BUFFER *jmp, int retval );
407 __ASM_GLOBAL_FUNC( longjmp_set_regs,
408                    "movl 4(%esp),%ecx\n\t"   /* jmp_buf */
409                    "movl 8(%esp),%eax\n\t"   /* retval */
410                    "movl 0(%ecx),%ebp\n\t"   /* jmp_buf.Ebp */
411                    "movl 4(%ecx),%ebx\n\t"   /* jmp_buf.Ebx */
412                    "movl 8(%ecx),%edi\n\t"   /* jmp_buf.Edi */
413                    "movl 12(%ecx),%esi\n\t"  /* jmp_buf.Esi */
414                    "movl 16(%ecx),%esp\n\t"  /* jmp_buf.Esp */
415                    "addl $4,%esp\n\t"        /* get rid of return address */
416                    "jmp *20(%ecx)\n\t"       /* jmp_buf.Eip */ )
417
418 /*
419  * The signatures of the setjmp/longjmp functions do not match that
420  * declared in the setjmp header so they don't follow the regular naming
421  * convention to avoid conflicts.
422  */
423
424 /*******************************************************************
425  *              _setjmp (MSVCRT.@)
426  */
427 DEFINE_SETJMP_ENTRYPOINT(MSVCRT__setjmp)
428 int CDECL __regs_MSVCRT__setjmp(struct MSVCRT___JUMP_BUFFER *jmp)
429 {
430     jmp->Registration = (unsigned long)NtCurrentTeb()->Tib.ExceptionList;
431     if (jmp->Registration == ~0UL)
432         jmp->TryLevel = TRYLEVEL_END;
433     else
434         jmp->TryLevel = ((MSVCRT_EXCEPTION_FRAME*)jmp->Registration)->trylevel;
435
436     TRACE("buf=%p ebx=%08lx esi=%08lx edi=%08lx ebp=%08lx esp=%08lx eip=%08lx frame=%08lx\n",
437           jmp, jmp->Ebx, jmp->Esi, jmp->Edi, jmp->Ebp, jmp->Esp, jmp->Eip, jmp->Registration );
438     return 0;
439 }
440
441 /*******************************************************************
442  *              _setjmp3 (MSVCRT.@)
443  */
444 DEFINE_SETJMP_ENTRYPOINT( MSVCRT__setjmp3 )
445 int CDECL __regs_MSVCRT__setjmp3(struct MSVCRT___JUMP_BUFFER *jmp, int nb_args, ...)
446 {
447     jmp->Cookie = MSVCRT_JMP_MAGIC;
448     jmp->UnwindFunc = 0;
449     jmp->Registration = (unsigned long)NtCurrentTeb()->Tib.ExceptionList;
450     if (jmp->Registration == ~0UL)
451     {
452         jmp->TryLevel = TRYLEVEL_END;
453     }
454     else
455     {
456         int i;
457         va_list args;
458
459         va_start( args, nb_args );
460         if (nb_args > 0) jmp->UnwindFunc = va_arg( args, unsigned long );
461         if (nb_args > 1) jmp->TryLevel = va_arg( args, unsigned long );
462         else jmp->TryLevel = ((MSVCRT_EXCEPTION_FRAME*)jmp->Registration)->trylevel;
463         for (i = 0; i < 6 && i < nb_args - 2; i++)
464             jmp->UnwindData[i] = va_arg( args, unsigned long );
465         va_end( args );
466     }
467
468     TRACE("buf=%p ebx=%08lx esi=%08lx edi=%08lx ebp=%08lx esp=%08lx eip=%08lx frame=%08lx\n",
469           jmp, jmp->Ebx, jmp->Esi, jmp->Edi, jmp->Ebp, jmp->Esp, jmp->Eip, jmp->Registration );
470     return 0;
471 }
472
473 /*********************************************************************
474  *              longjmp (MSVCRT.@)
475  */
476 int CDECL MSVCRT_longjmp(struct MSVCRT___JUMP_BUFFER *jmp, int retval)
477 {
478     unsigned long cur_frame = 0;
479
480     TRACE("buf=%p ebx=%08lx esi=%08lx edi=%08lx ebp=%08lx esp=%08lx eip=%08lx frame=%08lx retval=%08x\n",
481           jmp, jmp->Ebx, jmp->Esi, jmp->Edi, jmp->Ebp, jmp->Esp, jmp->Eip, jmp->Registration, retval );
482
483     cur_frame=(unsigned long)NtCurrentTeb()->Tib.ExceptionList;
484     TRACE("cur_frame=%lx\n",cur_frame);
485
486     if (cur_frame != jmp->Registration)
487         _global_unwind2((EXCEPTION_REGISTRATION_RECORD*)jmp->Registration);
488
489     if (jmp->Registration)
490     {
491         if (!IsBadReadPtr(&jmp->Cookie, sizeof(long)) &&
492             jmp->Cookie == MSVCRT_JMP_MAGIC && jmp->UnwindFunc)
493         {
494             MSVCRT_unwind_function unwind_func;
495
496             unwind_func=(MSVCRT_unwind_function)jmp->UnwindFunc;
497             unwind_func(jmp);
498         }
499         else
500             msvcrt_local_unwind2((MSVCRT_EXCEPTION_FRAME*)jmp->Registration,
501                                  jmp->TryLevel, (void *)jmp->Ebp);
502     }
503
504     if (!retval)
505         retval = 1;
506
507     longjmp_set_regs( jmp, retval );
508 }
509
510 /*********************************************************************
511  *              _seh_longjmp_unwind (MSVCRT.@)
512  */
513 void __stdcall _seh_longjmp_unwind(struct MSVCRT___JUMP_BUFFER *jmp)
514 {
515     msvcrt_local_unwind2( (MSVCRT_EXCEPTION_FRAME *)jmp->Registration, jmp->TryLevel, (void *)jmp->Ebp );
516 }
517
518 #elif defined(__x86_64__)
519
520 /*******************************************************************
521  *              _setjmp (MSVCRT.@)
522  */
523 __ASM_GLOBAL_FUNC( MSVCRT__setjmp,
524                    "xorq %rdx,%rdx\n\t"  /* frame */
525                    "jmp " __ASM_NAME("MSVCRT__setjmpex") );
526
527 /*******************************************************************
528  *              _setjmpex (MSVCRT.@)
529  */
530 __ASM_GLOBAL_FUNC( MSVCRT__setjmpex,
531                    "movq %rdx,(%rcx)\n\t"          /* jmp_buf->Frame */
532                    "movq %rbx,0x8(%rcx)\n\t"       /* jmp_buf->Rbx */
533                    "leaq 0x8(%rsp),%rax\n\t"
534                    "movq %rax,0x10(%rcx)\n\t"      /* jmp_buf->Rsp */
535                    "movq %rbp,0x18(%rcx)\n\t"      /* jmp_buf->Rbp */
536                    "movq %rsi,0x20(%rcx)\n\t"      /* jmp_buf->Rsi */
537                    "movq %rdi,0x28(%rcx)\n\t"      /* jmp_buf->Rdi */
538                    "movq %r12,0x30(%rcx)\n\t"      /* jmp_buf->R12 */
539                    "movq %r13,0x38(%rcx)\n\t"      /* jmp_buf->R13 */
540                    "movq %r14,0x40(%rcx)\n\t"      /* jmp_buf->R14 */
541                    "movq %r15,0x48(%rcx)\n\t"      /* jmp_buf->R15 */
542                    "movq (%rsp),%rax\n\t"
543                    "movq %rax,0x50(%rcx)\n\t"      /* jmp_buf->Rip */
544                    "movdqa %xmm6,0x60(%rcx)\n\t"   /* jmp_buf->Xmm6 */
545                    "movdqa %xmm7,0x70(%rcx)\n\t"   /* jmp_buf->Xmm7 */
546                    "movdqa %xmm8,0x80(%rcx)\n\t"   /* jmp_buf->Xmm8 */
547                    "movdqa %xmm9,0x90(%rcx)\n\t"   /* jmp_buf->Xmm9 */
548                    "movdqa %xmm10,0xa0(%rcx)\n\t"  /* jmp_buf->Xmm10 */
549                    "movdqa %xmm11,0xb0(%rcx)\n\t"  /* jmp_buf->Xmm11 */
550                    "movdqa %xmm12,0xc0(%rcx)\n\t"  /* jmp_buf->Xmm12 */
551                    "movdqa %xmm13,0xd0(%rcx)\n\t"  /* jmp_buf->Xmm13 */
552                    "movdqa %xmm14,0xe0(%rcx)\n\t"  /* jmp_buf->Xmm14 */
553                    "movdqa %xmm15,0xf0(%rcx)\n\t"  /* jmp_buf->Xmm15 */
554                    "xorq %rax,%rax\n\t"
555                    "retq" );
556
557 #endif /* __x86_64__ */
558
559 static MSVCRT___sighandler_t sighandlers[MSVCRT_NSIG] = { MSVCRT_SIG_DFL };
560
561 static BOOL WINAPI msvcrt_console_handler(DWORD ctrlType)
562 {
563     BOOL ret = FALSE;
564
565     switch (ctrlType)
566     {
567     case CTRL_C_EVENT:
568         if (sighandlers[MSVCRT_SIGINT])
569         {
570             if (sighandlers[MSVCRT_SIGINT] != MSVCRT_SIG_IGN)
571                 sighandlers[MSVCRT_SIGINT](MSVCRT_SIGINT);
572             ret = TRUE;
573         }
574         break;
575     }
576     return ret;
577 }
578
579 typedef void (*float_handler)(int, int);
580
581 /* The exception codes are actually NTSTATUS values */
582 static const struct
583 {
584     NTSTATUS status;
585     int signal;
586 } float_exception_map[] = {
587  { EXCEPTION_FLT_DENORMAL_OPERAND, MSVCRT__FPE_DENORMAL },
588  { EXCEPTION_FLT_DIVIDE_BY_ZERO, MSVCRT__FPE_ZERODIVIDE },
589  { EXCEPTION_FLT_INEXACT_RESULT, MSVCRT__FPE_INEXACT },
590  { EXCEPTION_FLT_INVALID_OPERATION, MSVCRT__FPE_INVALID },
591  { EXCEPTION_FLT_OVERFLOW, MSVCRT__FPE_OVERFLOW },
592  { EXCEPTION_FLT_STACK_CHECK, MSVCRT__FPE_STACKOVERFLOW },
593  { EXCEPTION_FLT_UNDERFLOW, MSVCRT__FPE_UNDERFLOW },
594 };
595
596 static LONG WINAPI msvcrt_exception_filter(struct _EXCEPTION_POINTERS *except)
597 {
598     LONG ret = EXCEPTION_CONTINUE_SEARCH;
599     MSVCRT___sighandler_t handler;
600
601     if (!except || !except->ExceptionRecord)
602         return EXCEPTION_CONTINUE_SEARCH;
603
604     switch (except->ExceptionRecord->ExceptionCode)
605     {
606     case EXCEPTION_ACCESS_VIOLATION:
607         if ((handler = sighandlers[MSVCRT_SIGSEGV]) != MSVCRT_SIG_DFL)
608         {
609             if (handler != MSVCRT_SIG_IGN)
610             {
611                 sighandlers[MSVCRT_SIGSEGV] = MSVCRT_SIG_DFL;
612                 handler(MSVCRT_SIGSEGV);
613             }
614             ret = EXCEPTION_CONTINUE_EXECUTION;
615         }
616         break;
617     /* According to msdn,
618      * the FPE signal handler takes as a second argument the type of
619      * floating point exception.
620      */
621     case EXCEPTION_FLT_DENORMAL_OPERAND:
622     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
623     case EXCEPTION_FLT_INEXACT_RESULT:
624     case EXCEPTION_FLT_INVALID_OPERATION:
625     case EXCEPTION_FLT_OVERFLOW:
626     case EXCEPTION_FLT_STACK_CHECK:
627     case EXCEPTION_FLT_UNDERFLOW:
628         if ((handler = sighandlers[MSVCRT_SIGFPE]) != MSVCRT_SIG_DFL)
629         {
630             if (handler != MSVCRT_SIG_IGN)
631             {
632                 unsigned int i;
633                 int float_signal = MSVCRT__FPE_INVALID;
634
635                 sighandlers[MSVCRT_SIGFPE] = MSVCRT_SIG_DFL;
636                 for (i = 0; i < sizeof(float_exception_map) /
637                          sizeof(float_exception_map[0]); i++)
638                 {
639                     if (float_exception_map[i].status ==
640                         except->ExceptionRecord->ExceptionCode)
641                     {
642                         float_signal = float_exception_map[i].signal;
643                         break;
644                     }
645                 }
646                 ((float_handler)handler)(MSVCRT_SIGFPE, float_signal);
647             }
648             ret = EXCEPTION_CONTINUE_EXECUTION;
649         }
650         break;
651     case EXCEPTION_ILLEGAL_INSTRUCTION:
652     case EXCEPTION_PRIV_INSTRUCTION:
653         if ((handler = sighandlers[MSVCRT_SIGILL]) != MSVCRT_SIG_DFL)
654         {
655             if (handler != MSVCRT_SIG_IGN)
656             {
657                 sighandlers[MSVCRT_SIGILL] = MSVCRT_SIG_DFL;
658                 handler(MSVCRT_SIGILL);
659             }
660             ret = EXCEPTION_CONTINUE_EXECUTION;
661         }
662         break;
663     }
664     return ret;
665 }
666
667 void msvcrt_init_signals(void)
668 {
669     SetConsoleCtrlHandler(msvcrt_console_handler, TRUE);
670     SetUnhandledExceptionFilter(msvcrt_exception_filter);
671 }
672
673 void msvcrt_free_signals(void)
674 {
675     SetConsoleCtrlHandler(msvcrt_console_handler, FALSE);
676     SetUnhandledExceptionFilter(NULL);
677 }
678
679 /*********************************************************************
680  *              signal (MSVCRT.@)
681  * Some signals may never be generated except through an explicit call to
682  * raise.
683  */
684 MSVCRT___sighandler_t CDECL MSVCRT_signal(int sig, MSVCRT___sighandler_t func)
685 {
686     MSVCRT___sighandler_t ret = MSVCRT_SIG_ERR;
687
688     TRACE("(%d, %p)\n", sig, func);
689
690     if (func == MSVCRT_SIG_ERR) return MSVCRT_SIG_ERR;
691
692     switch (sig)
693     {
694     /* Cases handled internally.  Note SIGTERM is never generated by Windows,
695      * so we effectively mask it.
696      */
697     case MSVCRT_SIGABRT:
698     case MSVCRT_SIGFPE:
699     case MSVCRT_SIGILL:
700     case MSVCRT_SIGSEGV:
701     case MSVCRT_SIGINT:
702     case MSVCRT_SIGTERM:
703     case MSVCRT_SIGBREAK:
704         ret = sighandlers[sig];
705         sighandlers[sig] = func;
706         break;
707     default:
708         ret = MSVCRT_SIG_ERR;
709     }
710     return ret;
711 }
712
713 /*********************************************************************
714  *              raise (MSVCRT.@)
715  */
716 int CDECL MSVCRT_raise(int sig)
717 {
718     MSVCRT___sighandler_t handler;
719
720     TRACE("(%d)\n", sig);
721
722     switch (sig)
723     {
724     case MSVCRT_SIGABRT:
725     case MSVCRT_SIGFPE:
726     case MSVCRT_SIGILL:
727     case MSVCRT_SIGSEGV:
728     case MSVCRT_SIGINT:
729     case MSVCRT_SIGTERM:
730     case MSVCRT_SIGBREAK:
731         handler = sighandlers[sig];
732         if (handler == MSVCRT_SIG_DFL) MSVCRT__exit(3);
733         if (handler != MSVCRT_SIG_IGN)
734         {
735             sighandlers[sig] = MSVCRT_SIG_DFL;
736             if (sig == MSVCRT_SIGFPE)
737                 ((float_handler)handler)(sig, MSVCRT__FPE_EXPLICITGEN);
738             else
739                 handler(sig);
740         }
741         break;
742     default:
743         return -1;
744     }
745     return 0;
746 }
747
748 /*********************************************************************
749  *              _XcptFilter (MSVCRT.@)
750  */
751 int CDECL _XcptFilter(NTSTATUS ex, PEXCEPTION_POINTERS ptr)
752 {
753     TRACE("(%08x,%p)\n", ex, ptr);
754     /* I assume ptr->ExceptionRecord->ExceptionCode is the same as ex */
755     return msvcrt_exception_filter(ptr);
756 }
757
758 /*********************************************************************
759  *              _abnormal_termination (MSVCRT.@)
760  */
761 int CDECL _abnormal_termination(void)
762 {
763   FIXME("(void)stub\n");
764   return 0;
765 }
766
767 /******************************************************************
768  *              MSVCRT___uncaught_exception
769  */
770 BOOL CDECL MSVCRT___uncaught_exception(void)
771 {
772     return FALSE;
773 }