ole32: Remove some assertions in the stuctured storage code by
[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  * 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(seh);
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 CDECL _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 CDECL _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 CDECL _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 CDECL _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 CDECL _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 /* define an entrypoint for setjmp/setjmp3 that stores the registers in the jmp buf */
265 /* and then jumps to the C backend function */
266 #define DEFINE_SETJMP_ENTRYPOINT(name) \
267     __ASM_GLOBAL_FUNC( name, \
268                        "movl 4(%esp),%ecx\n\t"   /* jmp_buf */      \
269                        "movl %ebp,0(%ecx)\n\t"   /* jmp_buf.Ebp */  \
270                        "movl %ebx,4(%ecx)\n\t"   /* jmp_buf.Ebx */  \
271                        "movl %edi,8(%ecx)\n\t"   /* jmp_buf.Edi */  \
272                        "movl %esi,12(%ecx)\n\t"  /* jmp_buf.Esi */  \
273                        "movl %esp,16(%ecx)\n\t"  /* jmp_buf.Esp */  \
274                        "movl 0(%esp),%eax\n\t"                      \
275                        "movl %eax,20(%ecx)\n\t"  /* jmp_buf.Eip */  \
276                        "jmp " __ASM_NAME("__regs_") # name )
277
278 /* restore the registers from the jmp buf upon longjmp */
279 extern void DECLSPEC_NORETURN longjmp_set_regs( struct MSVCRT___JUMP_BUFFER *jmp, int retval );
280 __ASM_GLOBAL_FUNC( longjmp_set_regs,
281                    "movl 4(%esp),%ecx\n\t"   /* jmp_buf */
282                    "movl 8(%esp),%eax\n\t"   /* retval */
283                    "movl 0(%ecx),%ebp\n\t"   /* jmp_buf.Ebp */
284                    "movl 4(%ecx),%ebx\n\t"   /* jmp_buf.Ebx */
285                    "movl 8(%ecx),%edi\n\t"   /* jmp_buf.Edi */
286                    "movl 12(%ecx),%esi\n\t"  /* jmp_buf.Esi */
287                    "movl 16(%ecx),%esp\n\t"  /* jmp_buf.Esp */
288                    "addl $4,%esp\n\t"        /* get rid of return address */
289                    "jmp *20(%ecx)\n\t"       /* jmp_buf.Eip */ );
290
291 /*
292  * The signatures of the setjmp/longjmp functions do not match that
293  * declared in the setjmp header so they don't follow the regular naming
294  * convention to avoid conflicts.
295  */
296
297 /*******************************************************************
298  *              _setjmp (MSVCRT.@)
299  */
300 DEFINE_SETJMP_ENTRYPOINT(MSVCRT__setjmp);
301 int CDECL __regs_MSVCRT__setjmp(struct MSVCRT___JUMP_BUFFER *jmp)
302 {
303     jmp->Registration = (unsigned long)NtCurrentTeb()->Tib.ExceptionList;
304     if (jmp->Registration == TRYLEVEL_END)
305         jmp->TryLevel = TRYLEVEL_END;
306     else
307         jmp->TryLevel = ((MSVCRT_EXCEPTION_FRAME*)jmp->Registration)->trylevel;
308
309     TRACE("buf=%p ebx=%08lx esi=%08lx edi=%08lx ebp=%08lx esp=%08lx eip=%08lx frame=%08lx\n",
310           jmp, jmp->Ebx, jmp->Esi, jmp->Edi, jmp->Ebp, jmp->Esp, jmp->Eip, jmp->Registration );
311     return 0;
312 }
313
314 /*******************************************************************
315  *              _setjmp3 (MSVCRT.@)
316  */
317 DEFINE_SETJMP_ENTRYPOINT( MSVCRT__setjmp3 );
318 int CDECL __regs_MSVCRT__setjmp3(struct MSVCRT___JUMP_BUFFER *jmp, int nb_args, ...)
319 {
320     jmp->Cookie = MSVCRT_JMP_MAGIC;
321     jmp->UnwindFunc = 0;
322     jmp->Registration = (unsigned long)NtCurrentTeb()->Tib.ExceptionList;
323     if (jmp->Registration == TRYLEVEL_END)
324     {
325         jmp->TryLevel = TRYLEVEL_END;
326     }
327     else
328     {
329         int i;
330         va_list args;
331
332         va_start( args, nb_args );
333         if (nb_args > 0) jmp->UnwindFunc = va_arg( args, unsigned long );
334         if (nb_args > 1) jmp->TryLevel = va_arg( args, unsigned long );
335         else jmp->TryLevel = ((MSVCRT_EXCEPTION_FRAME*)jmp->Registration)->trylevel;
336         for (i = 0; i < 6 && i < nb_args - 2; i++)
337             jmp->UnwindData[i] = va_arg( args, unsigned long );
338         va_end( args );
339     }
340
341     TRACE("buf=%p ebx=%08lx esi=%08lx edi=%08lx ebp=%08lx esp=%08lx eip=%08lx frame=%08lx\n",
342           jmp, jmp->Ebx, jmp->Esi, jmp->Edi, jmp->Ebp, jmp->Esp, jmp->Eip, jmp->Registration );
343     return 0;
344 }
345
346 /*********************************************************************
347  *              longjmp (MSVCRT.@)
348  */
349 int CDECL MSVCRT_longjmp(struct MSVCRT___JUMP_BUFFER *jmp, int retval)
350 {
351     unsigned long cur_frame = 0;
352
353     TRACE("buf=%p ebx=%08lx esi=%08lx edi=%08lx ebp=%08lx esp=%08lx eip=%08lx frame=%08lx retval=%08x\n",
354           jmp, jmp->Ebx, jmp->Esi, jmp->Edi, jmp->Ebp, jmp->Esp, jmp->Eip, jmp->Registration, retval );
355
356     cur_frame=(unsigned long)NtCurrentTeb()->Tib.ExceptionList;
357     TRACE("cur_frame=%lx\n",cur_frame);
358
359     if (cur_frame != jmp->Registration)
360         _global_unwind2((EXCEPTION_REGISTRATION_RECORD*)jmp->Registration);
361
362     if (jmp->Registration)
363     {
364         if (!IsBadReadPtr(&jmp->Cookie, sizeof(long)) &&
365             jmp->Cookie == MSVCRT_JMP_MAGIC && jmp->UnwindFunc)
366         {
367             MSVCRT_unwind_function unwind_func;
368
369             unwind_func=(MSVCRT_unwind_function)jmp->UnwindFunc;
370             unwind_func(jmp);
371         }
372         else
373             _local_unwind2((MSVCRT_EXCEPTION_FRAME*)jmp->Registration,
374                            jmp->TryLevel);
375     }
376
377     if (!retval)
378         retval = 1;
379
380     longjmp_set_regs( jmp, retval );
381 }
382
383 /*********************************************************************
384  *              _seh_longjmp_unwind (MSVCRT.@)
385  */
386 void __stdcall _seh_longjmp_unwind(struct MSVCRT___JUMP_BUFFER *jmp)
387 {
388     _local_unwind2( (MSVCRT_EXCEPTION_FRAME *)jmp->Registration, jmp->TryLevel );
389 }
390 #endif /* i386 */
391
392 static MSVCRT___sighandler_t sighandlers[MSVCRT_NSIG] = { MSVCRT_SIG_DFL };
393
394 static BOOL WINAPI msvcrt_console_handler(DWORD ctrlType)
395 {
396     BOOL ret = FALSE;
397
398     switch (ctrlType)
399     {
400     case CTRL_C_EVENT:
401         if (sighandlers[MSVCRT_SIGINT])
402         {
403             if (sighandlers[MSVCRT_SIGINT] != MSVCRT_SIG_IGN)
404                 sighandlers[MSVCRT_SIGINT](MSVCRT_SIGINT);
405             ret = TRUE;
406         }
407         break;
408     }
409     return ret;
410 }
411
412 typedef void (*float_handler)(int, int);
413
414 /* The exception codes are actually NTSTATUS values */
415 struct
416 {
417     NTSTATUS status;
418     int signal;
419 } float_exception_map[] = {
420  { EXCEPTION_FLT_DENORMAL_OPERAND, _FPE_DENORMAL },
421  { EXCEPTION_FLT_DIVIDE_BY_ZERO, _FPE_ZERODIVIDE },
422  { EXCEPTION_FLT_INEXACT_RESULT, _FPE_INEXACT },
423  { EXCEPTION_FLT_INVALID_OPERATION, _FPE_INVALID },
424  { EXCEPTION_FLT_OVERFLOW, _FPE_OVERFLOW },
425  { EXCEPTION_FLT_STACK_CHECK, _FPE_STACKOVERFLOW },
426  { EXCEPTION_FLT_UNDERFLOW, _FPE_UNDERFLOW },
427 };
428
429 static LONG WINAPI msvcrt_exception_filter(struct _EXCEPTION_POINTERS *except)
430 {
431     LONG ret = EXCEPTION_CONTINUE_SEARCH;
432
433     if (!except || !except->ExceptionRecord)
434         return EXCEPTION_CONTINUE_SEARCH;
435
436     switch (except->ExceptionRecord->ExceptionCode)
437     {
438     case EXCEPTION_ACCESS_VIOLATION:
439         if (sighandlers[MSVCRT_SIGSEGV])
440         {
441             if (sighandlers[MSVCRT_SIGSEGV] != MSVCRT_SIG_IGN)
442                 sighandlers[MSVCRT_SIGSEGV](MSVCRT_SIGSEGV);
443             ret = EXCEPTION_CONTINUE_EXECUTION;
444         }
445         break;
446     /* According to
447      * http://msdn.microsoft.com/library/en-us/vclib/html/_CRT_signal.asp
448      * the FPE signal handler takes as a second argument the type of
449      * floating point exception.
450      */
451     case EXCEPTION_FLT_DENORMAL_OPERAND:
452     case EXCEPTION_FLT_DIVIDE_BY_ZERO:
453     case EXCEPTION_FLT_INEXACT_RESULT:
454     case EXCEPTION_FLT_INVALID_OPERATION:
455     case EXCEPTION_FLT_OVERFLOW:
456     case EXCEPTION_FLT_STACK_CHECK:
457     case EXCEPTION_FLT_UNDERFLOW:
458         if (sighandlers[MSVCRT_SIGFPE])
459         {
460             if (sighandlers[MSVCRT_SIGFPE] != MSVCRT_SIG_IGN)
461             {
462                 int i, float_signal = _FPE_INVALID;
463
464                 float_handler handler = (float_handler)sighandlers[MSVCRT_SIGFPE];
465                 for (i = 0; i < sizeof(float_exception_map) /
466                  sizeof(float_exception_map[0]); i++)
467                     if (float_exception_map[i].status ==
468                      except->ExceptionRecord->ExceptionCode)
469                     {
470                         float_signal = float_exception_map[i].signal;
471                         break;
472                     }
473                 handler(MSVCRT_SIGFPE, float_signal);
474             }
475             ret = EXCEPTION_CONTINUE_EXECUTION;
476         }
477         break;
478     case EXCEPTION_ILLEGAL_INSTRUCTION:
479         if (sighandlers[MSVCRT_SIGILL])
480         {
481             if (sighandlers[MSVCRT_SIGILL] != MSVCRT_SIG_IGN)
482                 sighandlers[MSVCRT_SIGILL](MSVCRT_SIGILL);
483             ret = EXCEPTION_CONTINUE_EXECUTION;
484         }
485         break;
486     }
487     return ret;
488 }
489
490 void msvcrt_init_signals(void)
491 {
492     SetConsoleCtrlHandler(msvcrt_console_handler, TRUE);
493     SetUnhandledExceptionFilter(msvcrt_exception_filter);
494 }
495
496 void msvcrt_free_signals(void)
497 {
498     SetConsoleCtrlHandler(msvcrt_console_handler, FALSE);
499     SetUnhandledExceptionFilter(NULL);
500 }
501
502 /*********************************************************************
503  *              signal (MSVCRT.@)
504  * MS signal handling is described here:
505  * http://msdn.microsoft.com/library/en-us/vclib/html/_CRT_signal.asp
506  * Some signals may never be generated except through an explicit call to
507  * raise.
508  */
509 MSVCRT___sighandler_t CDECL MSVCRT_signal(int sig, MSVCRT___sighandler_t func)
510 {
511     MSVCRT___sighandler_t ret = MSVCRT_SIG_ERR;
512
513     TRACE("(%d, %p)\n", sig, func);
514
515     if (func == MSVCRT_SIG_ERR) return MSVCRT_SIG_ERR;
516
517     switch (sig)
518     {
519     /* Cases handled internally.  Note SIGTERM is never generated by Windows,
520      * so we effectively mask it.
521      */
522     case MSVCRT_SIGABRT:
523     case MSVCRT_SIGFPE:
524     case MSVCRT_SIGILL:
525     case MSVCRT_SIGSEGV:
526     case MSVCRT_SIGINT:
527     case MSVCRT_SIGTERM:
528         ret = sighandlers[sig];
529         sighandlers[sig] = func;
530         break;
531     default:
532         ret = MSVCRT_SIG_ERR;
533     }
534     return ret;
535 }
536
537 /*********************************************************************
538  *              _XcptFilter (MSVCRT.@)
539  */
540 int CDECL _XcptFilter(NTSTATUS ex, PEXCEPTION_POINTERS ptr)
541 {
542     TRACE("(%08lx,%p)\n", ex, ptr);
543     /* I assume ptr->ExceptionRecord->ExceptionCode is the same as ex */
544     return msvcrt_exception_filter(ptr);
545 }