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