ntdll: Fix up instruction pointer in context inside raise_exception.
[wine.git] / dlls / ntdll / exception.c
blob8974cedce95b2227aeb775b00fdf91054af862e4
1 /*
2 * NT exception handling routines
4 * Copyright 1999 Turchanov Sergey
5 * Copyright 1999 Alexandre Julliard
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.
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.
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
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <signal.h>
27 #include <stdarg.h>
29 #include "ntstatus.h"
30 #define WIN32_NO_STATUS
31 #include "windef.h"
32 #include "winternl.h"
33 #include "wine/exception.h"
34 #include "wine/server.h"
35 #include "wine/list.h"
36 #include "wine/debug.h"
37 #include "excpt.h"
38 #include "ntdll_misc.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(seh);
42 /* Exception record for handling exceptions happening inside exception handlers */
43 typedef struct
45 EXCEPTION_REGISTRATION_RECORD frame;
46 EXCEPTION_REGISTRATION_RECORD *prevFrame;
47 } EXC_NESTED_FRAME;
49 typedef struct
51 struct list entry;
52 PVECTORED_EXCEPTION_HANDLER func;
53 } VECTORED_HANDLER;
55 static struct list vectored_handlers = LIST_INIT(vectored_handlers);
57 static RTL_CRITICAL_SECTION vectored_handlers_section;
58 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
60 0, 0, &vectored_handlers_section,
61 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
62 0, 0, { (DWORD_PTR)(__FILE__ ": vectored_handlers_section") }
64 static RTL_CRITICAL_SECTION vectored_handlers_section = { &critsect_debug, -1, 0, 0, 0, 0 };
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 #elif defined(__ALPHA__)
73 # define GET_IP(context) ((LPVOID)(context)->Fir)
74 #elif defined(__x86_64__)
75 # define GET_IP(context) ((LPVOID)(context)->Rip)
76 #else
77 # error You must define GET_IP for this CPU
78 #endif
80 /*******************************************************************
81 * EXC_RaiseHandler
83 * Handler for exceptions happening inside a handler.
85 static DWORD EXC_RaiseHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
86 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
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;
96 /*******************************************************************
97 * EXC_UnwindHandler
99 * Handler for exceptions happening inside an unwind handler.
101 static DWORD EXC_UnwindHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
102 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
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;
112 /*******************************************************************
113 * EXC_CallHandler
115 * Call an exception handler, setting up an exception frame to catch exceptions
116 * happening during the handler execution.
118 * For i386 this function is implemented in assembler in signal_i386.c.
120 #ifndef __i386__
121 static DWORD EXC_CallHandler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
122 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher,
123 PEXCEPTION_HANDLER handler, PEXCEPTION_HANDLER nested_handler)
125 EXC_NESTED_FRAME newframe;
126 DWORD ret;
128 newframe.frame.Handler = nested_handler;
129 newframe.prevFrame = frame;
130 __wine_push_frame( &newframe.frame );
131 ret = handler( record, frame, context, dispatcher );
132 __wine_pop_frame( &newframe.frame );
133 return ret;
135 #else
136 /* in signal_i386.c */
137 extern DWORD EXC_CallHandler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
138 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher,
139 PEXCEPTION_HANDLER handler, PEXCEPTION_HANDLER nested_handler);
140 #endif
142 /**********************************************************************
143 * wait_suspend
145 * Wait until the thread is no longer suspended.
147 void wait_suspend( CONTEXT *context )
149 LARGE_INTEGER timeout;
151 /* store the context we got at suspend time */
152 SERVER_START_REQ( set_thread_context )
154 req->handle = GetCurrentThread();
155 req->flags = CONTEXT_FULL;
156 req->suspend = 1;
157 wine_server_add_data( req, context, sizeof(*context) );
158 wine_server_call( req );
160 SERVER_END_REQ;
162 /* wait with 0 timeout, will only return once the thread is no longer suspended */
163 timeout.QuadPart = 0;
164 NTDLL_wait_for_multiple_objects( 0, NULL, SELECT_INTERRUPTIBLE, &timeout, 0 );
166 /* retrieve the new context */
167 SERVER_START_REQ( get_thread_context )
169 req->handle = GetCurrentThread();
170 req->flags = CONTEXT_FULL;
171 req->suspend = 1;
172 wine_server_set_reply( req, context, sizeof(*context) );
173 wine_server_call( req );
175 SERVER_END_REQ;
179 /**********************************************************************
180 * send_debug_event
182 * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
184 static NTSTATUS send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
186 int ret;
187 HANDLE handle = 0;
189 if (!NtCurrentTeb()->Peb->BeingDebugged) return 0; /* no debugger present */
191 SERVER_START_REQ( queue_exception_event )
193 req->first = first_chance;
194 wine_server_add_data( req, context, sizeof(*context) );
195 wine_server_add_data( req, rec, sizeof(*rec) );
196 if (!wine_server_call( req )) handle = reply->handle;
198 SERVER_END_REQ;
199 if (!handle) return 0;
201 NTDLL_wait_for_multiple_objects( 1, &handle, SELECT_INTERRUPTIBLE, NULL, 0 );
203 SERVER_START_REQ( get_exception_status )
205 req->handle = handle;
206 wine_server_set_reply( req, context, sizeof(*context) );
207 ret = wine_server_call( req );
209 SERVER_END_REQ;
210 return ret;
214 /**********************************************************************
215 * call_vectored_handlers
217 * Call the vectored handlers chain.
219 static LONG call_vectored_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
221 struct list *ptr;
222 LONG ret = EXCEPTION_CONTINUE_SEARCH;
223 EXCEPTION_POINTERS except_ptrs;
225 except_ptrs.ExceptionRecord = rec;
226 except_ptrs.ContextRecord = context;
228 RtlEnterCriticalSection( &vectored_handlers_section );
229 LIST_FOR_EACH( ptr, &vectored_handlers )
231 VECTORED_HANDLER *handler = LIST_ENTRY( ptr, VECTORED_HANDLER, entry );
232 ret = handler->func( &except_ptrs );
233 if (ret == EXCEPTION_CONTINUE_EXECUTION) break;
235 RtlLeaveCriticalSection( &vectored_handlers_section );
236 return ret;
240 /**********************************************************************
241 * call_stack_handlers
243 * Call the stack handlers chain.
245 static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
247 EXCEPTION_REGISTRATION_RECORD *frame, *dispatch, *nested_frame;
248 DWORD res;
250 frame = NtCurrentTeb()->Tib.ExceptionList;
251 nested_frame = NULL;
252 while (frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL)
254 /* Check frame address */
255 if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
256 ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
257 (ULONG_PTR)frame & 3)
259 rec->ExceptionFlags |= EH_STACK_INVALID;
260 break;
263 /* Call handler */
264 TRACE( "calling handler at %p code=%x flags=%x\n",
265 frame->Handler, rec->ExceptionCode, rec->ExceptionFlags );
266 res = EXC_CallHandler( rec, frame, context, &dispatch, frame->Handler, EXC_RaiseHandler );
267 TRACE( "handler at %p returned %x\n", frame->Handler, res );
269 if (frame == nested_frame)
271 /* no longer nested */
272 nested_frame = NULL;
273 rec->ExceptionFlags &= ~EH_NESTED_CALL;
276 switch(res)
278 case ExceptionContinueExecution:
279 if (!(rec->ExceptionFlags & EH_NONCONTINUABLE)) return STATUS_SUCCESS;
280 return STATUS_NONCONTINUABLE_EXCEPTION;
281 case ExceptionContinueSearch:
282 break;
283 case ExceptionNestedException:
284 if (nested_frame < dispatch) nested_frame = dispatch;
285 rec->ExceptionFlags |= EH_NESTED_CALL;
286 break;
287 default:
288 return STATUS_INVALID_DISPOSITION;
290 frame = frame->Prev;
292 return STATUS_UNHANDLED_EXCEPTION;
296 /*******************************************************************
297 * raise_exception
299 * Implementation of NtRaiseException.
301 static NTSTATUS raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
303 NTSTATUS status;
305 if (first_chance)
307 DWORD c;
309 TRACE( "code=%x flags=%x addr=%p\n",
310 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
311 for (c = 0; c < rec->NumberParameters; c++)
312 TRACE( " info[%d]=%08lx\n", c, rec->ExceptionInformation[c] );
313 if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
315 if (rec->ExceptionInformation[1] >> 16)
316 MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
317 rec->ExceptionAddress,
318 (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
319 else
320 MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
321 rec->ExceptionAddress,
322 (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
324 #ifdef __i386__
325 else
327 TRACE(" eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n",
328 context->Eax, context->Ebx, context->Ecx,
329 context->Edx, context->Esi, context->Edi );
330 TRACE(" ebp=%08x esp=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
331 context->Ebp, context->Esp, context->SegCs, context->SegDs,
332 context->SegEs, context->SegFs, context->SegGs, context->EFlags );
334 #endif
335 status = send_debug_event( rec, TRUE, context );
336 if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
337 return STATUS_SUCCESS;
339 #ifdef __i386__
340 /* fix up instruction pointer in context for EXCEPTION_BREAKPOINT */
341 if (rec->ExceptionCode == EXCEPTION_BREAKPOINT) context->Eip--;
342 #endif
344 if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION)
345 return STATUS_SUCCESS;
347 if ((status = call_stack_handlers( rec, context )) != STATUS_UNHANDLED_EXCEPTION)
348 return status;
351 /* last chance exception */
353 status = send_debug_event( rec, FALSE, context );
354 if (status != DBG_CONTINUE)
356 if (rec->ExceptionFlags & EH_STACK_INVALID)
357 ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
358 else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
359 ERR("Process attempted to continue execution after noncontinuable exception.\n");
360 else
361 ERR("Unhandled exception code %x flags %x addr %p\n",
362 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
363 NtTerminateProcess( NtCurrentProcess(), 1 );
365 return STATUS_SUCCESS;
369 /*******************************************************************
370 * NtRaiseException (NTDLL.@)
372 NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
374 NTSTATUS status = raise_exception( rec, context, first_chance );
375 if (status == STATUS_SUCCESS) NtSetContextThread( GetCurrentThread(), context );
376 return status;
379 /***********************************************************************
380 * RtlRaiseException (NTDLL.@)
382 void WINAPI __regs_RtlRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context )
384 NTSTATUS status = raise_exception( rec, context, TRUE );
385 if (status != STATUS_SUCCESS)
387 EXCEPTION_RECORD newrec;
388 newrec.ExceptionCode = status;
389 newrec.ExceptionFlags = EH_NONCONTINUABLE;
390 newrec.ExceptionRecord = rec;
391 newrec.NumberParameters = 0;
392 RtlRaiseException( &newrec ); /* never returns */
396 /**********************************************************************/
398 #ifdef DEFINE_REGS_ENTRYPOINT
399 DEFINE_REGS_ENTRYPOINT( RtlRaiseException, 4, 4 )
400 #else
401 void WINAPI RtlRaiseException( EXCEPTION_RECORD *rec )
403 CONTEXT context;
404 memset( &context, 0, sizeof(context) );
405 __regs_RtlRaiseException( rec, &context );
407 #endif
410 /*******************************************************************
411 * RtlUnwind (NTDLL.@)
413 void WINAPI __regs_RtlUnwind( EXCEPTION_REGISTRATION_RECORD* pEndFrame, PVOID unusedEip,
414 PEXCEPTION_RECORD pRecord, PVOID returnEax, CONTEXT *context )
416 EXCEPTION_RECORD record, newrec;
417 EXCEPTION_REGISTRATION_RECORD *frame, *dispatch;
418 DWORD res;
420 #ifdef __i386__
421 context->Eax = (DWORD)returnEax;
422 #endif
424 /* build an exception record, if we do not have one */
425 if (!pRecord)
427 record.ExceptionCode = STATUS_UNWIND;
428 record.ExceptionFlags = 0;
429 record.ExceptionRecord = NULL;
430 record.ExceptionAddress = GET_IP(context);
431 record.NumberParameters = 0;
432 pRecord = &record;
435 pRecord->ExceptionFlags |= EH_UNWINDING | (pEndFrame ? 0 : EH_EXIT_UNWIND);
437 TRACE( "code=%x flags=%x\n", pRecord->ExceptionCode, pRecord->ExceptionFlags );
439 /* get chain of exception frames */
440 frame = NtCurrentTeb()->Tib.ExceptionList;
441 while ((frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL) && (frame != pEndFrame))
443 /* Check frame address */
444 if (pEndFrame && (frame > pEndFrame))
446 newrec.ExceptionCode = STATUS_INVALID_UNWIND_TARGET;
447 newrec.ExceptionFlags = EH_NONCONTINUABLE;
448 newrec.ExceptionRecord = pRecord;
449 newrec.NumberParameters = 0;
450 RtlRaiseException( &newrec ); /* never returns */
452 if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
453 ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
454 (UINT_PTR)frame & 3)
456 newrec.ExceptionCode = STATUS_BAD_STACK;
457 newrec.ExceptionFlags = EH_NONCONTINUABLE;
458 newrec.ExceptionRecord = pRecord;
459 newrec.NumberParameters = 0;
460 RtlRaiseException( &newrec ); /* never returns */
463 /* Call handler */
464 TRACE( "calling handler at %p code=%x flags=%x\n",
465 frame->Handler, pRecord->ExceptionCode, pRecord->ExceptionFlags );
466 res = EXC_CallHandler( pRecord, frame, context, &dispatch, frame->Handler, EXC_UnwindHandler );
467 TRACE( "handler at %p returned %x\n", frame->Handler, res );
469 switch(res)
471 case ExceptionContinueSearch:
472 break;
473 case ExceptionCollidedUnwind:
474 frame = dispatch;
475 break;
476 default:
477 newrec.ExceptionCode = STATUS_INVALID_DISPOSITION;
478 newrec.ExceptionFlags = EH_NONCONTINUABLE;
479 newrec.ExceptionRecord = pRecord;
480 newrec.NumberParameters = 0;
481 RtlRaiseException( &newrec ); /* never returns */
482 break;
484 frame = __wine_pop_frame( frame );
488 /**********************************************************************/
490 #ifdef DEFINE_REGS_ENTRYPOINT
491 DEFINE_REGS_ENTRYPOINT( RtlUnwind, 16, 16 )
492 #else
493 void WINAPI RtlUnwind( PVOID pEndFrame, PVOID unusedEip,
494 PEXCEPTION_RECORD pRecord, PVOID returnEax )
496 CONTEXT context;
497 memset( &context, 0, sizeof(context) );
498 __regs_RtlUnwind( pEndFrame, unusedEip, pRecord, returnEax, &context );
500 #endif
503 /***********************************************************************
504 * RtlRaiseStatus (NTDLL.@)
506 * Raise an exception with ExceptionCode = status
508 void WINAPI RtlRaiseStatus( NTSTATUS status )
510 EXCEPTION_RECORD ExceptionRec;
512 ExceptionRec.ExceptionCode = status;
513 ExceptionRec.ExceptionFlags = EH_NONCONTINUABLE;
514 ExceptionRec.ExceptionRecord = NULL;
515 ExceptionRec.NumberParameters = 0;
516 RtlRaiseException( &ExceptionRec );
520 /*******************************************************************
521 * RtlAddVectoredExceptionHandler (NTDLL.@)
523 PVOID WINAPI RtlAddVectoredExceptionHandler( ULONG first, PVECTORED_EXCEPTION_HANDLER func )
525 VECTORED_HANDLER *handler = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*handler) );
526 if (handler)
528 handler->func = func;
529 RtlEnterCriticalSection( &vectored_handlers_section );
530 if (first) list_add_head( &vectored_handlers, &handler->entry );
531 else list_add_tail( &vectored_handlers, &handler->entry );
532 RtlLeaveCriticalSection( &vectored_handlers_section );
534 return handler;
538 /*******************************************************************
539 * RtlRemoveVectoredExceptionHandler (NTDLL.@)
541 ULONG WINAPI RtlRemoveVectoredExceptionHandler( PVOID handler )
543 struct list *ptr;
544 ULONG ret = FALSE;
546 RtlEnterCriticalSection( &vectored_handlers_section );
547 LIST_FOR_EACH( ptr, &vectored_handlers )
549 VECTORED_HANDLER *curr_handler = LIST_ENTRY( ptr, VECTORED_HANDLER, entry );
550 if (curr_handler == handler)
552 list_remove( ptr );
553 ret = TRUE;
554 break;
557 RtlLeaveCriticalSection( &vectored_handlers_section );
558 if (ret) RtlFreeHeap( GetProcessHeap(), 0, handler );
559 return ret;
563 /*************************************************************
564 * __wine_exception_handler (NTDLL.@)
566 * Exception handler for exception blocks declared in Wine code.
568 DWORD __wine_exception_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
569 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
571 __WINE_FRAME *wine_frame = (__WINE_FRAME *)frame;
573 if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND | EH_NESTED_CALL))
574 return ExceptionContinueSearch;
576 if (wine_frame->u.filter == (void *)1) /* special hack for page faults */
578 if (record->ExceptionCode != STATUS_ACCESS_VIOLATION)
579 return ExceptionContinueSearch;
581 else if (wine_frame->u.filter)
583 EXCEPTION_POINTERS ptrs;
584 ptrs.ExceptionRecord = record;
585 ptrs.ContextRecord = context;
586 switch(wine_frame->u.filter( &ptrs ))
588 case EXCEPTION_CONTINUE_SEARCH:
589 return ExceptionContinueSearch;
590 case EXCEPTION_CONTINUE_EXECUTION:
591 return ExceptionContinueExecution;
592 case EXCEPTION_EXECUTE_HANDLER:
593 break;
594 default:
595 MESSAGE( "Invalid return value from exception filter\n" );
596 assert( FALSE );
599 /* hack to make GetExceptionCode() work in handler */
600 wine_frame->ExceptionCode = record->ExceptionCode;
601 wine_frame->ExceptionRecord = wine_frame;
603 RtlUnwind( frame, 0, record, 0 );
604 __wine_pop_frame( frame );
605 siglongjmp( wine_frame->jmp, 1 );
609 /*************************************************************
610 * __wine_finally_handler (NTDLL.@)
612 * Exception handler for try/finally blocks declared in Wine code.
614 DWORD __wine_finally_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
615 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
617 if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
619 __WINE_FRAME *wine_frame = (__WINE_FRAME *)frame;
620 wine_frame->u.finally_func( FALSE );
622 return ExceptionContinueSearch;
626 /*************************************************************
627 * __wine_spec_unimplemented_stub
629 * ntdll-specific implementation to avoid depending on kernel functions.
630 * Can be removed once ntdll.spec no longer contains stubs.
632 void __wine_spec_unimplemented_stub( const char *module, const char *function )
634 EXCEPTION_RECORD record;
636 record.ExceptionCode = EXCEPTION_WINE_STUB;
637 record.ExceptionFlags = EH_NONCONTINUABLE;
638 record.ExceptionRecord = NULL;
639 record.ExceptionAddress = __wine_spec_unimplemented_stub;
640 record.NumberParameters = 2;
641 record.ExceptionInformation[0] = (ULONG_PTR)module;
642 record.ExceptionInformation[1] = (ULONG_PTR)function;
643 RtlRaiseException( &record );