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