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