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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include "wine/port.h"
30 #define WIN32_NO_STATUS
33 #include "wine/exception.h"
34 #include "wine/server.h"
35 #include "wine/list.h"
36 #include "wine/debug.h"
38 #include "ntdll_misc.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(seh);
42 /* Exception record for handling exceptions happening inside exception handlers */
45 EXCEPTION_REGISTRATION_RECORD frame;
46 EXCEPTION_REGISTRATION_RECORD *prevFrame;
52 PVECTORED_EXCEPTION_HANDLER func;
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 };
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)
77 # error You must define GET_IP for this CPU
80 extern void DECLSPEC_NORETURN __wine_call_from_32_restore_regs( const CONTEXT *context );
82 /*******************************************************************
85 * Handler for exceptions happening inside a handler.
87 static DWORD EXC_RaiseHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
88 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
90 if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
91 return ExceptionContinueSearch;
92 /* We shouldn't get here so we store faulty frame in dispatcher */
93 *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
94 return ExceptionNestedException;
98 /*******************************************************************
101 * Handler for exceptions happening inside an unwind handler.
103 static DWORD EXC_UnwindHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
104 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
106 if (!(rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))
107 return ExceptionContinueSearch;
108 /* We shouldn't get here so we store faulty frame in dispatcher */
109 *dispatcher = ((EXC_NESTED_FRAME*)frame)->prevFrame;
110 return ExceptionCollidedUnwind;
114 /*******************************************************************
117 * Call an exception handler, setting up an exception frame to catch exceptions
118 * happening during the handler execution.
120 * For i386 this function is implemented in assembler in signal_i386.c.
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)
127 EXC_NESTED_FRAME newframe;
130 newframe.frame.Handler = nested_handler;
131 newframe.prevFrame = frame;
132 __wine_push_frame( &newframe.frame );
133 ret = handler( record, frame, context, dispatcher );
134 __wine_pop_frame( &newframe.frame );
138 /* in signal_i386.c */
139 extern DWORD EXC_CallHandler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
140 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher,
141 PEXCEPTION_HANDLER handler, PEXCEPTION_HANDLER nested_handler);
144 /**********************************************************************
147 * Wait until the thread is no longer suspended.
149 void wait_suspend( CONTEXT *context )
151 LARGE_INTEGER timeout;
153 /* store the context we got at suspend time */
154 SERVER_START_REQ( set_thread_context )
156 req->handle = GetCurrentThread();
157 req->flags = CONTEXT_FULL;
159 wine_server_add_data( req, context, sizeof(*context) );
160 wine_server_call( req );
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, 0, &timeout, 0 );
168 /* retrieve the new context */
169 SERVER_START_REQ( get_thread_context )
171 req->handle = GetCurrentThread();
172 req->flags = CONTEXT_FULL;
174 wine_server_set_reply( req, context, sizeof(*context) );
175 wine_server_call( req );
181 /**********************************************************************
184 * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
186 static NTSTATUS send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
191 if (!NtCurrentTeb()->Peb->BeingDebugged) return 0; /* no debugger present */
193 SERVER_START_REQ( queue_exception_event )
195 req->first = first_chance;
196 wine_server_add_data( req, context, sizeof(*context) );
197 wine_server_add_data( req, rec, sizeof(*rec) );
198 if (!wine_server_call( req )) handle = reply->handle;
201 if (!handle) return 0;
203 NTDLL_wait_for_multiple_objects( 1, &handle, 0, NULL, 0 );
205 SERVER_START_REQ( get_exception_status )
207 req->handle = handle;
208 wine_server_set_reply( req, context, sizeof(*context) );
209 ret = wine_server_call( req );
216 /**********************************************************************
217 * call_vectored_handlers
219 * Call the vectored handlers chain.
221 static LONG call_vectored_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
224 LONG ret = EXCEPTION_CONTINUE_SEARCH;
225 EXCEPTION_POINTERS except_ptrs;
227 except_ptrs.ExceptionRecord = rec;
228 except_ptrs.ContextRecord = context;
230 RtlEnterCriticalSection( &vectored_handlers_section );
231 LIST_FOR_EACH( ptr, &vectored_handlers )
233 VECTORED_HANDLER *handler = LIST_ENTRY( ptr, VECTORED_HANDLER, entry );
234 ret = handler->func( &except_ptrs );
235 if (ret == EXCEPTION_CONTINUE_EXECUTION) break;
237 RtlLeaveCriticalSection( &vectored_handlers_section );
242 /**********************************************************************
243 * call_stack_handlers
245 * Call the stack handlers chain.
247 static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
249 EXCEPTION_REGISTRATION_RECORD *frame, *dispatch, *nested_frame;
252 frame = NtCurrentTeb()->Tib.ExceptionList;
254 while (frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL)
256 /* Check frame address */
257 if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
258 ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
259 (ULONG_PTR)frame & 3)
261 rec->ExceptionFlags |= EH_STACK_INVALID;
266 TRACE( "calling handler at %p code=%lx flags=%lx\n",
267 frame->Handler, rec->ExceptionCode, rec->ExceptionFlags );
268 res = EXC_CallHandler( rec, frame, context, &dispatch, frame->Handler, EXC_RaiseHandler );
269 TRACE( "handler at %p returned %lx\n", frame->Handler, res );
271 if (frame == nested_frame)
273 /* no longer nested */
275 rec->ExceptionFlags &= ~EH_NESTED_CALL;
280 case ExceptionContinueExecution:
281 if (!(rec->ExceptionFlags & EH_NONCONTINUABLE)) return STATUS_SUCCESS;
282 return STATUS_NONCONTINUABLE_EXCEPTION;
283 case ExceptionContinueSearch:
285 case ExceptionNestedException:
286 if (nested_frame < dispatch) nested_frame = dispatch;
287 rec->ExceptionFlags |= EH_NESTED_CALL;
290 return STATUS_INVALID_DISPOSITION;
294 return STATUS_UNHANDLED_EXCEPTION;
298 /*******************************************************************
301 * Implementation of NtRaiseException.
303 static NTSTATUS raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
311 TRACE( "code=%lx flags=%lx addr=%p\n",
312 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
313 for (c = 0; c < rec->NumberParameters; c++)
314 TRACE( " info[%ld]=%08lx\n", c, rec->ExceptionInformation[c] );
315 if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
317 if (rec->ExceptionInformation[1] >> 16)
318 MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
319 rec->ExceptionAddress,
320 (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
322 MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
323 rec->ExceptionAddress,
324 (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
329 TRACE(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
330 context->Eax, context->Ebx, context->Ecx,
331 context->Edx, context->Esi, context->Edi );
332 TRACE(" ebp=%08lx esp=%08lx cs=%04lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
333 context->Ebp, context->Esp, context->SegCs, context->SegDs,
334 context->SegEs, context->SegFs, context->SegGs, context->EFlags );
337 status = send_debug_event( rec, TRUE, context );
338 if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
339 return STATUS_SUCCESS;
341 if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION)
342 return STATUS_SUCCESS;
344 if ((status = call_stack_handlers( rec, context )) != STATUS_UNHANDLED_EXCEPTION)
348 /* last chance exception */
350 status = send_debug_event( rec, FALSE, context );
351 if (status != DBG_CONTINUE)
353 if (rec->ExceptionFlags & EH_STACK_INVALID)
354 ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
355 else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
356 ERR("Process attempted to continue execution after noncontinuable exception.\n");
358 ERR("Unhandled exception code %lx flags %lx addr %p\n",
359 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
360 NtTerminateProcess( NtCurrentProcess(), 1 );
362 return STATUS_SUCCESS;
366 /*******************************************************************
367 * NtRaiseException (NTDLL.@)
369 NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
371 NTSTATUS status = raise_exception( rec, context, first_chance );
372 #ifdef DEFINE_REGS_ENTRYPOINT
373 if (status == STATUS_SUCCESS) __wine_call_from_32_restore_regs( context );
378 /***********************************************************************
379 * RtlRaiseException (NTDLL.@)
381 void WINAPI __regs_RtlRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context )
383 NTSTATUS status = raise_exception( rec, context, TRUE );
384 if (status != STATUS_SUCCESS)
386 EXCEPTION_RECORD newrec;
387 newrec.ExceptionCode = status;
388 newrec.ExceptionFlags = EH_NONCONTINUABLE;
389 newrec.ExceptionRecord = rec;
390 newrec.NumberParameters = 0;
391 RtlRaiseException( &newrec ); /* never returns */
395 /**********************************************************************/
397 #ifdef DEFINE_REGS_ENTRYPOINT
398 DEFINE_REGS_ENTRYPOINT( RtlRaiseException, 4, 4 );
400 void WINAPI RtlRaiseException( EXCEPTION_RECORD *rec )
403 memset( &context, 0, sizeof(context) );
404 __regs_RtlRaiseException( rec, &context );
409 /*******************************************************************
410 * RtlUnwind (NTDLL.@)
412 void WINAPI __regs_RtlUnwind( EXCEPTION_REGISTRATION_RECORD* pEndFrame, PVOID unusedEip,
413 PEXCEPTION_RECORD pRecord, PVOID returnEax, CONTEXT *context )
415 EXCEPTION_RECORD record, newrec;
416 EXCEPTION_REGISTRATION_RECORD *frame, *dispatch;
420 context->Eax = (DWORD)returnEax;
423 /* build an exception record, if we do not have one */
426 record.ExceptionCode = STATUS_UNWIND;
427 record.ExceptionFlags = 0;
428 record.ExceptionRecord = NULL;
429 record.ExceptionAddress = GET_IP(context);
430 record.NumberParameters = 0;
434 pRecord->ExceptionFlags |= EH_UNWINDING | (pEndFrame ? 0 : EH_EXIT_UNWIND);
436 TRACE( "code=%lx flags=%lx\n", pRecord->ExceptionCode, pRecord->ExceptionFlags );
438 /* get chain of exception frames */
439 frame = NtCurrentTeb()->Tib.ExceptionList;
440 while ((frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL) && (frame != pEndFrame))
442 /* Check frame address */
443 if (pEndFrame && (frame > pEndFrame))
445 newrec.ExceptionCode = STATUS_INVALID_UNWIND_TARGET;
446 newrec.ExceptionFlags = EH_NONCONTINUABLE;
447 newrec.ExceptionRecord = pRecord;
448 newrec.NumberParameters = 0;
449 RtlRaiseException( &newrec ); /* never returns */
451 if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
452 ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
455 newrec.ExceptionCode = STATUS_BAD_STACK;
456 newrec.ExceptionFlags = EH_NONCONTINUABLE;
457 newrec.ExceptionRecord = pRecord;
458 newrec.NumberParameters = 0;
459 RtlRaiseException( &newrec ); /* never returns */
463 TRACE( "calling handler at %p code=%lx flags=%lx\n",
464 frame->Handler, pRecord->ExceptionCode, pRecord->ExceptionFlags );
465 res = EXC_CallHandler( pRecord, frame, context, &dispatch, frame->Handler, EXC_UnwindHandler );
466 TRACE( "handler at %p returned %lx\n", frame->Handler, res );
470 case ExceptionContinueSearch:
472 case ExceptionCollidedUnwind:
476 newrec.ExceptionCode = STATUS_INVALID_DISPOSITION;
477 newrec.ExceptionFlags = EH_NONCONTINUABLE;
478 newrec.ExceptionRecord = pRecord;
479 newrec.NumberParameters = 0;
480 RtlRaiseException( &newrec ); /* never returns */
483 frame = __wine_pop_frame( frame );
487 /**********************************************************************/
489 #ifdef DEFINE_REGS_ENTRYPOINT
490 DEFINE_REGS_ENTRYPOINT( RtlUnwind, 16, 16 );
492 void WINAPI RtlUnwind( PVOID pEndFrame, PVOID unusedEip,
493 PEXCEPTION_RECORD pRecord, PVOID returnEax )
496 memset( &context, 0, sizeof(context) );
497 __regs_RtlUnwind( pEndFrame, unusedEip, pRecord, returnEax, &context );
502 /***********************************************************************
503 * RtlRaiseStatus (NTDLL.@)
505 * Raise an exception with ExceptionCode = status
507 void WINAPI RtlRaiseStatus( NTSTATUS status )
509 EXCEPTION_RECORD ExceptionRec;
511 ExceptionRec.ExceptionCode = status;
512 ExceptionRec.ExceptionFlags = EH_NONCONTINUABLE;
513 ExceptionRec.ExceptionRecord = NULL;
514 ExceptionRec.NumberParameters = 0;
515 RtlRaiseException( &ExceptionRec );
519 /*******************************************************************
520 * RtlAddVectoredExceptionHandler (NTDLL.@)
522 PVOID WINAPI RtlAddVectoredExceptionHandler( ULONG first, PVECTORED_EXCEPTION_HANDLER func )
524 VECTORED_HANDLER *handler = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*handler) );
527 handler->func = func;
528 RtlEnterCriticalSection( &vectored_handlers_section );
529 if (first) list_add_head( &vectored_handlers, &handler->entry );
530 else list_add_tail( &vectored_handlers, &handler->entry );
531 RtlLeaveCriticalSection( &vectored_handlers_section );
537 /*******************************************************************
538 * RtlRemoveVectoredExceptionHandler (NTDLL.@)
540 ULONG WINAPI RtlRemoveVectoredExceptionHandler( PVOID handler )
545 RtlEnterCriticalSection( &vectored_handlers_section );
546 LIST_FOR_EACH( ptr, &vectored_handlers )
548 VECTORED_HANDLER *curr_handler = LIST_ENTRY( ptr, VECTORED_HANDLER, entry );
549 if (curr_handler == handler)
556 RtlLeaveCriticalSection( &vectored_handlers_section );
557 if (ret) RtlFreeHeap( GetProcessHeap(), 0, handler );
562 /*************************************************************
563 * __wine_exception_handler (NTDLL.@)
565 * Exception handler for exception blocks declared in Wine code.
567 DWORD __wine_exception_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
568 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
570 __WINE_FRAME *wine_frame = (__WINE_FRAME *)frame;
572 if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND | EH_NESTED_CALL))
573 return ExceptionContinueSearch;
575 if (wine_frame->u.filter == (void *)1) /* special hack for page faults */
577 if (record->ExceptionCode != STATUS_ACCESS_VIOLATION)
578 return ExceptionContinueSearch;
580 else if (wine_frame->u.filter)
582 EXCEPTION_POINTERS ptrs;
583 ptrs.ExceptionRecord = record;
584 ptrs.ContextRecord = context;
585 switch(wine_frame->u.filter( &ptrs ))
587 case EXCEPTION_CONTINUE_SEARCH:
588 return ExceptionContinueSearch;
589 case EXCEPTION_CONTINUE_EXECUTION:
590 return ExceptionContinueExecution;
591 case EXCEPTION_EXECUTE_HANDLER:
594 MESSAGE( "Invalid return value from exception filter\n" );
598 /* hack to make GetExceptionCode() work in handler */
599 wine_frame->ExceptionCode = record->ExceptionCode;
600 wine_frame->ExceptionRecord = wine_frame;
602 RtlUnwind( frame, 0, record, 0 );
603 __wine_pop_frame( frame );
604 siglongjmp( wine_frame->jmp, 1 );
608 /*************************************************************
609 * __wine_finally_handler (NTDLL.@)
611 * Exception handler for try/finally blocks declared in Wine code.
613 DWORD __wine_finally_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
614 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
616 if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
618 __WINE_FRAME *wine_frame = (__WINE_FRAME *)frame;
619 wine_frame->u.finally_func( FALSE );
621 return ExceptionContinueSearch;
625 /*************************************************************
626 * __wine_spec_unimplemented_stub
628 * ntdll-specific implementation to avoid depending on kernel functions.
629 * Can be removed once ntdll.spec no longer contains stubs.
631 void __wine_spec_unimplemented_stub( const char *module, const char *function )
633 EXCEPTION_RECORD record;
635 record.ExceptionCode = EXCEPTION_WINE_STUB;
636 record.ExceptionFlags = EH_NONCONTINUABLE;
637 record.ExceptionRecord = NULL;
638 record.ExceptionAddress = __wine_spec_unimplemented_stub;
639 record.NumberParameters = 2;
640 record.ExceptionInformation[0] = (ULONG_PTR)module;
641 record.ExceptionInformation[1] = (ULONG_PTR)function;
642 RtlRaiseException( &record );