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