Prefix signal definitions with MSVCRT_ to avoid conflicts with system
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * NOTES:
22  *
23  * See http://www.microsoft.com/msj/0197/exception/exception.htm,
24  * but don't believe all of it.
25  *
26  * FIXME: Incomplete support for nested exceptions/try block cleanup.
27  */
28
29 #include "config.h"
30 #include "wine/port.h"
31
32 #include <stdarg.h>
33
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winreg.h"
37 #include "winternl.h"
38 #include "wine/exception.h"
39 #include "msvcrt.h"
40 #include "excpt.h"
41 #include "wincon.h"
42 #include "msvcrt/float.h"
43 #include "wine/debug.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
46
47 /* VC++ extensions to Win32 SEH */
48 typedef struct _SCOPETABLE
49 {
50   int previousTryLevel;
51   int (*lpfnFilter)(PEXCEPTION_POINTERS);
52   int (*lpfnHandler)(void);
53 } SCOPETABLE, *PSCOPETABLE;
54
55 typedef struct _MSVCRT_EXCEPTION_FRAME
56 {
57   EXCEPTION_REGISTRATION_RECORD *prev;
58   void (*handler)(PEXCEPTION_RECORD, EXCEPTION_REGISTRATION_RECORD*,
59                   PCONTEXT, PEXCEPTION_RECORD);
60   PSCOPETABLE scopetable;
61   int trylevel;
62   int _ebp;
63   PEXCEPTION_POINTERS xpointers;
64 } MSVCRT_EXCEPTION_FRAME;
65
66 #define TRYLEVEL_END (-1) /* End of trylevel list */
67
68 #if defined(__GNUC__) && defined(__i386__)
69 inline static void call_finally_block( void *code_block, void *base_ptr )
70 {
71     __asm__ __volatile__ ("movl %1,%%ebp; call *%%eax" \
72                           : : "a" (code_block), "g" (base_ptr));
73 }
74
75 inline static DWORD call_filter( void *func, void *arg, void *ebp )
76 {
77     DWORD ret;
78     __asm__ __volatile__ ("pushl %%ebp; pushl %3; movl %2,%%ebp; call *%%eax; popl %%ebp; popl %%ebp"
79                           : "=a" (ret)
80                           : "0" (func), "r" (ebp), "r" (arg)
81                           : "ecx", "edx", "memory" );
82     return ret;
83 }
84 #endif
85
86 static DWORD MSVCRT_nested_handler(PEXCEPTION_RECORD rec,
87                                    EXCEPTION_REGISTRATION_RECORD* frame,
88                                    PCONTEXT context,
89                                    EXCEPTION_REGISTRATION_RECORD** dispatch)
90 {
91   if (rec->ExceptionFlags & 0x6)
92     return ExceptionContinueSearch;
93   *dispatch = frame;
94   return ExceptionCollidedUnwind;
95 }
96
97
98 /*********************************************************************
99  *              _EH_prolog (MSVCRT.@)
100  */
101 #ifdef __i386__
102 /* Provided for VC++ binary compatibility only */
103 __ASM_GLOBAL_FUNC(_EH_prolog,
104                   "pushl $-1\n\t"
105                   "pushl %eax\n\t"
106                   "pushl %fs:0\n\t"
107                   "movl  %esp, %fs:0\n\t"
108                   "movl  12(%esp), %eax\n\t"
109                   "movl  %ebp, 12(%esp)\n\t"
110                   "leal  12(%esp), %ebp\n\t"
111                   "pushl %eax\n\t"
112                   "ret");
113 #endif
114
115 /*******************************************************************
116  *              _global_unwind2 (MSVCRT.@)
117  */
118 void _global_unwind2(EXCEPTION_REGISTRATION_RECORD* frame)
119 {
120     TRACE("(%p)\n",frame);
121     RtlUnwind( frame, 0, 0, 0 );
122 }
123
124 /*******************************************************************
125  *              _local_unwind2 (MSVCRT.@)
126  */
127 void _local_unwind2(MSVCRT_EXCEPTION_FRAME* frame, int trylevel)
128 {
129   MSVCRT_EXCEPTION_FRAME *curframe = frame;
130   EXCEPTION_REGISTRATION_RECORD reg;
131
132   TRACE("(%p,%d,%d)\n",frame, frame->trylevel, trylevel);
133
134   /* Register a handler in case of a nested exception */
135   reg.Handler = (PEXCEPTION_HANDLER)MSVCRT_nested_handler;
136   reg.Prev = NtCurrentTeb()->Tib.ExceptionList;
137   __wine_push_frame(&reg);
138
139   while (frame->trylevel != TRYLEVEL_END && frame->trylevel != trylevel)
140   {
141     int curtrylevel = frame->scopetable[frame->trylevel].previousTryLevel;
142     curframe = frame;
143     curframe->trylevel = curtrylevel;
144     if (!frame->scopetable[curtrylevel].lpfnFilter)
145     {
146       ERR("__try block cleanup not implemented - expect crash!\n");
147       /* FIXME: Remove current frame, set ebp, call
148        * frame->scopetable[curtrylevel].lpfnHandler()
149        */
150     }
151   }
152   __wine_pop_frame(&reg);
153   TRACE("unwound OK\n");
154 }
155
156 /*********************************************************************
157  *              _except_handler2 (MSVCRT.@)
158  */
159 int _except_handler2(PEXCEPTION_RECORD rec,
160                      EXCEPTION_REGISTRATION_RECORD* frame,
161                      PCONTEXT context,
162                      EXCEPTION_REGISTRATION_RECORD** dispatcher)
163 {
164   FIXME("exception %lx flags=%lx at %p handler=%p %p %p stub\n",
165         rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
166         frame->Handler, context, dispatcher);
167   return ExceptionContinueSearch;
168 }
169
170 /*********************************************************************
171  *              _except_handler3 (MSVCRT.@)
172  */
173 int _except_handler3(PEXCEPTION_RECORD rec,
174                      MSVCRT_EXCEPTION_FRAME* frame,
175                      PCONTEXT context, void* dispatcher)
176 {
177 #if defined(__GNUC__) && defined(__i386__)
178   long retval;
179   int trylevel;
180   EXCEPTION_POINTERS exceptPtrs;
181   PSCOPETABLE pScopeTable;
182
183   TRACE("exception %lx flags=%lx at %p handler=%p %p %p semi-stub\n",
184         rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
185         frame->handler, context, dispatcher);
186
187   __asm__ __volatile__ ("cld");
188
189   if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
190   {
191     /* Unwinding the current frame */
192      _local_unwind2(frame, TRYLEVEL_END);
193     TRACE("unwound current frame, returning ExceptionContinueSearch\n");
194     return ExceptionContinueSearch;
195   }
196   else
197   {
198     /* Hunting for handler */
199     exceptPtrs.ExceptionRecord = rec;
200     exceptPtrs.ContextRecord = context;
201     *((DWORD *)frame-1) = (DWORD)&exceptPtrs;
202     trylevel = frame->trylevel;
203     pScopeTable = frame->scopetable;
204
205     while (trylevel != TRYLEVEL_END)
206     {
207       if (pScopeTable[trylevel].lpfnFilter)
208       {
209         TRACE("filter = %p\n", pScopeTable[trylevel].lpfnFilter);
210
211         retval = call_filter( pScopeTable[trylevel].lpfnFilter, &exceptPtrs, &frame->_ebp );
212
213         TRACE("filter returned %s\n", retval == EXCEPTION_CONTINUE_EXECUTION ?
214               "CONTINUE_EXECUTION" : retval == EXCEPTION_EXECUTE_HANDLER ?
215               "EXECUTE_HANDLER" : "CONTINUE_SEARCH");
216
217         if (retval == EXCEPTION_CONTINUE_EXECUTION)
218           return ExceptionContinueExecution;
219
220         if (retval == EXCEPTION_EXECUTE_HANDLER)
221         {
222           /* Unwind all higher frames, this one will handle the exception */
223           _global_unwind2((EXCEPTION_REGISTRATION_RECORD*)frame);
224           _local_unwind2(frame, trylevel);
225
226           /* Set our trylevel to the enclosing block, and call the __finally
227            * code, which won't return
228            */
229           frame->trylevel = pScopeTable->previousTryLevel;
230           TRACE("__finally block %p\n",pScopeTable[trylevel].lpfnHandler);
231           call_finally_block(pScopeTable[trylevel].lpfnHandler, &frame->_ebp);
232           ERR("Returned from __finally block - expect crash!\n");
233        }
234       }
235       trylevel = pScopeTable->previousTryLevel;
236     }
237   }
238 #else
239   TRACE("exception %lx flags=%lx at %p handler=%p %p %p stub\n",
240         rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
241         frame->handler, context, dispatcher);
242 #endif
243   TRACE("reached TRYLEVEL_END, returning ExceptionContinueSearch\n");
244   return ExceptionContinueSearch;
245 }
246
247 /*********************************************************************
248  *              _abnormal_termination (MSVCRT.@)
249  */
250 int _abnormal_termination(void)
251 {
252   FIXME("(void)stub\n");
253   return 0;
254 }
255
256 /*
257  * setjmp/longjmp implementation
258  */
259
260 #ifdef __i386__
261 #define MSVCRT_JMP_MAGIC 0x56433230 /* ID value for new jump structure */
262 typedef void (*MSVCRT_unwind_function)(const void*);
263
264 /*
265  * The signatures of the setjmp/longjmp functions do not match that
266  * declared in the setjmp header so they don't follow the regular naming
267  * convention to avoid conflicts.
268  */
269
270 /*******************************************************************
271  *              _setjmp (MSVCRT.@)
272  */
273 DEFINE_REGS_ENTRYPOINT( MSVCRT__setjmp, 4, 0 );
274 void WINAPI __regs_MSVCRT__setjmp(struct MSVCRT___JUMP_BUFFER *jmp, CONTEXT86* context)
275 {
276     TRACE("(%p)\n",jmp);
277     jmp->Ebp = context->Ebp;
278     jmp->Ebx = context->Ebx;
279     jmp->Edi = context->Edi;
280     jmp->Esi = context->Esi;
281     jmp->Esp = context->Esp;
282     jmp->Eip = context->Eip;
283     jmp->Registration = (unsigned long)NtCurrentTeb()->Tib.ExceptionList;
284     if (jmp->Registration == TRYLEVEL_END)
285         jmp->TryLevel = TRYLEVEL_END;
286     else
287         jmp->TryLevel = ((MSVCRT_EXCEPTION_FRAME*)jmp->Registration)->trylevel;
288     TRACE("returning 0\n");
289     context->Eax=0;
290 }
291
292 /*******************************************************************
293  *              _setjmp3 (MSVCRT.@)
294  */
295 DEFINE_REGS_ENTRYPOINT( MSVCRT__setjmp3, 8, 0 );
296 void WINAPI __regs_MSVCRT__setjmp3(struct MSVCRT___JUMP_BUFFER *jmp, int nb_args, CONTEXT86* context)
297 {
298     TRACE("(%p,%d)\n",jmp,nb_args);
299     jmp->Ebp = context->Ebp;
300     jmp->Ebx = context->Ebx;
301     jmp->Edi = context->Edi;
302     jmp->Esi = context->Esi;
303     jmp->Esp = context->Esp;
304     jmp->Eip = context->Eip;
305     jmp->Cookie = MSVCRT_JMP_MAGIC;
306     jmp->UnwindFunc = 0;
307     jmp->Registration = (unsigned long)NtCurrentTeb()->Tib.ExceptionList;
308     if (jmp->Registration == TRYLEVEL_END)
309     {
310         jmp->TryLevel = TRYLEVEL_END;
311     }
312     else
313     {
314         void **args = ((void**)context->Esp)+2;
315
316         if (nb_args > 0) jmp->UnwindFunc = (unsigned long)*args++;
317         if (nb_args > 1) jmp->TryLevel = (unsigned long)*args++;
318         else jmp->TryLevel = ((MSVCRT_EXCEPTION_FRAME*)jmp->Registration)->trylevel;
319         if (nb_args > 2)
320         {
321             size_t size = (nb_args - 2) * sizeof(DWORD);
322             memcpy( jmp->UnwindData, args, min( size, sizeof(jmp->UnwindData) ));
323         }
324     }
325     TRACE("returning 0\n");
326     context->Eax = 0;
327 }
328
329 /*********************************************************************
330  *              longjmp (MSVCRT.@)
331  */
332 DEFINE_REGS_ENTRYPOINT( MSVCRT_longjmp, 8, 0 );
333 void WINAPI __regs_MSVCRT_longjmp(struct MSVCRT___JUMP_BUFFER *jmp, int retval, CONTEXT86* context)
334 {
335     unsigned long cur_frame = 0;
336
337     TRACE("(%p,%d)\n", jmp, retval);
338
339     cur_frame=(unsigned long)NtCurrentTeb()->Tib.ExceptionList;
340     TRACE("cur_frame=%lx\n",cur_frame);
341
342     if (cur_frame != jmp->Registration)
343         _global_unwind2((EXCEPTION_REGISTRATION_RECORD*)jmp->Registration);
344
345     if (jmp->Registration)
346     {
347         if (!IsBadReadPtr(&jmp->Cookie, sizeof(long)) &&
348             jmp->Cookie == MSVCRT_JMP_MAGIC && jmp->UnwindFunc)
349         {
350             MSVCRT_unwind_function unwind_func;
351
352             unwind_func=(MSVCRT_unwind_function)jmp->UnwindFunc;
353             unwind_func(jmp);
354         }
355         else
356             _local_unwind2((MSVCRT_EXCEPTION_FRAME*)jmp->Registration,
357                            jmp->TryLevel);
358     }
359
360     if (!retval)
361         retval = 1;
362
363     TRACE("Jump to %lx returning %d\n",jmp->Eip,retval);
364     context->Ebp = jmp->Ebp;
365     context->Ebx = jmp->Ebx;
366     context->Edi = jmp->Edi;
367     context->Esi = jmp->Esi;
368     context->Esp = jmp->Esp;
369     context->Eip = jmp->Eip;
370     context->Eax = retval;
371 }
372
373 /*********************************************************************
374  *              _seh_longjmp_unwind (MSVCRT.@)
375  */
376 void __stdcall _seh_longjmp_unwind(struct MSVCRT___JUMP_BUFFER *jmp)
377 {
378     _local_unwind2( (MSVCRT_EXCEPTION_FRAME *)jmp->Registration, jmp->TryLevel );
379 }
380 #endif /* i386 */
381
382 static MSVCRT___sighandler_t sighandlers[MSVCRT_NSIG] = { MSVCRT_SIG_DFL };
383
384 static BOOL WINAPI msvcrt_console_handler(DWORD ctrlType)
385 {
386     BOOL ret = FALSE;
387
388     switch (ctrlType)
389     {
390     case CTRL_C_EVENT:
391         if (sighandlers[MSVCRT_SIGINT])
392         {
393             if (sighandlers[MSVCRT_SIGINT] != MSVCRT_SIG_IGN)
394                 sighandlers[MSVCRT_SIGINT](MSVCRT_SIGINT);
395             ret = TRUE;
396         }
397         break;
398     }
399     return ret;
400 }
401
402 typedef void (*float_handler)(int, int);
403
404 /* The exception codes are actually NTSTATUS values */
405 struct
406 {
407     NTSTATUS status;
408     int signal;
409 } float_exception_map[] = {
410  { EXCEPTION_FLT_DENORMAL_OPERAND, _FPE_DENORMAL },
411  { EXCEPTION_FLT_DIVIDE_BY_ZERO, _FPE_ZERODIVIDE },
412  { EXCEPTION_FLT_INEXACT_RESULT, _FPE_INEXACT },
413  { EXCEPTION_FLT_INVALID_OPERATION, _FPE_INVALID },
414  { EXCEPTION_FLT_OVERFLOW, _FPE_OVERFLOW },
415  { EXCEPTION_FLT_STACK_CHECK, _FPE_STACKOVERFLOW },
416  { EXCEPTION_FLT_UNDERFLOW, _FPE_UNDERFLOW },
417 };
418
419 static LONG WINAPI msvcrt_exception_filter(struct _EXCEPTION_POINTERS *except)
420 {
421     LONG ret = EXCEPTION_CONTINUE_SEARCH;
422
423     if (!except || !except->ExceptionRecord)
424         return EXCEPTION_CONTINUE_SEARCH;
425
426     switch (except->ExceptionRecord->ExceptionCode)
427     {
428     case EXCEPTION_ACCESS_VIOLATION:
429         if (sighandlers[MSVCRT_SIGSEGV])
430         {
431             if (sighandlers[MSVCRT_SIGSEGV] != MSVCRT_SIG_IGN)
432                 sighandlers[MSVCRT_SIGSEGV](MSVCRT_SIGSEGV);
433             ret = EXCEPTION_CONTINUE_EXECUTION;
434         }
435         break;
436     /* According to
437      * http://msdn.microsoft.com/library/en-us/vclib/html/_CRT_signal.asp
438      * the FPE signal handler takes as a second argument the type of
439      * floating point exception.
440      */
441     case EXCEPTION_FLT_DENORMAL_OPERAND:
442     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
443     case EXCEPTION_FLT_INEXACT_RESULT:
444     case EXCEPTION_FLT_INVALID_OPERATION:
445     case EXCEPTION_FLT_OVERFLOW:
446     case EXCEPTION_FLT_STACK_CHECK:
447     case EXCEPTION_FLT_UNDERFLOW:
448         if (sighandlers[MSVCRT_SIGFPE])
449         {
450             if (sighandlers[MSVCRT_SIGFPE] != MSVCRT_SIG_IGN)
451             {
452                 int i, float_signal = _FPE_INVALID;
453
454                 float_handler handler = (float_handler)sighandlers[MSVCRT_SIGFPE];
455                 for (i = 0; i < sizeof(float_exception_map) /
456                  sizeof(float_exception_map[0]); i++)
457                     if (float_exception_map[i].status ==
458                      except->ExceptionRecord->ExceptionCode)
459                     {
460                         float_signal = float_exception_map[i].signal;
461                         break;
462                     }
463                 handler(MSVCRT_SIGFPE, float_signal);
464             }
465             ret = EXCEPTION_CONTINUE_EXECUTION;
466         }
467         break;
468     case EXCEPTION_ILLEGAL_INSTRUCTION:
469         if (sighandlers[MSVCRT_SIGILL])
470         {
471             if (sighandlers[MSVCRT_SIGILL] != MSVCRT_SIG_IGN)
472                 sighandlers[MSVCRT_SIGILL](MSVCRT_SIGILL);
473             ret = EXCEPTION_CONTINUE_EXECUTION;
474         }
475         break;
476     }
477     return ret;
478 }
479
480 void msvcrt_init_signals(void)
481 {
482     SetConsoleCtrlHandler(msvcrt_console_handler, TRUE);
483     SetUnhandledExceptionFilter(msvcrt_exception_filter);
484 }
485
486 void msvcrt_free_signals(void)
487 {
488     SetConsoleCtrlHandler(msvcrt_console_handler, FALSE);
489     SetUnhandledExceptionFilter(NULL);
490 }
491
492 /*********************************************************************
493  *              signal (MSVCRT.@)
494  * MS signal handling is described here:
495  * http://msdn.microsoft.com/library/en-us/vclib/html/_CRT_signal.asp
496  * Some signals may never be generated except through an explicit call to
497  * raise.
498  */
499 MSVCRT___sighandler_t MSVCRT_signal(int sig, MSVCRT___sighandler_t func)
500 {
501     MSVCRT___sighandler_t ret = MSVCRT_SIG_ERR;
502
503     TRACE("(%d, %p)\n", sig, func);
504
505     if (func == MSVCRT_SIG_ERR) return MSVCRT_SIG_ERR;
506
507     switch (sig)
508     {
509     /* Cases handled internally.  Note SIGTERM is never generated by Windows,
510      * so we effectively mask it.
511      */
512     case MSVCRT_SIGABRT:
513     case MSVCRT_SIGFPE:
514     case MSVCRT_SIGILL:
515     case MSVCRT_SIGSEGV:
516     case MSVCRT_SIGINT:
517     case MSVCRT_SIGTERM:
518         ret = sighandlers[sig];
519         sighandlers[sig] = func;
520         break;
521     default:
522         ret = MSVCRT_SIG_ERR;
523     }
524     return ret;
525 }
526
527 /*********************************************************************
528  *              _XcptFilter (MSVCRT.@)
529  */
530 int _XcptFilter(NTSTATUS ex, PEXCEPTION_POINTERS ptr)
531 {
532     TRACE("(%ld,%p)\n", ex, ptr);
533     /* I assume ptr->ExceptionRecord->ExceptionCode is the same as ex */
534     return msvcrt_exception_filter(ptr);
535 }