Correct the test for the ODS_SELECTED bit in the WM_DRAWITEM message
[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 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     if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION) return;
245
246     frame = NtCurrentTeb()->Tib.ExceptionList;
247     nested_frame = NULL;
248     while (frame != (PEXCEPTION_REGISTRATION_RECORD)~0UL)
249     {
250         /* Check frame address */
251         if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
252             ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
253             (int)frame & 3)
254         {
255             rec->ExceptionFlags |= EH_STACK_INVALID;
256             break;
257         }
258
259         /* Call handler */
260         res = EXC_CallHandler( rec, frame, context, &dispatch, frame->Handler, EXC_RaiseHandler );
261         if (frame == nested_frame)
262         {
263             /* no longer nested */
264             nested_frame = NULL;
265             rec->ExceptionFlags &= ~EH_NESTED_CALL;
266         }
267
268         switch(res)
269         {
270         case ExceptionContinueExecution:
271             if (!(rec->ExceptionFlags & EH_NONCONTINUABLE)) return;
272             newrec.ExceptionCode    = STATUS_NONCONTINUABLE_EXCEPTION;
273             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
274             newrec.ExceptionRecord  = rec;
275             newrec.NumberParameters = 0;
276             RtlRaiseException( &newrec );  /* never returns */
277             break;
278         case ExceptionContinueSearch:
279             break;
280         case ExceptionNestedException:
281             if (nested_frame < dispatch) nested_frame = dispatch;
282             rec->ExceptionFlags |= EH_NESTED_CALL;
283             break;
284         default:
285             newrec.ExceptionCode    = STATUS_INVALID_DISPOSITION;
286             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
287             newrec.ExceptionRecord  = rec;
288             newrec.NumberParameters = 0;
289             RtlRaiseException( &newrec );  /* never returns */
290             break;
291         }
292         frame = frame->Prev;
293     }
294     EXC_DefaultHandling( rec, context );
295 }
296
297 #ifdef DEFINE_REGS_ENTRYPOINT
298 DEFINE_REGS_ENTRYPOINT( RtlRaiseException, EXC_RtlRaiseException, 4, 4 );
299 #else
300 void WINAPI RtlRaiseException( EXCEPTION_RECORD *rec )
301 {
302     CONTEXT context;
303     memset( &context, 0, sizeof(context) );
304     EXC_RtlRaiseException( rec, &context );
305 }
306 #endif
307
308
309 /*******************************************************************
310  *              RtlUnwind (NTDLL.@)
311  */
312 void WINAPI EXC_RtlUnwind( PEXCEPTION_REGISTRATION_RECORD pEndFrame, LPVOID unusedEip,
313                            PEXCEPTION_RECORD pRecord, DWORD returnEax,
314                            CONTEXT *context )
315 {
316     EXCEPTION_RECORD record, newrec;
317     PEXCEPTION_REGISTRATION_RECORD frame, dispatch;
318
319 #ifdef __i386__
320     context->Eax = returnEax;
321 #endif
322
323     /* build an exception record, if we do not have one */
324     if (!pRecord)
325     {
326         record.ExceptionCode    = STATUS_UNWIND;
327         record.ExceptionFlags   = 0;
328         record.ExceptionRecord  = NULL;
329         record.ExceptionAddress = GET_IP(context);
330         record.NumberParameters = 0;
331         pRecord = &record;
332     }
333
334     pRecord->ExceptionFlags |= EH_UNWINDING | (pEndFrame ? 0 : EH_EXIT_UNWIND);
335
336     TRACE( "code=%lx flags=%lx\n", pRecord->ExceptionCode, pRecord->ExceptionFlags );
337
338     /* get chain of exception frames */
339     frame = NtCurrentTeb()->Tib.ExceptionList;
340     while ((frame != (PEXCEPTION_REGISTRATION_RECORD)~0UL) && (frame != pEndFrame))
341     {
342         /* Check frame address */
343         if (pEndFrame && (frame > pEndFrame))
344         {
345             newrec.ExceptionCode    = STATUS_INVALID_UNWIND_TARGET;
346             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
347             newrec.ExceptionRecord  = pRecord;
348             newrec.NumberParameters = 0;
349             RtlRaiseException( &newrec );  /* never returns */
350         }
351         if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
352             ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
353             (int)frame & 3)
354         {
355             newrec.ExceptionCode    = STATUS_BAD_STACK;
356             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
357             newrec.ExceptionRecord  = pRecord;
358             newrec.NumberParameters = 0;
359             RtlRaiseException( &newrec );  /* never returns */
360         }
361
362         /* Call handler */
363         switch(EXC_CallHandler( pRecord, frame, context, &dispatch,
364                                 frame->Handler, EXC_UnwindHandler ))
365         {
366         case ExceptionContinueSearch:
367             break;
368         case ExceptionCollidedUnwind:
369             frame = dispatch;
370             break;
371         default:
372             newrec.ExceptionCode    = STATUS_INVALID_DISPOSITION;
373             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
374             newrec.ExceptionRecord  = pRecord;
375             newrec.NumberParameters = 0;
376             RtlRaiseException( &newrec );  /* never returns */
377             break;
378         }
379         frame = __wine_pop_frame( frame );
380     }
381 }
382
383 #ifdef DEFINE_REGS_ENTRYPOINT
384 DEFINE_REGS_ENTRYPOINT( RtlUnwind, EXC_RtlUnwind, 16, 16 );
385 #else
386 void WINAPI RtlUnwind( PEXCEPTION_REGISTRATION_RECORD pEndFrame, LPVOID unusedEip,
387                        PEXCEPTION_RECORD pRecord, DWORD returnEax )
388 {
389     CONTEXT context;
390     memset( &context, 0, sizeof(context) );
391     EXC_RtlUnwind( pEndFrame, unusedEip, pRecord, returnEax, &context );
392 }
393 #endif
394
395
396 /*******************************************************************
397  *              NtRaiseException (NTDLL.@)
398  */
399 void WINAPI EXC_NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *ctx,
400                                   BOOL first, CONTEXT *context )
401 {
402     EXC_RtlRaiseException( rec, ctx );
403     *context = *ctx;
404 }
405
406 #ifdef DEFINE_REGS_ENTRYPOINT
407 DEFINE_REGS_ENTRYPOINT( NtRaiseException, EXC_NtRaiseException, 12, 12 );
408 #else
409 void WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *ctx, BOOL first )
410 {
411     CONTEXT context;
412     memset( &context, 0, sizeof(context) );
413     EXC_NtRaiseException( rec, ctx, first, &context );
414 }
415 #endif
416
417
418 /***********************************************************************
419  *            RtlRaiseStatus  (NTDLL.@)
420  *
421  * Raise an exception with ExceptionCode = status
422  */
423 void WINAPI RtlRaiseStatus( NTSTATUS status )
424 {
425     EXCEPTION_RECORD ExceptionRec;
426
427     ExceptionRec.ExceptionCode    = status;
428     ExceptionRec.ExceptionFlags   = EH_NONCONTINUABLE;
429     ExceptionRec.ExceptionRecord  = NULL;
430     ExceptionRec.NumberParameters = 0;
431     RtlRaiseException( &ExceptionRec );
432 }
433
434
435 /*******************************************************************
436  *         RtlAddVectoredExceptionHandler   (NTDLL.@)
437  */
438 PVOID WINAPI RtlAddVectoredExceptionHandler( ULONG first, PVECTORED_EXCEPTION_HANDLER func )
439 {
440     VECTORED_HANDLER *handler = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*handler) );
441     if (handler)
442     {
443         handler->func = func;
444         RtlEnterCriticalSection( &vectored_handlers_section );
445         if (first) list_add_head( &vectored_handlers, &handler->entry );
446         else list_add_tail( &vectored_handlers, &handler->entry );
447         RtlLeaveCriticalSection( &vectored_handlers_section );
448     }
449     return handler;
450 }
451
452
453 /*******************************************************************
454  *         RtlRemoveVectoredExceptionHandler   (NTDLL.@)
455  */
456 ULONG WINAPI RtlRemoveVectoredExceptionHandler( PVOID handler )
457 {
458     struct list *ptr;
459     ULONG ret = FALSE;
460
461     RtlEnterCriticalSection( &vectored_handlers_section );
462     LIST_FOR_EACH( ptr, &vectored_handlers )
463     {
464         if (ptr == &((VECTORED_HANDLER *)handler)->entry)
465         {
466             list_remove( ptr );
467             ret = TRUE;
468             break;
469         }
470     }
471     RtlLeaveCriticalSection( &vectored_handlers_section );
472     if (ret) RtlFreeHeap( GetProcessHeap(), 0, handler );
473     return ret;
474 }
475
476
477 /*************************************************************
478  *            __wine_exception_handler (NTDLL.@)
479  *
480  * Exception handler for exception blocks declared in Wine code.
481  */
482 DWORD __wine_exception_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
483                                 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
484 {
485     __WINE_FRAME *wine_frame = (__WINE_FRAME *)frame;
486
487     if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND | EH_NESTED_CALL))
488         return ExceptionContinueSearch;
489     if (wine_frame->u.filter)
490     {
491         EXCEPTION_POINTERS ptrs;
492         ptrs.ExceptionRecord = record;
493         ptrs.ContextRecord = context;
494         switch(wine_frame->u.filter( &ptrs ))
495         {
496         case EXCEPTION_CONTINUE_SEARCH:
497             return ExceptionContinueSearch;
498         case EXCEPTION_CONTINUE_EXECUTION:
499             return ExceptionContinueExecution;
500         case EXCEPTION_EXECUTE_HANDLER:
501             break;
502         default:
503             MESSAGE( "Invalid return value from exception filter\n" );
504             assert( FALSE );
505         }
506     }
507     /* hack to make GetExceptionCode() work in handler */
508     wine_frame->ExceptionCode   = record->ExceptionCode;
509     wine_frame->ExceptionRecord = wine_frame;
510
511     RtlUnwind( frame, 0, record, 0 );
512     __wine_pop_frame( frame );
513     siglongjmp( wine_frame->jmp, 1 );
514 }
515
516
517 /*************************************************************
518  *            __wine_finally_handler (NTDLL.@)
519  *
520  * Exception handler for try/finally blocks declared in Wine code.
521  */
522 DWORD __wine_finally_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
523                               CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
524 {
525     if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
526     {
527         __WINE_FRAME *wine_frame = (__WINE_FRAME *)frame;
528         wine_frame->u.finally_func( FALSE );
529     }
530     return ExceptionContinueSearch;
531 }