server: Add functions for conversions between server object handles and pointer-style...
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdarg.h>
29
30 #include "ntstatus.h"
31 #define WIN32_NO_STATUS
32 #include "windef.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 RTL_CRITICAL_SECTION vectored_handlers_section;
59 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
60 {
61     0, 0, &vectored_handlers_section,
62     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
63       0, 0, { (DWORD_PTR)(__FILE__ ": vectored_handlers_section") }
64 };
65 static RTL_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 #elif defined(__x86_64__)
76 # define GET_IP(context) ((LPVOID)(context)->Rip)
77 #else
78 # error You must define GET_IP for this CPU
79 #endif
80
81 /*******************************************************************
82  *         EXC_RaiseHandler
83  *
84  * Handler for exceptions happening inside a handler.
85  */
86 static DWORD EXC_RaiseHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
87                                CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
88 {
89     if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
90         return ExceptionContinueSearch;
91     /* We shouldn't get here so we store faulty frame in dispatcher */
92     *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
93     return ExceptionNestedException;
94 }
95
96
97 /*******************************************************************
98  *         EXC_UnwindHandler
99  *
100  * Handler for exceptions happening inside an unwind handler.
101  */
102 static DWORD EXC_UnwindHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
103                                 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
104 {
105     if (!(rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))
106         return ExceptionContinueSearch;
107     /* We shouldn't get here so we store faulty frame in dispatcher */
108     *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
109     return ExceptionCollidedUnwind;
110 }
111
112
113 /*******************************************************************
114  *         EXC_CallHandler
115  *
116  * Call an exception handler, setting up an exception frame to catch exceptions
117  * happening during the handler execution.
118  *
119  * For i386 this function is implemented in assembler in signal_i386.c.
120  */
121 #ifndef __i386__
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     ret = handler( record, frame, context, dispatcher );
133     __wine_pop_frame( &newframe.frame );
134     return ret;
135 }
136 #else
137 /* in signal_i386.c */
138 extern DWORD EXC_CallHandler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
139                               CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher,
140                               PEXCEPTION_HANDLER handler, PEXCEPTION_HANDLER nested_handler);
141 #endif
142
143 /**********************************************************************
144  *           wait_suspend
145  *
146  * Wait until the thread is no longer suspended.
147  */
148 void wait_suspend( CONTEXT *context )
149 {
150     LARGE_INTEGER timeout;
151     int saved_errno = errno;
152
153     /* store the context we got at suspend time */
154     SERVER_START_REQ( set_thread_context )
155     {
156         req->handle  = wine_server_obj_handle( GetCurrentThread() );
157         req->flags   = CONTEXT_FULL;
158         req->suspend = 1;
159         wine_server_add_data( req, context, sizeof(*context) );
160         wine_server_call( req );
161     }
162     SERVER_END_REQ;
163
164     /* wait with 0 timeout, will only return once the thread is no longer suspended */
165     timeout.QuadPart = 0;
166     NTDLL_wait_for_multiple_objects( 0, NULL, SELECT_INTERRUPTIBLE, &timeout, 0 );
167
168     /* retrieve the new context */
169     SERVER_START_REQ( get_thread_context )
170     {
171         req->handle  = wine_server_obj_handle( GetCurrentThread() );
172         req->flags   = CONTEXT_FULL;
173         req->suspend = 1;
174         wine_server_set_reply( req, context, sizeof(*context) );
175         wine_server_call( req );
176     }
177     SERVER_END_REQ;
178
179     errno = saved_errno;
180 }
181
182
183 /**********************************************************************
184  *           send_debug_event
185  *
186  * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
187  */
188 static NTSTATUS send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
189 {
190     int ret;
191     HANDLE handle = 0;
192
193     if (!NtCurrentTeb()->Peb->BeingDebugged) return 0;  /* no debugger present */
194
195     SERVER_START_REQ( queue_exception_event )
196     {
197         req->first   = first_chance;
198         wine_server_add_data( req, context, sizeof(*context) );
199         wine_server_add_data( req, rec, sizeof(*rec) );
200         if (!wine_server_call( req )) handle = wine_server_ptr_handle( reply->handle );
201     }
202     SERVER_END_REQ;
203     if (!handle) return 0;
204
205     NTDLL_wait_for_multiple_objects( 1, &handle, SELECT_INTERRUPTIBLE, NULL, 0 );
206
207     SERVER_START_REQ( get_exception_status )
208     {
209         req->handle = wine_server_obj_handle( handle );
210         wine_server_set_reply( req, context, sizeof(*context) );
211         ret = wine_server_call( req );
212     }
213     SERVER_END_REQ;
214     return ret;
215 }
216
217
218 /**********************************************************************
219  *           call_vectored_handlers
220  *
221  * Call the vectored handlers chain.
222  */
223 static LONG call_vectored_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
224 {
225     struct list *ptr;
226     LONG ret = EXCEPTION_CONTINUE_SEARCH;
227     EXCEPTION_POINTERS except_ptrs;
228
229     except_ptrs.ExceptionRecord = rec;
230     except_ptrs.ContextRecord = context;
231
232     RtlEnterCriticalSection( &vectored_handlers_section );
233     LIST_FOR_EACH( ptr, &vectored_handlers )
234     {
235         VECTORED_HANDLER *handler = LIST_ENTRY( ptr, VECTORED_HANDLER, entry );
236         ret = handler->func( &except_ptrs );
237         if (ret == EXCEPTION_CONTINUE_EXECUTION) break;
238     }
239     RtlLeaveCriticalSection( &vectored_handlers_section );
240     return ret;
241 }
242
243
244 /**********************************************************************
245  *           call_stack_handlers
246  *
247  * Call the stack handlers chain.
248  */
249 static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
250 {
251     EXCEPTION_REGISTRATION_RECORD *frame, *dispatch, *nested_frame;
252     DWORD res;
253
254     frame = NtCurrentTeb()->Tib.ExceptionList;
255     nested_frame = NULL;
256     while (frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL)
257     {
258         /* Check frame address */
259         if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
260             ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
261             (ULONG_PTR)frame & 3)
262         {
263             rec->ExceptionFlags |= EH_STACK_INVALID;
264             break;
265         }
266
267         /* Call handler */
268         TRACE( "calling handler at %p code=%x flags=%x\n",
269                frame->Handler, rec->ExceptionCode, rec->ExceptionFlags );
270         res = EXC_CallHandler( rec, frame, context, &dispatch, frame->Handler, EXC_RaiseHandler );
271         TRACE( "handler at %p returned %x\n", frame->Handler, res );
272
273         if (frame == nested_frame)
274         {
275             /* no longer nested */
276             nested_frame = NULL;
277             rec->ExceptionFlags &= ~EH_NESTED_CALL;
278         }
279
280         switch(res)
281         {
282         case ExceptionContinueExecution:
283             if (!(rec->ExceptionFlags & EH_NONCONTINUABLE)) return STATUS_SUCCESS;
284             return STATUS_NONCONTINUABLE_EXCEPTION;
285         case ExceptionContinueSearch:
286             break;
287         case ExceptionNestedException:
288             if (nested_frame < dispatch) nested_frame = dispatch;
289             rec->ExceptionFlags |= EH_NESTED_CALL;
290             break;
291         default:
292             return STATUS_INVALID_DISPOSITION;
293         }
294         frame = frame->Prev;
295     }
296     return STATUS_UNHANDLED_EXCEPTION;
297 }
298
299
300 /*******************************************************************
301  *              raise_exception
302  *
303  * Implementation of NtRaiseException.
304  */
305 static NTSTATUS raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
306 {
307     NTSTATUS status;
308
309     if (first_chance)
310     {
311         DWORD c;
312
313         TRACE( "code=%x flags=%x addr=%p\n",
314                rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
315         for (c = 0; c < rec->NumberParameters; c++)
316             TRACE( " info[%d]=%08lx\n", c, rec->ExceptionInformation[c] );
317         if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
318         {
319             if (rec->ExceptionInformation[1] >> 16)
320                 MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
321                          rec->ExceptionAddress,
322                          (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
323             else
324                 MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
325                          rec->ExceptionAddress,
326                          (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
327         }
328 #ifdef __i386__
329         else
330         {
331             TRACE(" eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n",
332                   context->Eax, context->Ebx, context->Ecx,
333                   context->Edx, context->Esi, context->Edi );
334             TRACE(" ebp=%08x esp=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
335                   context->Ebp, context->Esp, context->SegCs, context->SegDs,
336                   context->SegEs, context->SegFs, context->SegGs, context->EFlags );
337         }
338 #endif
339         status = send_debug_event( rec, TRUE, context );
340         if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
341             return STATUS_SUCCESS;
342
343 #ifdef __i386__
344         /* fix up instruction pointer in context for EXCEPTION_BREAKPOINT */
345         if (rec->ExceptionCode == EXCEPTION_BREAKPOINT) context->Eip--;
346 #endif
347
348         if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION)
349             return STATUS_SUCCESS;
350
351         if ((status = call_stack_handlers( rec, context )) != STATUS_UNHANDLED_EXCEPTION)
352             return status;
353     }
354
355     /* last chance exception */
356
357     status = send_debug_event( rec, FALSE, context );
358     if (status != DBG_CONTINUE)
359     {
360         if (rec->ExceptionFlags & EH_STACK_INVALID)
361             ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
362         else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
363             ERR("Process attempted to continue execution after noncontinuable exception.\n");
364         else
365             ERR("Unhandled exception code %x flags %x addr %p\n",
366                 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
367         NtTerminateProcess( NtCurrentProcess(), 1 );
368     }
369     return STATUS_SUCCESS;
370 }
371
372
373 /*******************************************************************
374  *              NtRaiseException (NTDLL.@)
375  */
376 NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
377 {
378     NTSTATUS status = raise_exception( rec, context, first_chance );
379     if (status == STATUS_SUCCESS) NtSetContextThread( GetCurrentThread(), context );
380     return status;
381 }
382
383 /***********************************************************************
384  *              RtlCaptureContext (NTDLL.@)
385  */
386 void WINAPI __regs_RtlCaptureContext( CONTEXT *context_out, CONTEXT *context_in )
387 {
388     *context_out = *context_in;
389 }
390
391 /**********************************************************************/
392
393 #ifdef DEFINE_REGS_ENTRYPOINT
394 DEFINE_REGS_ENTRYPOINT( RtlCaptureContext, 4, 4 )
395 #else
396 void WINAPI RtlCaptureContext( CONTEXT *context_out )
397 {
398     memset( context_out, 0, sizeof(*context_out) );
399 }
400 #endif
401
402
403 /***********************************************************************
404  *              RtlRaiseException (NTDLL.@)
405  */
406 void WINAPI __regs_RtlRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context )
407 {
408     NTSTATUS status = raise_exception( rec, context, TRUE );
409     if (status != STATUS_SUCCESS)
410     {
411         EXCEPTION_RECORD newrec;
412         newrec.ExceptionCode    = status;
413         newrec.ExceptionFlags   = EH_NONCONTINUABLE;
414         newrec.ExceptionRecord  = rec;
415         newrec.NumberParameters = 0;
416         RtlRaiseException( &newrec );  /* never returns */
417     }
418 }
419
420 /**********************************************************************/
421
422 #ifdef DEFINE_REGS_ENTRYPOINT
423 DEFINE_REGS_ENTRYPOINT( RtlRaiseException, 4, 4 )
424 #else
425 void WINAPI RtlRaiseException( EXCEPTION_RECORD *rec )
426 {
427     CONTEXT context;
428     RtlCaptureContext( &context );
429     __regs_RtlRaiseException( rec, &context );
430 }
431 #endif
432
433
434 /*******************************************************************
435  *              RtlUnwind (NTDLL.@)
436  */
437 void WINAPI __regs_RtlUnwind( EXCEPTION_REGISTRATION_RECORD* pEndFrame, PVOID unusedEip,
438                               PEXCEPTION_RECORD pRecord, PVOID returnEax, CONTEXT *context )
439 {
440     EXCEPTION_RECORD record, newrec;
441     EXCEPTION_REGISTRATION_RECORD *frame, *dispatch;
442     DWORD res;
443
444 #ifdef __i386__
445     context->Eax = (DWORD)returnEax;
446 #endif
447
448     /* build an exception record, if we do not have one */
449     if (!pRecord)
450     {
451         record.ExceptionCode    = STATUS_UNWIND;
452         record.ExceptionFlags   = 0;
453         record.ExceptionRecord  = NULL;
454         record.ExceptionAddress = GET_IP(context);
455         record.NumberParameters = 0;
456         pRecord = &record;
457     }
458
459     pRecord->ExceptionFlags |= EH_UNWINDING | (pEndFrame ? 0 : EH_EXIT_UNWIND);
460
461     TRACE( "code=%x flags=%x\n", pRecord->ExceptionCode, pRecord->ExceptionFlags );
462
463     /* get chain of exception frames */
464     frame = NtCurrentTeb()->Tib.ExceptionList;
465     while ((frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL) && (frame != pEndFrame))
466     {
467         /* Check frame address */
468         if (pEndFrame && (frame > pEndFrame))
469         {
470             newrec.ExceptionCode    = STATUS_INVALID_UNWIND_TARGET;
471             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
472             newrec.ExceptionRecord  = pRecord;
473             newrec.NumberParameters = 0;
474             RtlRaiseException( &newrec );  /* never returns */
475         }
476         if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
477             ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
478             (UINT_PTR)frame & 3)
479         {
480             newrec.ExceptionCode    = STATUS_BAD_STACK;
481             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
482             newrec.ExceptionRecord  = pRecord;
483             newrec.NumberParameters = 0;
484             RtlRaiseException( &newrec );  /* never returns */
485         }
486
487         /* Call handler */
488         TRACE( "calling handler at %p code=%x flags=%x\n",
489                frame->Handler, pRecord->ExceptionCode, pRecord->ExceptionFlags );
490         res = EXC_CallHandler( pRecord, frame, context, &dispatch, frame->Handler, EXC_UnwindHandler );
491         TRACE( "handler at %p returned %x\n", frame->Handler, res );
492
493         switch(res)
494         {
495         case ExceptionContinueSearch:
496             break;
497         case ExceptionCollidedUnwind:
498             frame = dispatch;
499             break;
500         default:
501             newrec.ExceptionCode    = STATUS_INVALID_DISPOSITION;
502             newrec.ExceptionFlags   = EH_NONCONTINUABLE;
503             newrec.ExceptionRecord  = pRecord;
504             newrec.NumberParameters = 0;
505             RtlRaiseException( &newrec );  /* never returns */
506             break;
507         }
508         frame = __wine_pop_frame( frame );
509     }
510 }
511
512 /**********************************************************************/
513
514 #ifdef DEFINE_REGS_ENTRYPOINT
515 DEFINE_REGS_ENTRYPOINT( RtlUnwind, 16, 16 )
516 #else
517 void WINAPI RtlUnwind( PVOID pEndFrame, PVOID unusedEip,
518                        PEXCEPTION_RECORD pRecord, PVOID returnEax )
519 {
520     CONTEXT context;
521     RtlCaptureContext( &context );
522     __regs_RtlUnwind( pEndFrame, unusedEip, pRecord, returnEax, &context );
523 }
524 #endif
525
526
527 /***********************************************************************
528  *            RtlRaiseStatus  (NTDLL.@)
529  *
530  * Raise an exception with ExceptionCode = status
531  */
532 void WINAPI RtlRaiseStatus( NTSTATUS status )
533 {
534     EXCEPTION_RECORD ExceptionRec;
535
536     ExceptionRec.ExceptionCode    = status;
537     ExceptionRec.ExceptionFlags   = EH_NONCONTINUABLE;
538     ExceptionRec.ExceptionRecord  = NULL;
539     ExceptionRec.NumberParameters = 0;
540     RtlRaiseException( &ExceptionRec );
541 }
542
543
544 /*******************************************************************
545  *         RtlAddVectoredExceptionHandler   (NTDLL.@)
546  */
547 PVOID WINAPI RtlAddVectoredExceptionHandler( ULONG first, PVECTORED_EXCEPTION_HANDLER func )
548 {
549     VECTORED_HANDLER *handler = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*handler) );
550     if (handler)
551     {
552         handler->func = func;
553         RtlEnterCriticalSection( &vectored_handlers_section );
554         if (first) list_add_head( &vectored_handlers, &handler->entry );
555         else list_add_tail( &vectored_handlers, &handler->entry );
556         RtlLeaveCriticalSection( &vectored_handlers_section );
557     }
558     return handler;
559 }
560
561
562 /*******************************************************************
563  *         RtlRemoveVectoredExceptionHandler   (NTDLL.@)
564  */
565 ULONG WINAPI RtlRemoveVectoredExceptionHandler( PVOID handler )
566 {
567     struct list *ptr;
568     ULONG ret = FALSE;
569
570     RtlEnterCriticalSection( &vectored_handlers_section );
571     LIST_FOR_EACH( ptr, &vectored_handlers )
572     {
573         VECTORED_HANDLER *curr_handler = LIST_ENTRY( ptr, VECTORED_HANDLER, entry );
574         if (curr_handler == handler)
575         {
576             list_remove( ptr );
577             ret = TRUE;
578             break;
579         }
580     }
581     RtlLeaveCriticalSection( &vectored_handlers_section );
582     if (ret) RtlFreeHeap( GetProcessHeap(), 0, handler );
583     return ret;
584 }
585
586
587 /*************************************************************
588  *            __wine_spec_unimplemented_stub
589  *
590  * ntdll-specific implementation to avoid depending on kernel functions.
591  * Can be removed once ntdll.spec no longer contains stubs.
592  */
593 void __wine_spec_unimplemented_stub( const char *module, const char *function )
594 {
595     EXCEPTION_RECORD record;
596
597     record.ExceptionCode    = EXCEPTION_WINE_STUB;
598     record.ExceptionFlags   = EH_NONCONTINUABLE;
599     record.ExceptionRecord  = NULL;
600     record.ExceptionAddress = __wine_spec_unimplemented_stub;
601     record.NumberParameters = 2;
602     record.ExceptionInformation[0] = (ULONG_PTR)module;
603     record.ExceptionInformation[1] = (ULONG_PTR)function;
604     RtlRaiseException( &record );
605 }