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