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