Use RTL_CRITICAL_SECTION instead of CRITICAL_SECTION.
[wine] / dlls / ntdll / exception.c
1 /*
2  * NT exception handling routines
3  *
4  * Copyright 1999 Turchanov Sergey
5  * Copyright 1999 Alexandre Julliard
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
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <signal.h>
27 #include <stdarg.h>
28
29 #include "ntstatus.h"
30 #include "windef.h"
31 #include "winternl.h"
32 #include "wine/exception.h"
33 #include "wine/server.h"
34 #include "wine/list.h"
35 #include "wine/debug.h"
36 #include "excpt.h"
37 #include "ntdll_misc.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(seh);
40
41 /* Exception record for handling exceptions happening inside exception handlers */
42 typedef struct
43 {
44     EXCEPTION_REGISTRATION_RECORD frame;
45     EXCEPTION_REGISTRATION_RECORD *prevFrame;
46 } EXC_NESTED_FRAME;
47
48 typedef struct
49 {
50     struct list                 entry;
51     PVECTORED_EXCEPTION_HANDLER func;
52 } VECTORED_HANDLER;
53
54 static struct list vectored_handlers = LIST_INIT(vectored_handlers);
55
56 static RTL_CRITICAL_SECTION vectored_handlers_section;
57 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
58 {
59     0, 0, &vectored_handlers_section,
60     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
61       0, 0, { 0, (DWORD)(__FILE__ ": vectored_handlers_section") }
62 };
63 static RTL_CRITICAL_SECTION vectored_handlers_section = { &critsect_debug, -1, 0, 0, 0, 0 };
64
65 #ifdef __i386__
66 # define GET_IP(context) ((LPVOID)(context)->Eip)
67 #elif defined(__sparc__)
68 # define GET_IP(context) ((LPVOID)(context)->pc)
69 #elif defined(__powerpc__)
70 # define GET_IP(context) ((LPVOID)(context)->Iar)
71 #elif defined(__ALPHA__)
72 # define GET_IP(context) ((LPVOID)(context)->Fir)
73 #else
74 # error You must define GET_IP for this CPU
75 #endif
76
77
78 /*******************************************************************
79  *         EXC_RaiseHandler
80  *
81  * Handler for exceptions happening inside a handler.
82  */
83 static DWORD EXC_RaiseHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
84                                CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
85 {
86     if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
87         return ExceptionContinueSearch;
88     /* We shouldn't get here so we store faulty frame in dispatcher */
89     *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
90     return ExceptionNestedException;
91 }
92
93
94 /*******************************************************************
95  *         EXC_UnwindHandler
96  *
97  * Handler for exceptions happening inside an unwind handler.
98  */
99 static DWORD EXC_UnwindHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
100                                 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
101 {
102     if (!(rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))
103         return ExceptionContinueSearch;
104     /* We shouldn't get here so we store faulty frame in dispatcher */
105     *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
106     return ExceptionCollidedUnwind;
107 }
108
109
110 /*******************************************************************
111  *         EXC_CallHandler
112  *
113  * Call an exception handler, setting up an exception frame to catch exceptions
114  * happening during the handler execution.
115  * Please do not change the first 4 parameters order in any way - some exceptions handlers
116  * rely on Base Pointer (EBP) to have a fixed position related to the exception frame
117  */
118 static DWORD EXC_CallHandler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
119                               CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher,
120                               PEXCEPTION_HANDLER handler, PEXCEPTION_HANDLER nested_handler)
121 {
122     EXC_NESTED_FRAME newframe;
123     DWORD ret;
124
125     newframe.frame.Handler = nested_handler;
126     newframe.prevFrame     = frame;
127     __wine_push_frame( &newframe.frame );
128     TRACE( "calling handler at %p code=%lx flags=%lx\n",
129            handler, record->ExceptionCode, record->ExceptionFlags );
130     ret = handler( record, frame, context, dispatcher );
131     TRACE( "handler returned %lx\n", ret );
132     __wine_pop_frame( &newframe.frame );
133     return ret;
134 }
135
136
137 /**********************************************************************
138  *           send_debug_event
139  *
140  * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
141  */
142 static int send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
143 {
144     int ret;
145     HANDLE handle = 0;
146
147     if (!NtCurrentTeb()->Peb->BeingDebugged) return 0;  /* no debugger present */
148
149     SERVER_START_REQ( queue_exception_event )
150     {
151         req->first   = first_chance;
152         wine_server_add_data( req, context, sizeof(*context) );
153         wine_server_add_data( req, rec, sizeof(*rec) );
154         if (!wine_server_call( req )) handle = reply->handle;
155     }
156     SERVER_END_REQ;
157     if (!handle) return 0;
158
159     /* No need to wait on the handle since the process gets suspended
160      * once the event is passed to the debugger, so when we get back
161      * here the event has been continued already.
162      */
163     SERVER_START_REQ( get_exception_status )
164     {
165         req->handle = handle;
166         wine_server_set_reply( req, context, sizeof(*context) );
167         wine_server_call( req );
168         ret = reply->status;
169     }
170     SERVER_END_REQ;
171     NtClose( handle );
172     return ret;
173 }
174
175
176 /**********************************************************************
177  *           call_vectored_handlers
178  *
179  * Call the vectored handlers chain.
180  */
181 static LONG call_vectored_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
182 {
183     struct list *ptr;
184     LONG ret = EXCEPTION_CONTINUE_SEARCH;
185     EXCEPTION_POINTERS except_ptrs;
186
187     except_ptrs.ExceptionRecord = rec;
188     except_ptrs.ContextRecord = context;
189
190     RtlEnterCriticalSection( &vectored_handlers_section );
191     LIST_FOR_EACH( ptr, &vectored_handlers )
192     {
193         VECTORED_HANDLER *handler = LIST_ENTRY( ptr, VECTORED_HANDLER, entry );
194         ret = handler->func( &except_ptrs );
195         if (ret == EXCEPTION_CONTINUE_EXECUTION) break;
196     }
197     RtlLeaveCriticalSection( &vectored_handlers_section );
198     return ret;
199 }
200
201
202 /*******************************************************************
203  *         EXC_DefaultHandling
204  *
205  * Default handling for exceptions. Called when we didn't find a suitable handler.
206  */
207 static void EXC_DefaultHandling( EXCEPTION_RECORD *rec, CONTEXT *context )
208 {
209     if (send_debug_event( rec, FALSE, context ) == DBG_CONTINUE) return;  /* continue execution */
210
211     if (rec->ExceptionFlags & EH_STACK_INVALID)
212         ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
213     else if (rec->ExceptionCode == EXCEPTION_NONCONTINUABLE_EXCEPTION)
214         ERR("Process attempted to continue execution after noncontinuable exception.\n");
215     else
216         ERR("Unhandled exception code %lx flags %lx addr %p\n",
217             rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
218     NtTerminateProcess( NtCurrentProcess(), 1 );
219 }
220
221
222 /***********************************************************************
223  *              RtlRaiseException (NTDLL.@)
224  */
225 void WINAPI __regs_RtlRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context )
226 {
227     EXCEPTION_REGISTRATION_RECORD *frame, *dispatch, *nested_frame;
228     EXCEPTION_RECORD newrec;
229     DWORD res, c;
230
231     TRACE( "code=%lx flags=%lx addr=%p\n", rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
232     for (c=0; c<rec->NumberParameters; c++) TRACE(" info[%ld]=%08lx\n", c, rec->ExceptionInformation[c]);
233     if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
234     {
235         if (HIWORD(rec->ExceptionInformation[1]))
236             MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
237                    rec->ExceptionAddress,
238                    (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
239         else
240             MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
241                    rec->ExceptionAddress,
242                    (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
243     }
244 #ifdef __i386__
245     else
246     {
247         TRACE(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
248               context->Eax, context->Ebx, context->Ecx,
249               context->Edx, context->Esi, context->Edi );
250         TRACE(" ebp=%08lx esp=%08lx cs=%04lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
251               context->Ebp, context->Esp, context->SegCs, context->SegDs,
252               context->SegEs, context->SegFs, context->SegGs, context->EFlags );
253     }
254 #endif
255
256     if (send_debug_event( rec, TRUE, context ) == DBG_CONTINUE) return;  /* continue execution */
257
258     if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION) return;
259
260     frame = NtCurrentTeb()->Tib.ExceptionList;
261     nested_frame = NULL;
262     while (frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL)
263     {
264         /* Check frame address */
265         if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
266             ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
267             (ULONG_PTR)frame & 3)
268         {
269             rec->ExceptionFlags |= EH_STACK_INVALID;
270             break;
271         }
272
273         /* Call handler */
274         res = EXC_CallHandler( rec, frame, context, &dispatch, frame->Handler, EXC_RaiseHandler );
275         if (frame == nested_frame)
276         {
277             /* no longer nested */
278             nested_frame = NULL;
279             rec->ExceptionFlags &= ~EH_NESTED_CALL;
280         }
281
282         switch(res)
283         {
284         case ExceptionContinueExecution:
285             if (!(rec->ExceptionFlags & EH_NONCONTINUABLE)) return;
286             newrec.ExceptionCode    = STATUS_NONCONTINUABLE_EXCEPTION;
287             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
288             newrec.ExceptionRecord  = rec;
289             newrec.NumberParameters = 0;
290             RtlRaiseException( &newrec );  /* never returns */
291             break;
292         case ExceptionContinueSearch:
293             break;
294         case ExceptionNestedException:
295             if (nested_frame < dispatch) nested_frame = dispatch;
296             rec->ExceptionFlags |= EH_NESTED_CALL;
297             break;
298         default:
299             newrec.ExceptionCode    = STATUS_INVALID_DISPOSITION;
300             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
301             newrec.ExceptionRecord  = rec;
302             newrec.NumberParameters = 0;
303             RtlRaiseException( &newrec );  /* never returns */
304             break;
305         }
306         frame = frame->Prev;
307     }
308     EXC_DefaultHandling( rec, context );
309 }
310
311 /**********************************************************************/
312
313 #ifdef DEFINE_REGS_ENTRYPOINT
314 DEFINE_REGS_ENTRYPOINT( RtlRaiseException, 4, 4 );
315 #else
316 void WINAPI RtlRaiseException( EXCEPTION_RECORD *rec )
317 {
318     CONTEXT context;
319     memset( &context, 0, sizeof(context) );
320     __regs_RtlRaiseException( rec, &context );
321 }
322 #endif
323
324
325 /*******************************************************************
326  *              RtlUnwind (NTDLL.@)
327  */
328 void WINAPI __regs_RtlUnwind( EXCEPTION_REGISTRATION_RECORD* pEndFrame, PVOID unusedEip,
329                               PEXCEPTION_RECORD pRecord, PVOID returnEax, CONTEXT *context )
330 {
331     EXCEPTION_RECORD record, newrec;
332     EXCEPTION_REGISTRATION_RECORD *frame, *dispatch;
333
334 #ifdef __i386__
335     context->Eax = (DWORD)returnEax;
336 #endif
337
338     /* build an exception record, if we do not have one */
339     if (!pRecord)
340     {
341         record.ExceptionCode    = STATUS_UNWIND;
342         record.ExceptionFlags   = 0;
343         record.ExceptionRecord  = NULL;
344         record.ExceptionAddress = GET_IP(context);
345         record.NumberParameters = 0;
346         pRecord = &record;
347     }
348
349     pRecord->ExceptionFlags |= EH_UNWINDING | (pEndFrame ? 0 : EH_EXIT_UNWIND);
350
351     TRACE( "code=%lx flags=%lx\n", pRecord->ExceptionCode, pRecord->ExceptionFlags );
352
353     /* get chain of exception frames */
354     frame = NtCurrentTeb()->Tib.ExceptionList;
355     while ((frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL) && (frame != pEndFrame))
356     {
357         /* Check frame address */
358         if (pEndFrame && (frame > pEndFrame))
359         {
360             newrec.ExceptionCode    = STATUS_INVALID_UNWIND_TARGET;
361             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
362             newrec.ExceptionRecord  = pRecord;
363             newrec.NumberParameters = 0;
364             RtlRaiseException( &newrec );  /* never returns */
365         }
366         if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
367             ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
368             (int)frame & 3)
369         {
370             newrec.ExceptionCode    = STATUS_BAD_STACK;
371             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
372             newrec.ExceptionRecord  = pRecord;
373             newrec.NumberParameters = 0;
374             RtlRaiseException( &newrec );  /* never returns */
375         }
376
377         /* Call handler */
378         switch(EXC_CallHandler( pRecord, frame, context, &dispatch,
379                                 frame->Handler, EXC_UnwindHandler ))
380         {
381         case ExceptionContinueSearch:
382             break;
383         case ExceptionCollidedUnwind:
384             frame = dispatch;
385             break;
386         default:
387             newrec.ExceptionCode    = STATUS_INVALID_DISPOSITION;
388             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
389             newrec.ExceptionRecord  = pRecord;
390             newrec.NumberParameters = 0;
391             RtlRaiseException( &newrec );  /* never returns */
392             break;
393         }
394         frame = __wine_pop_frame( frame );
395     }
396 }
397
398 /**********************************************************************/
399
400 #ifdef DEFINE_REGS_ENTRYPOINT
401 DEFINE_REGS_ENTRYPOINT( RtlUnwind, 16, 16 );
402 #else
403 void WINAPI RtlUnwind( PVOID pEndFrame, PVOID unusedEip,
404                        PEXCEPTION_RECORD pRecord, PVOID returnEax )
405 {
406     CONTEXT context;
407     memset( &context, 0, sizeof(context) );
408     __regs_RtlUnwind( pEndFrame, unusedEip, pRecord, returnEax, &context );
409 }
410 #endif
411
412
413 /*******************************************************************
414  *              NtRaiseException (NTDLL.@)
415  */
416 void WINAPI __regs_NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *ctx,
417                                   BOOL first, CONTEXT *context )
418 {
419     __regs_RtlRaiseException( rec, ctx );
420     *context = *ctx;
421 }
422
423 #ifdef DEFINE_REGS_ENTRYPOINT
424 DEFINE_REGS_ENTRYPOINT( NtRaiseException, 12, 12 );
425 #else
426 void WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *ctx, BOOL first )
427 {
428     CONTEXT context;
429     memset( &context, 0, sizeof(context) );
430     __regs_NtRaiseException( rec, ctx, first, &context );
431 }
432 #endif
433
434
435 /***********************************************************************
436  *            RtlRaiseStatus  (NTDLL.@)
437  *
438  * Raise an exception with ExceptionCode = status
439  */
440 void WINAPI RtlRaiseStatus( NTSTATUS status )
441 {
442     EXCEPTION_RECORD ExceptionRec;
443
444     ExceptionRec.ExceptionCode    = status;
445     ExceptionRec.ExceptionFlags   = EH_NONCONTINUABLE;
446     ExceptionRec.ExceptionRecord  = NULL;
447     ExceptionRec.NumberParameters = 0;
448     RtlRaiseException( &ExceptionRec );
449 }
450
451
452 /*******************************************************************
453  *         RtlAddVectoredExceptionHandler   (NTDLL.@)
454  */
455 PVOID WINAPI RtlAddVectoredExceptionHandler( ULONG first, PVECTORED_EXCEPTION_HANDLER func )
456 {
457     VECTORED_HANDLER *handler = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*handler) );
458     if (handler)
459     {
460         handler->func = func;
461         RtlEnterCriticalSection( &vectored_handlers_section );
462         if (first) list_add_head( &vectored_handlers, &handler->entry );
463         else list_add_tail( &vectored_handlers, &handler->entry );
464         RtlLeaveCriticalSection( &vectored_handlers_section );
465     }
466     return handler;
467 }
468
469
470 /*******************************************************************
471  *         RtlRemoveVectoredExceptionHandler   (NTDLL.@)
472  */
473 ULONG WINAPI RtlRemoveVectoredExceptionHandler( PVOID handler )
474 {
475     struct list *ptr;
476     ULONG ret = FALSE;
477
478     RtlEnterCriticalSection( &vectored_handlers_section );
479     LIST_FOR_EACH( ptr, &vectored_handlers )
480     {
481         VECTORED_HANDLER *curr_handler = LIST_ENTRY( ptr, VECTORED_HANDLER, entry );
482         if (curr_handler == handler)
483         {
484             list_remove( ptr );
485             ret = TRUE;
486             break;
487         }
488     }
489     RtlLeaveCriticalSection( &vectored_handlers_section );
490     if (ret) RtlFreeHeap( GetProcessHeap(), 0, handler );
491     return ret;
492 }
493
494
495 /*************************************************************
496  *            __wine_exception_handler (NTDLL.@)
497  *
498  * Exception handler for exception blocks declared in Wine code.
499  */
500 DWORD __wine_exception_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
501                                 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
502 {
503     __WINE_FRAME *wine_frame = (__WINE_FRAME *)frame;
504
505     if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND | EH_NESTED_CALL))
506         return ExceptionContinueSearch;
507     if (wine_frame->u.filter)
508     {
509         EXCEPTION_POINTERS ptrs;
510         ptrs.ExceptionRecord = record;
511         ptrs.ContextRecord = context;
512         switch(wine_frame->u.filter( &ptrs ))
513         {
514         case EXCEPTION_CONTINUE_SEARCH:
515             return ExceptionContinueSearch;
516         case EXCEPTION_CONTINUE_EXECUTION:
517             return ExceptionContinueExecution;
518         case EXCEPTION_EXECUTE_HANDLER:
519             break;
520         default:
521             MESSAGE( "Invalid return value from exception filter\n" );
522             assert( FALSE );
523         }
524     }
525     /* hack to make GetExceptionCode() work in handler */
526     wine_frame->ExceptionCode   = record->ExceptionCode;
527     wine_frame->ExceptionRecord = wine_frame;
528
529     RtlUnwind( frame, 0, record, 0 );
530     __wine_pop_frame( frame );
531     siglongjmp( wine_frame->jmp, 1 );
532 }
533
534
535 /*************************************************************
536  *            __wine_finally_handler (NTDLL.@)
537  *
538  * Exception handler for try/finally blocks declared in Wine code.
539  */
540 DWORD __wine_finally_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
541                               CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
542 {
543     if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
544     {
545         __WINE_FRAME *wine_frame = (__WINE_FRAME *)frame;
546         wine_frame->u.finally_func( FALSE );
547     }
548     return ExceptionContinueSearch;
549 }