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
23 #include "wine/port.h"
31 #define WIN32_NO_STATUS
34 #include "wine/exception.h"
35 #include "wine/server.h"
36 #include "wine/list.h"
37 #include "wine/debug.h"
39 #include "ntdll_misc.h"
41 WINE_DEFAULT_DEBUG_CHANNEL(seh);
43 /* Exception record for handling exceptions happening inside exception handlers */
46 EXCEPTION_REGISTRATION_RECORD frame;
47 EXCEPTION_REGISTRATION_RECORD *prevFrame;
53 PVECTORED_EXCEPTION_HANDLER func;
56 static struct list vectored_handlers = LIST_INIT(vectored_handlers);
58 static RTL_CRITICAL_SECTION vectored_handlers_section;
59 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
61 0, 0, &vectored_handlers_section,
62 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
63 0, 0, { (DWORD_PTR)(__FILE__ ": vectored_handlers_section") }
65 static RTL_CRITICAL_SECTION vectored_handlers_section = { &critsect_debug, -1, 0, 0, 0, 0 };
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)
78 # error You must define GET_IP for this CPU
81 /*******************************************************************
84 * Handler for exceptions happening inside a handler.
86 static DWORD EXC_RaiseHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
87 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
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;
97 /*******************************************************************
100 * Handler for exceptions happening inside an unwind handler.
102 static DWORD EXC_UnwindHandler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
103 CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
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;
113 /*******************************************************************
116 * Call an exception handler, setting up an exception frame to catch exceptions
117 * happening during the handler execution.
119 * For i386 this function is implemented in assembler in signal_i386.c.
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)
126 EXC_NESTED_FRAME newframe;
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 );
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);
143 /**********************************************************************
146 * Wait until the thread is no longer suspended.
148 void wait_suspend( CONTEXT *context )
150 LARGE_INTEGER timeout;
151 int saved_errno = errno;
152 context_t server_context;
154 context_to_server( &server_context, context );
156 /* store the context we got at suspend time */
157 SERVER_START_REQ( set_thread_context )
159 req->handle = wine_server_obj_handle( GetCurrentThread() );
161 wine_server_add_data( req, &server_context, sizeof(server_context) );
162 wine_server_call( req );
166 /* wait with 0 timeout, will only return once the thread is no longer suspended */
167 timeout.QuadPart = 0;
168 NTDLL_wait_for_multiple_objects( 0, NULL, SELECT_INTERRUPTIBLE, &timeout, 0 );
170 /* retrieve the new context */
171 SERVER_START_REQ( get_thread_context )
173 req->handle = wine_server_obj_handle( GetCurrentThread() );
175 wine_server_set_reply( req, &server_context, sizeof(server_context) );
176 wine_server_call( req );
180 context_from_server( context, &server_context );
185 /**********************************************************************
188 * Send an EXCEPTION_DEBUG_EVENT event to the debugger.
190 static NTSTATUS send_debug_event( EXCEPTION_RECORD *rec, int first_chance, CONTEXT *context )
195 client_ptr_t params[EXCEPTION_MAXIMUM_PARAMETERS];
196 context_t server_context;
198 if (!NtCurrentTeb()->Peb->BeingDebugged) return 0; /* no debugger present */
200 for (i = 0; i < min( rec->NumberParameters, EXCEPTION_MAXIMUM_PARAMETERS ); i++)
201 params[i] = rec->ExceptionInformation[i];
203 context_to_server( &server_context, context );
205 SERVER_START_REQ( queue_exception_event )
207 req->first = first_chance;
208 req->code = rec->ExceptionCode;
209 req->flags = rec->ExceptionFlags;
210 req->record = wine_server_client_ptr( rec->ExceptionRecord );
211 req->address = wine_server_client_ptr( rec->ExceptionAddress );
212 req->len = i * sizeof(params[0]);
213 wine_server_add_data( req, params, req->len );
214 wine_server_add_data( req, &server_context, sizeof(server_context) );
215 if (!wine_server_call( req )) handle = wine_server_ptr_handle( reply->handle );
218 if (!handle) return 0;
220 NTDLL_wait_for_multiple_objects( 1, &handle, SELECT_INTERRUPTIBLE, NULL, 0 );
222 SERVER_START_REQ( get_exception_status )
224 req->handle = wine_server_obj_handle( handle );
225 wine_server_set_reply( req, &server_context, sizeof(server_context) );
226 ret = wine_server_call( req );
229 if (ret >= 0) context_from_server( context, &server_context );
234 /**********************************************************************
235 * call_vectored_handlers
237 * Call the vectored handlers chain.
239 static LONG call_vectored_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
242 LONG ret = EXCEPTION_CONTINUE_SEARCH;
243 EXCEPTION_POINTERS except_ptrs;
245 except_ptrs.ExceptionRecord = rec;
246 except_ptrs.ContextRecord = context;
248 RtlEnterCriticalSection( &vectored_handlers_section );
249 LIST_FOR_EACH( ptr, &vectored_handlers )
251 VECTORED_HANDLER *handler = LIST_ENTRY( ptr, VECTORED_HANDLER, entry );
252 TRACE( "calling handler at %p code=%x flags=%x\n",
253 handler->func, rec->ExceptionCode, rec->ExceptionFlags );
254 ret = handler->func( &except_ptrs );
255 TRACE( "handler at %p returned %x\n", handler->func, ret );
256 if (ret == EXCEPTION_CONTINUE_EXECUTION) break;
258 RtlLeaveCriticalSection( &vectored_handlers_section );
263 /**********************************************************************
264 * call_stack_handlers
266 * Call the stack handlers chain.
268 static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
270 EXCEPTION_REGISTRATION_RECORD *frame, *dispatch, *nested_frame;
273 frame = NtCurrentTeb()->Tib.ExceptionList;
275 while (frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL)
277 /* Check frame address */
278 if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
279 ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
280 (ULONG_PTR)frame & 3)
282 rec->ExceptionFlags |= EH_STACK_INVALID;
287 TRACE( "calling handler at %p code=%x flags=%x\n",
288 frame->Handler, rec->ExceptionCode, rec->ExceptionFlags );
289 res = EXC_CallHandler( rec, frame, context, &dispatch, frame->Handler, EXC_RaiseHandler );
290 TRACE( "handler at %p returned %x\n", frame->Handler, res );
292 if (frame == nested_frame)
294 /* no longer nested */
296 rec->ExceptionFlags &= ~EH_NESTED_CALL;
301 case ExceptionContinueExecution:
302 if (!(rec->ExceptionFlags & EH_NONCONTINUABLE)) return STATUS_SUCCESS;
303 return STATUS_NONCONTINUABLE_EXCEPTION;
304 case ExceptionContinueSearch:
306 case ExceptionNestedException:
307 if (nested_frame < dispatch) nested_frame = dispatch;
308 rec->ExceptionFlags |= EH_NESTED_CALL;
311 return STATUS_INVALID_DISPOSITION;
315 return STATUS_UNHANDLED_EXCEPTION;
319 /*******************************************************************
322 * Implementation of NtRaiseException.
324 NTSTATUS raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
332 TRACE( "code=%x flags=%x addr=%p ip=%p tid=%04x\n",
333 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress,
334 GET_IP(context), GetCurrentThreadId() );
335 for (c = 0; c < rec->NumberParameters; c++)
336 TRACE( " info[%d]=%08lx\n", c, rec->ExceptionInformation[c] );
337 if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
339 if (rec->ExceptionInformation[1] >> 16)
340 MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
341 rec->ExceptionAddress,
342 (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
344 MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
345 rec->ExceptionAddress,
346 (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
351 TRACE(" eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n",
352 context->Eax, context->Ebx, context->Ecx,
353 context->Edx, context->Esi, context->Edi );
354 TRACE(" ebp=%08x esp=%08x cs=%04x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
355 context->Ebp, context->Esp, context->SegCs, context->SegDs,
356 context->SegEs, context->SegFs, context->SegGs, context->EFlags );
357 #elif defined(__x86_64__)
358 TRACE(" rax=%016lx rbx=%016lx rcx=%016lx rdx=%016lx\n",
359 context->Rax, context->Rbx, context->Rcx, context->Rdx );
360 TRACE(" rsi=%016lx rdi=%016lx rbp=%016lx rsp=%016lx\n",
361 context->Rsi, context->Rdi, context->Rbp, context->Rsp );
362 TRACE(" r8=%016lx r9=%016lx r10=%016lx r11=%016lx\n",
363 context->R8, context->R9, context->R10, context->R11 );
364 TRACE(" r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n",
365 context->R12, context->R13, context->R14, context->R15 );
368 status = send_debug_event( rec, TRUE, context );
369 if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
370 return STATUS_SUCCESS;
373 /* fix up instruction pointer in context for EXCEPTION_BREAKPOINT */
374 if (rec->ExceptionCode == EXCEPTION_BREAKPOINT) context->Eip--;
377 if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION)
378 return STATUS_SUCCESS;
380 if ((status = call_stack_handlers( rec, context )) != STATUS_UNHANDLED_EXCEPTION)
384 /* last chance exception */
386 status = send_debug_event( rec, FALSE, context );
387 if (status != DBG_CONTINUE)
389 if (rec->ExceptionFlags & EH_STACK_INVALID)
390 ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
391 else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
392 ERR("Process attempted to continue execution after noncontinuable exception.\n");
394 ERR("Unhandled exception code %x flags %x addr %p\n",
395 rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
396 NtTerminateProcess( NtCurrentProcess(), 1 );
398 return STATUS_SUCCESS;
402 /*******************************************************************
403 * NtRaiseException (NTDLL.@)
405 NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
407 NTSTATUS status = raise_exception( rec, context, first_chance );
408 if (status == STATUS_SUCCESS) NtSetContextThread( GetCurrentThread(), context );
413 /*******************************************************************
416 * Implementation of RtlRaiseStatus with a specific exception record.
418 void raise_status( NTSTATUS status, EXCEPTION_RECORD *rec )
420 EXCEPTION_RECORD ExceptionRec;
422 ExceptionRec.ExceptionCode = status;
423 ExceptionRec.ExceptionFlags = EH_NONCONTINUABLE;
424 ExceptionRec.ExceptionRecord = rec;
425 ExceptionRec.NumberParameters = 0;
426 for (;;) RtlRaiseException( &ExceptionRec ); /* never returns */
430 /*******************************************************************
431 * RtlUnwind (NTDLL.@)
433 void WINAPI __regs_RtlUnwind( EXCEPTION_REGISTRATION_RECORD* pEndFrame, PVOID unusedEip,
434 PEXCEPTION_RECORD pRecord, PVOID returnEax, CONTEXT *context )
436 EXCEPTION_RECORD record;
437 EXCEPTION_REGISTRATION_RECORD *frame, *dispatch;
441 context->Eax = (DWORD)returnEax;
444 /* build an exception record, if we do not have one */
447 record.ExceptionCode = STATUS_UNWIND;
448 record.ExceptionFlags = 0;
449 record.ExceptionRecord = NULL;
450 record.ExceptionAddress = GET_IP(context);
451 record.NumberParameters = 0;
455 pRecord->ExceptionFlags |= EH_UNWINDING | (pEndFrame ? 0 : EH_EXIT_UNWIND);
457 TRACE( "code=%x flags=%x\n", pRecord->ExceptionCode, pRecord->ExceptionFlags );
459 /* get chain of exception frames */
460 frame = NtCurrentTeb()->Tib.ExceptionList;
461 while ((frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL) && (frame != pEndFrame))
463 /* Check frame address */
464 if (pEndFrame && (frame > pEndFrame))
465 raise_status( STATUS_INVALID_UNWIND_TARGET, pRecord );
467 if (((void*)frame < NtCurrentTeb()->Tib.StackLimit) ||
468 ((void*)(frame+1) > NtCurrentTeb()->Tib.StackBase) ||
470 raise_status( STATUS_BAD_STACK, pRecord );
473 TRACE( "calling handler at %p code=%x flags=%x\n",
474 frame->Handler, pRecord->ExceptionCode, pRecord->ExceptionFlags );
475 res = EXC_CallHandler( pRecord, frame, context, &dispatch, frame->Handler, EXC_UnwindHandler );
476 TRACE( "handler at %p returned %x\n", frame->Handler, res );
480 case ExceptionContinueSearch:
482 case ExceptionCollidedUnwind:
486 raise_status( STATUS_INVALID_DISPOSITION, pRecord );
489 frame = __wine_pop_frame( frame );
493 /**********************************************************************/
495 #ifdef DEFINE_REGS_ENTRYPOINT
496 DEFINE_REGS_ENTRYPOINT( RtlUnwind, 4 )
498 void WINAPI RtlUnwind( PVOID pEndFrame, PVOID unusedEip,
499 PEXCEPTION_RECORD pRecord, PVOID returnEax )
502 RtlCaptureContext( &context );
503 __regs_RtlUnwind( pEndFrame, unusedEip, pRecord, returnEax, &context );
508 /***********************************************************************
509 * RtlRaiseStatus (NTDLL.@)
511 * Raise an exception with ExceptionCode = status
513 void WINAPI RtlRaiseStatus( NTSTATUS status )
515 raise_status( status, NULL );
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 * RtlCaptureStackBackTrace [NTDLL.@]
565 * Captures stack backtrace
568 * Skip [I] Number of stack frames to skip before starting a capture
569 * Count [I] Number of stack frames to capture into Buffer
570 * Buffer [O] Array of backtrace pointers captured from stack
571 * Hash [O] Optional pointer to variable where backtrace hash should be stored
574 * Number of captured stack frames or 0 if error occurred
579 USHORT WINAPI RtlCaptureStackBackTrace(ULONG Skip, ULONG Count, PVOID *Buffer, ULONG *Hash)
581 FIXME("(%d, %d, %p, %p) stub!\n", Skip, Count, Buffer, Hash);
586 /*************************************************************
587 * __wine_spec_unimplemented_stub
589 * ntdll-specific implementation to avoid depending on kernel functions.
590 * Can be removed once ntdll.spec no longer contains stubs.
592 void __wine_spec_unimplemented_stub( const char *module, const char *function )
594 EXCEPTION_RECORD record;
596 record.ExceptionCode = EXCEPTION_WINE_STUB;
597 record.ExceptionFlags = EH_NONCONTINUABLE;
598 record.ExceptionRecord = NULL;
599 record.ExceptionAddress = __wine_spec_unimplemented_stub;
600 record.NumberParameters = 2;
601 record.ExceptionInformation[0] = (ULONG_PTR)module;
602 record.ExceptionInformation[1] = (ULONG_PTR)function;
603 for (;;) RtlRaiseException( &record );